diff --git a/.github/workflows/create-cherry-pick-pr.yml b/.github/workflows/create-cherry-pick-pr.yml index edeec25e8f3..cc4d1abdb06 100644 --- a/.github/workflows/create-cherry-pick-pr.yml +++ b/.github/workflows/create-cherry-pick-pr.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: branch_name: - description: 'Target branch name to merge the cherry-picked branch into' + description: 'Branch name you want the cherry-pick branch to be based from' required: true commit_hash: description: 'Commit Hash' diff --git a/.github/workflows/security-code-scanner.yml b/.github/workflows/security-code-scanner.yml deleted file mode 100644 index 729f6f4e31e..00000000000 --- a/.github/workflows/security-code-scanner.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: "MetaMask Security Code Scanner" - -on: - push: - branches: ["main"] - pull_request: - branches: ["main"] - -jobs: - run-security-scan: - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - steps: - - name: MetaMask Security Code Scanner - uses: MetaMask/Security-Code-Scanner@main - with: - repo: ${{ github.repository }} - paths_ignored: | - e2e/ - docs/ - storybook/ - .storybook/ - '**/*.test.js' - '**/*.test.ts' - '**/*.test.jsx' - '**/*.test.tsx' - '**/*.stories.tsx' - '**/*.stories.js' - '**/*.snap' - rules_excluded: example - mixpanel_project_token: ${{secrets.SECURITY_CODE_SCANNER_MIXPANEL_TOKEN}} - slack_webhook: ${{ secrets.APPSEC_BOT_SLACK_WEBHOOK }} diff --git a/.js.env.example b/.js.env.example index 6a76c00af6c..fd36d5d5e62 100644 --- a/.js.env.example +++ b/.js.env.example @@ -53,10 +53,4 @@ export WATCHER_PORT=8081 export METAMASK_ENVIRONMENT="" # Build type: "main" or "flask" -export METAMASK_BUILD_TYPE="" - -# Segment SDK proxy endpoint and write key -export SEGMENT_WRITE_KEY="" -export SEGMENT_PROXY_URL="" -export SEGMENT_DELETE_API_SOURCE_ID="" -export SEGMENT_REGULATIONS_ENDPOINT="" +export METAMASK_BUILD_TYPE="" \ No newline at end of file diff --git a/README.md b/README.md index 9c942d7a561..f6e20357017 100644 --- a/README.md +++ b/README.md @@ -10,59 +10,365 @@ For up to the minute news, follow our [Twitter](https://twitter.com/metamask) or To learn how to develop MetaMask-compatible applications, visit our [Developer Docs](https://docs.metamask.io). -## Documentation -- [Architecture](./docs/readme/architecture.md) -- [Development Environment Setup](./docs/readme/environment.md) -- [Build Troubleshooting](./docs/readme/troubleshooting.md) -- [Testing](./docs/readme/testing.md) -- [Debugging](./docs/readme/debugging.md) -- [Storybook](./docs/readme/storybook.md) -- [Miscellaneous](./docs/readme/miscellaneous.md) +## MetaMask Mobile -## Getting started +### Environment Setup -### Environment setup +The code is built using React-Native and running code locally requires a Mac or Linux OS. -Before running the app, make sure your development environment has all the required tools. +- Install [sentry-cli](https://github.com/getsentry/sentry-cli) tools: `brew install getsentry/tools/sentry-cli` -[Setup your development environment](./docs/readme/environment.md) +<<<<<<< HEAD +- Install [Node.js](https://nodejs.org) **version 18** +======= + - Auto upload for source maps and debug files is disabled by default. To enable it, set the `SENTRY_DISABLE_AUTO_UPLOAD` environment variable to `false`. +>>>>>>> 7c51abce6 (fix: Fix/8352 source map stack trace (#8509)) -### Building the app +- Install [Node.js](https://nodejs.org) **version 18.18** + + - If you are using [nvm](https://github.com/creationix/nvm#installation) (recommended) running `nvm use` will automatically choose the right node version for you. + +- Install [Yarn v1](https://yarnpkg.com/en/docs/install) + + One way to install Yarn v1 is by using brew: + + ```bash + brew install yarn@1.22.19 + ``` + +<<<<<<< HEAD +- Install the shared [React Native dependencies](https://reactnative.dev/docs/environment-setup#installing-dependencies) (`React Native CLI`, _not_ `Expo CLI`) + - XCode version `15.0.1` or below +======= + To check you've installed the right version: +>>>>>>> 7c51abce6 (fix: Fix/8352 source map stack trace (#8509)) + + ```bash + yarn --version + ``` + +- Install the shared [React Native dependencies](https://reactnative.dev/docs/environment-setup#installing-dependencies) (`React Native CLI`, _not_ `Expo CLI`) + + +- Install [cocoapods](https://guides.cocoapods.org/using/getting-started.html) by running: + + ```bash + sudo gem install cocoapods -v 1.12.1 + ``` + +- Install [Python](https://www.python.org/downloads/) **version ^3.10** + - _Note_: M1 User might need to stay with **version 3.10** + +### Device Environment Setup + +#### Android + +- Install [Java](https://www.java.com/en/download/). To check if Java is already installed, run: + ``` + java -version + ``` +- Install the Android SDK, via [Android Studio](https://developer.android.com/studio). + - _MetaMask Only:_ To create production builds, you need to install Google Play Licensing Library via the SDK Manager in Android Studio. +- Install the Android NDK (version `21.4.7075529`), via [Android Studio](https://developer.android.com/studio)'s SDK Manager. + - Go to Settings > Appearance & Behavior > System Settings > Android SDK + - Shortcut: Selecting `More Actions` > `SDK Manager` from the "Welcome to Android Studio" page will also bring you here. + - Select `SDK Tools` tab + - Check `Show Package Details` option below the tools list to show available versions + - Locate `NDK (Side-by-side)` option in the tools list + - Check NDK version `21.4.7075529` + - Locate `CMake` option in the tools list + - Check CMake version `3.22.1` + - Click "Apply" or "OK" to download +- Linux only: + - Ensure that you have the `secret-tool` binary on your machine. + - Part of the [libsecret-tools](https://launchpad.net/ubuntu/bionic/+package/libsecret-tools) package on Debian/Ubuntu based distributions. +- Install the correct emulator + - Follow the instructions at: + - [React Native Getting Started - Android](https://reactnative.dev/docs/environment-setup#installing-dependencies) _(React Native CLI Quickstart -> [your OS] -> Android)_ + - FYI: as of today (7/18/23) there is currently an issue when running detox on android 12 and 13 (API 32/33) which prevents the tests from running. The issue is, the tap() action is treated like a tapAndHold() action. See the open issue in wix/detox [here](https://github.com/wix/Detox/issues/3762) + - More details can be found [on the Android Developer site](https://developer.android.com/studio/run/emulator) + - You should use the following: + - **Android OS Version:** Latest, unless told otherwise + - **Device:** Google Pixel 5 +- Finally, start the emulator from Android Studio: + - Open "Virtual Device Manager" + - Launch emulator for "Pixel 5 " + +#### iOS + +- Install the iOS dependencies + - [React Native Getting Started - iOS](https://reactnative.dev/docs/environment-setup#installing-dependencies) _(React Native CLI Quickstart -> [your OS] -> iOS)_ +- Install the correct simulator + - **iOS OS Version:** Latest, unless told otherwise + - **Device:** iPhone 13 Pro + +### Building Locally + +- Clone this repo: -**Clone the project** ```bash -git clone git@github.com:MetaMask/metamask-mobile.git && \ +git clone ... cd metamask-mobile ``` -**Install dependencies** +- _MetaMask Only:_ Rename the `.*.env.example` files (remove the `.example`) in the root of the project and fill in the appropriate values for each key. Get the values from another MetaMask Mobile developer. +- _Non-MetaMask Only:_ In the project root folder run +- If you intend to use WalletConnect v2 during your development, you should register to get a projectId from WalletConnect website and set the `WALLET_CONNECT_PROJECT_ID` value accordingly in .js.env file. + +``` + cp .ios.env.example .ios.env && \ + cp .android.env.example .android.env && \ + cp .js.env.example .js.env +``` + +- _Non-MetaMask Only:_ Create an account and generate your own API key at [Infura](https://infura.io) in order to connect to main and test nets. Fill `MM_INFURA_PROJECT_ID` in `.js.env`. (App will run without it, but will not be able to connect to actual network.) +- _Non-MetaMask Only:_ Fill `MM_SENTRY_DSN` in `.js.env` if you want the app to emit logs to your own Sentry project. +- Note: after updating env vars, make sure to run `source .js.env` on the root of the project + +- Install the app: + +``` +yarn setup # not the usual install command, this will run a lengthy postinstall flow +``` + +- Then, in one terminal, run: ```bash -yarn setup +yarn watch ``` -_Not the usual install command, this will run scripts and a lengthy postinstall flow_ -**Setup environment variables** +- You can change the default port (8081) from metro using the WATCHER_PORT environment variable. For example: + ```bash -cp .ios.env.example .ios.env && \ -cp .android.env.example .android.env && \ -cp .js.env.example .js.env +WATCHER_PORT=8082 yarn watch +# This value can also be set directly inside .js.env file ``` -### Running the app +#### Android -**Run Metro bundler** ```bash -yarn watch +yarn start:android ``` -_Like a local server for the app_ -**Run on a iOS device** +#### iOS + ```bash -yarn start:ios +yarn start:ios ``` -**Run on an Android device** +#### Build Troubleshooting + +Unfortunately, the build system may fail to pick up local changes, such as installing new NPM packages or `yarn link`ing a dependency. +If the app is behaving strangely or not picking up your local changes, it may be due to build issues. +To ensure that you're starting with a clean slate, close all emulators/simulators, stop the `yarn watch` process, and run: + ```bash +yarn clean + +# if you're going to `yarn link` any packages, +# do that here, before the next command + +yarn watch:clean + +# ...and then, in another terminal + +yarn start:ios + +# or + yarn start:android ``` + +If `yarn link` fails after going through these steps, try directly `yarn add`ing the local files instead. + +### Debugging + +First, make sure you have the following running: + +- `yarn watch` +- Your Android emulator or iOS simulator +- `yarn start:android` or `yarn start:ios` + +Next, install the [Flipper](https://fbflipper.com/) desktop app (verified working with v0.127.0) + +- Once Flipper is installed, configure your system as follows: + - Install react-devtools: `npm i -g react-devtools@4.22.1` + - Update Android SDK location settings by accessing Flipper's settings via the `Gear Icon` -> `Settings` + - Example SDK path: `/Users//Library/Android/sdk` + +Finally, check that the debugger is working: + +- Open your emulator or simulator alongside the Flipper app +- Flipper should auto-detect the device and the application to debug +- You should now be able to access features such as `Logs` + +#### Debugging Physical iOS devices + +- Debugging physical iOS devices requires `idb` to be installed, which consists of 2 parts +- Install the two idb parts: + 1. `brew tap facebook/fb` & `brew install idb-companion` + 2. `pip3.9 install fb-idb` (This step may require that you install python3 via `python -m pip3 install --upgrade pip`) + +#### Debug a website inside the WebView (in-app browser) + +Android + +- Run the app in debug mode (for example, in a simulator) +- Open Chrome on your desktop +- Go to `chrome://inspect/#devices` +- Look for the device and click inspect + +iOS + +- Run the app in debug mode (for example, in a simulator) +- Open Safari on your desktop +- Go to the menu Develop -> [Your device] -> [Website] + +You should see the console for the website that is running inside the WebView + +#### Miscellaneous + +- [Troubleshooting for React Native](https://facebook.github.io/react-native/docs/troubleshooting#content) +- [Flipper Documentation](https://fbflipper.com/docs/features/react-native/) + +### Running Tests + +#### Unit Tests + +```bash +yarn test:unit +``` + +#### E2E Tests + +##### Platforms + +For both iOS and Android platforms, our chosen E2E test framework is Detox. We also utilize Appium for Android (wdio folder). + +##### Test wallet + +E2E tests use a wallet able to access testnet and mainnet. +On Bitrise CI, the wallet is created using the secret recovery phrase from secret env var. +For local testing, the wallet is created using the secret recovery phrase from the `.e2e.env` file. + +##### Detox + +All tests live within the e2e/specs folder. + +### iOS + +Prerequisites for running tests: + +- Make sure to install `detox-cli` by referring to the instructions mentioned [here](https://wix.github.io/Detox/docs/introduction/getting-started/#detox-prerequisites). +- Additionally, install `applesimutils` by following the guidelines provided [here](https://github.com/wix/AppleSimulatorUtils). +- Before running any tests, it's recommended to refer to the `iOS section` above and check the latest simulator device specified under `Install the correct simulator`. +- The default device for iOS is the iPhone 13 Pro and Android the Pixel 5. Ensure you have these set up. +- Make sure that Metro is running. Use this command to launch the metro server: + +```bash +yarn watch +``` + +You can trigger the tests against a `release` or `debug` build. It recommended that you trigger the tests against a debug build. + +To trigger the tests on a debug build run this command: + +For iOS + +```bash +yarn test:e2e:ios:debug +``` + +and on Android: + +```bash +yarn test:e2e:android:debug +``` + +If you choose to run tests against a release build, you can do so by running this command: + +For iOS + +```bash +yarn test:e2e:ios +``` + +and on Android: + +```bash +yarn test:e2e:android +``` + +If you have already built the application for Detox and want to run a specific test from the test folder, you can use this command: + +For iOS + +```bash +yarn test:e2e:ios:debug:single e2e/specs/TEST_NAME.spec.js +``` + +and on Android: + +```bash +yarn test:e2e:android:debug:single e2e/specs/TEST_NAME.spec.js +``` + +To run tests associated with a certain tag, you can do so using the `--testNamePattern` flag. For example: + +```bash +yarn test:e2e:ios:debug --testNamePattern="Smoke" +``` + +```bash +yarn test:e2e:android:debug --testNamePattern="Smoke" +``` + +This runs all tests that are tagged "Smoke" + +##### Appium + +The appium tests lives within the wdio/feature folder. + +By default the tests use an avd named `Android 11 - Pixel 4a API 31`, with API `Level 30` (Android 11). You can modify the emulator and platform version by navigating to `wdio/config/android.config.debug.js` and adjusting the values of `deviceName` to match your emulator's name, and `platformVersion` to match your operating system's version. Make sure to verify that the config file accurately represents your emulator settings before executing any tests. + +The sequence in which you should run tests: + +create a test build using this command: + +```bash +yarn start:android:qa +``` + +Then run tests using this command: + +```bash +yarn test:wdio:android +``` + +If you want to run a specific test, you can include the `--spec` flag in the aforementioned command. For example: + +```bash +yarn test:wdio:android --spec ./wdio/features/Onboarding/CreateNewWallet.feature +``` + +### Changing dependencies + +Whenever you change dependencies (adding, removing, or updating, either in `package.json` or `yarn.lock`), there are various files that must be kept up-to-date. + +- `yarn.lock`: + - Run `yarn setup` again after your changes to ensure `yarn.lock` has been properly updated. +- The `allow-scripts` configuration in `package.json` + - Run `yarn allow-scripts auto` to update the `allow-scripts` configuration automatically. This config determines whether the package's install/postinstall scripts are allowed to run. Review each new package to determine whether the install script needs to run or not, testing if necessary. + - Unfortunately, `yarn allow-scripts auto` will behave inconsistently on different platforms. macOS and Windows users may see extraneous changes relating to optional dependencies. + +### Architecture + +To get a better understanding of the internal architecture of this app take a look at [this diagram](https://github.com/MetaMask/metamask-mobile/blob/main/architecture.svg). + +### Storybook + +We have begun documenting our components using Storybook. Please read the [Documentation Guidelines](./storybook/DOCUMENTATION_GUIDELINES.md) to get up and running. + +### Other Docs + +- [Adding Confirmations](./docs/confirmations.md) diff --git a/app/actions/browser/index.js b/app/actions/browser/index.js index 64c3a2fd522..0f63d097776 100644 --- a/app/actions/browser/index.js +++ b/app/actions/browser/index.js @@ -1,23 +1,3 @@ -/** - * Browser actions for Redux - */ -export const BrowserActionTypes = { - ADD_TO_VISITED_DAPP: 'ADD_TO_VISITED_DAPP', -}; - -/** - * Adds a new entry to visited dapps - * - * @param {string} hostname - Dapp hostname - * @returns - */ -export function addToVisitedDapp(hostname) { - return { - type: BrowserActionTypes.ADD_TO_VISITED_DAPP, - hostname, - }; -} - /** * Adds a new entry to the browser history * diff --git a/app/actions/settings/index.js b/app/actions/settings/index.js index ea64074d2d1..d4a3bb39fc7 100644 --- a/app/actions/settings/index.js +++ b/app/actions/settings/index.js @@ -46,3 +46,10 @@ export function setUseBlockieIcon(useBlockieIcon) { useBlockieIcon, }; } + +export function setLedgerBetaEnabled(ledgerBetaEnabled) { + return { + type: 'SET_LEDGER_BETA_ENABLED', + ledgerBetaEnabled, + }; +} diff --git a/app/actions/signatureRequest/index.ts b/app/actions/signatureRequest/index.ts index db042fef16d..c29eb5c217d 100644 --- a/app/actions/signatureRequest/index.ts +++ b/app/actions/signatureRequest/index.ts @@ -1,4 +1,4 @@ -import { SecurityAlertResponse } from '../../components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.types'; +import { SecurityAlertResponse } from '../../components/UI/BlockaidBanner/BlockaidBanner.types'; /** * Clears transaction object completely diff --git a/app/analytics/index.test.ts b/app/analytics/index.test.ts deleted file mode 100644 index fc3a9f375de..00000000000 --- a/app/analytics/index.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { trackDappVisitedEvent } from './index'; -import { MetaMetricsEvents } from '../core/Analytics'; -import AnalyticsV2 from '../util/analyticsV2'; - -// Mock AnalyticsV2 -jest.mock('../util/analyticsV2', () => ({ - trackEvent: jest.fn(), -})); - -// Mock store.getState -let mockGetState: jest.Mock; -jest.mock('../store', () => { - mockGetState = jest.fn(); - mockGetState.mockImplementation(() => ({ - browser: { - visitedDappsByHostname: {}, - }, - engine: { - backgroundState: { - PreferencesController: { - identities: { '0x1': true, '0x2': true }, - }, - }, - }, - })); - - return { - store: { - getState: mockGetState, - dispatch: jest.fn(), - }, - }; -}); - -describe('trackDappVisitedEvent', () => { - afterEach(() => { - jest.resetAllMocks(); - }); - - it('should track with isFirstVisit = true', () => { - mockGetState.mockImplementation(() => ({ - browser: { - visitedDappsByHostname: {}, - }, - engine: { - backgroundState: { - PreferencesController: { - identities: { '0x1': true, '0x2': true }, - }, - }, - }, - })); - - const expectedMetrics = { - is_first_visit: true, - number_of_accounts: 2, - number_of_accounts_connected: 1, - source: 'in-app browser', - }; - - trackDappVisitedEvent({ - hostname: 'uniswap.org', - numberOfConnectedAccounts: 1, - }); - - expect(AnalyticsV2.trackEvent).toBeCalledWith( - MetaMetricsEvents.DAPP_VISITED, - expectedMetrics, - ); - }); - - it('should track with isFirstVisit = false', () => { - mockGetState.mockImplementation(() => ({ - browser: { - visitedDappsByHostname: { 'uniswap.org': true }, - }, - engine: { - backgroundState: { - PreferencesController: { - identities: { '0x1': true, '0x2': true }, - }, - }, - }, - })); - - const expectedMetrics = { - is_first_visit: false, - number_of_accounts: 2, - number_of_accounts_connected: 1, - source: 'in-app browser', - }; - - trackDappVisitedEvent({ - hostname: 'uniswap.org', - numberOfConnectedAccounts: 1, - }); - - expect(AnalyticsV2.trackEvent).toBeCalledWith( - MetaMetricsEvents.DAPP_VISITED, - expectedMetrics, - ); - }); - - it('should track with the correct number of connected accounts', () => { - mockGetState.mockImplementation(() => ({ - browser: { - visitedDappsByHostname: { 'uniswap.org': true }, - }, - engine: { - backgroundState: { - PreferencesController: { - identities: { '0x1': true, '0x2': true }, - }, - }, - }, - })); - - const expectedMetrics = { - is_first_visit: false, - number_of_accounts: 2, - number_of_accounts_connected: 1, - source: 'in-app browser', - }; - - trackDappVisitedEvent({ - hostname: 'uniswap.org', - numberOfConnectedAccounts: 1, - }); - - expect(AnalyticsV2.trackEvent).toBeCalledWith( - MetaMetricsEvents.DAPP_VISITED, - expectedMetrics, - ); - }); - - it('should track with the correct number of wallet accounts', () => { - mockGetState.mockImplementation(() => ({ - browser: { - visitedDappsByHostname: { 'uniswap.org': true }, - }, - engine: { - backgroundState: { - PreferencesController: { - identities: { '0x1': true }, - }, - }, - }, - })); - - const expectedMetrics = { - is_first_visit: false, - number_of_accounts: 1, - number_of_accounts_connected: 1, - source: 'in-app browser', - }; - - trackDappVisitedEvent({ - hostname: 'uniswap.org', - numberOfConnectedAccounts: 1, - }); - - expect(AnalyticsV2.trackEvent).toBeCalledWith( - MetaMetricsEvents.DAPP_VISITED, - expectedMetrics, - ); - }); -}); diff --git a/app/analytics/index.ts b/app/analytics/index.ts deleted file mode 100644 index 10d35787e4d..00000000000 --- a/app/analytics/index.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { selectIdentities } from '../selectors/preferencesController'; -import { store } from '../store'; -import { MetaMetricsEvents } from '../core/Analytics'; -import AnalyticsV2 from '../util/analyticsV2'; -import { addToVisitedDapp } from '../actions/browser'; - -/** - * Tracks Dapp visited event - * - * @param hostname - Hostname of the Dapp - * @param numberOfConnectedAccounts - Number of connected accounts that are connected to the Dapp - */ -// This file will export more events in the future. -// eslint-disable-next-line import/prefer-default-export -export const trackDappVisitedEvent = ({ - hostname, - numberOfConnectedAccounts, -}: { - hostname: string; - numberOfConnectedAccounts: number; -}) => { - const visitedDappsByHostname = - store.getState().browser.visitedDappsByHostname; - const isFirstVisit = !visitedDappsByHostname[hostname]; - const accountByAddress = selectIdentities(store.getState()); - const numberOfWalletAccounts = Object.keys(accountByAddress).length; - - // Add Dapp hostname to visited dapps - store.dispatch(addToVisitedDapp(hostname)); - - // Track DAPP_VISITED event - AnalyticsV2.trackEvent(MetaMetricsEvents.DAPP_VISITED, { - is_first_visit: isFirstVisit, - number_of_accounts: numberOfWalletAccounts, - number_of_accounts_connected: numberOfConnectedAccounts, - source: 'in-app browser', - }); -}; diff --git a/app/component-library/components/Accordions/Accordion/README.md b/app/component-library/components/Accordions/Accordion/README.md index b03af34bbdc..7284bfebc49 100644 --- a/app/component-library/components/Accordions/Accordion/README.md +++ b/app/component-library/components/Accordions/Accordion/README.md @@ -1,4 +1,4 @@ -# [Accordion](https://metamask-consensys.notion.site/Accordion-f43e500b92754d9bb06bc72553c44494) +# Accordion ![Accordion](./Accordion.png) diff --git a/app/component-library/components/Avatars/Avatar/README.md b/app/component-library/components/Avatars/Avatar/README.md index bdcce39668e..f4f560333f9 100644 --- a/app/component-library/components/Avatars/Avatar/README.md +++ b/app/component-library/components/Avatars/Avatar/README.md @@ -1,4 +1,4 @@ -# [Avatar](https://metamask-consensys.notion.site/Avatar-3c55358131914c589ed1e6d21d14a04f) +# Avatar ![Avatar](./Avatar.png) diff --git a/app/component-library/components/Badges/Badge/README.md b/app/component-library/components/Badges/Badge/README.md index 823ee6eb3e2..3deed9285ec 100644 --- a/app/component-library/components/Badges/Badge/README.md +++ b/app/component-library/components/Badges/Badge/README.md @@ -1,7 +1,6 @@ # Badge -[BadgeNetwork](https://metamask-consensys.notion.site/Badge-Network-94a679c50cb446f4844dc624b4f74946) + ![BadgeNetwork](./variants/BadgeNetwork/BadgeNetwork.png) -[BadgeStatus](https://metamask-consensys.notion.site/Badge-Status-5caf000de32549f8ad67c0b89469ce4d) ![BadgeStatus](./variants/BadgeStatus/BadgeStatus.png) Badge is a union component, which currently only consist of [BadgeNetwork](./variants/BadgeNetwork/BadgeNetwork.tsx) diff --git a/app/component-library/components/Badges/Badge/variants/BadgeNetwork/README.md b/app/component-library/components/Badges/Badge/variants/BadgeNetwork/README.md index 39b019216cb..57a2cb2185d 100644 --- a/app/component-library/components/Badges/Badge/variants/BadgeNetwork/README.md +++ b/app/component-library/components/Badges/Badge/variants/BadgeNetwork/README.md @@ -1,4 +1,4 @@ -# [BadgeNetwork](https://metamask-consensys.notion.site/Badge-Network-94a679c50cb446f4844dc624b4f74946) +# BadgeNetwork ![BadgeNetwork](./BadgeNetwork.png) diff --git a/app/component-library/components/Badges/Badge/variants/BadgeStatus/README.md b/app/component-library/components/Badges/Badge/variants/BadgeStatus/README.md index 5b294c62942..a4cadf17e6f 100644 --- a/app/component-library/components/Badges/Badge/variants/BadgeStatus/README.md +++ b/app/component-library/components/Badges/Badge/variants/BadgeStatus/README.md @@ -1,4 +1,4 @@ -# [BadgeStatus](https://metamask-consensys.notion.site/Badge-Status-5caf000de32549f8ad67c0b89469ce4d) +# BadgeStatus ![BadgeStatus](./BadgeStatus.png) diff --git a/app/component-library/components/Banners/Banner/README.md b/app/component-library/components/Banners/Banner/README.md index 984ffa65425..d02b563be93 100644 --- a/app/component-library/components/Banners/Banner/README.md +++ b/app/component-library/components/Banners/Banner/README.md @@ -1,7 +1,6 @@ # Banner -[BannerAlert](https://metamask-consensys.notion.site/Banner-Alert-56177453644641ed8ef5c96db6a7681f) + ![BannerAlert](./variants/BannerAlert/BannerAlert.png) -[BannerTip](https://metamask-consensys.notion.site/Banner-Tip-67fdb01ab850472f90abc6f4127395cb) ![BannerTip](./variants/BannerTip/BannerTip.png) This component is a union Banner component, which consists of [BannerAlert](../BannerAlert/BannerAlert.tsx) and [BannerTip](../BannerTip/BannerTip.tsx). diff --git a/app/component-library/components/Banners/Banner/variants/BannerAlert/README.md b/app/component-library/components/Banners/Banner/variants/BannerAlert/README.md index 3e4f9a07142..46136bd4b2a 100644 --- a/app/component-library/components/Banners/Banner/variants/BannerAlert/README.md +++ b/app/component-library/components/Banners/Banner/variants/BannerAlert/README.md @@ -1,4 +1,4 @@ -# [BannerAlert](https://metamask-consensys.notion.site/Banner-Alert-56177453644641ed8ef5c96db6a7681f) +# BannerAlert ![BannerAlert](./BannerAlert.png) diff --git a/app/component-library/components/Banners/Banner/variants/BannerTip/README.md b/app/component-library/components/Banners/Banner/variants/BannerTip/README.md index a19ba8b7894..8ba12117fd2 100644 --- a/app/component-library/components/Banners/Banner/variants/BannerTip/README.md +++ b/app/component-library/components/Banners/Banner/variants/BannerTip/README.md @@ -1,4 +1,4 @@ -# [BannerTip](https://metamask-consensys.notion.site/Banner-Tip-67fdb01ab850472f90abc6f4127395cb) +# BannerTip ![BannerTip](./BannerTip.png) diff --git a/app/component-library/components/BottomSheets/BottomSheet/README.md b/app/component-library/components/BottomSheets/BottomSheet/README.md index c858d5319b6..8694cefc13d 100644 --- a/app/component-library/components/BottomSheets/BottomSheet/README.md +++ b/app/component-library/components/BottomSheets/BottomSheet/README.md @@ -1,4 +1,4 @@ -# [BottomSheet](https://metamask-consensys.notion.site/Bottom-Sheet-302164aff8a74b6eb721f49586f88ecd) +# BottomSheet ![BottomSheet](./BottomSheet.png) diff --git a/app/component-library/components/BottomSheets/BottomSheetFooter/README.md b/app/component-library/components/BottomSheets/BottomSheetFooter/README.md index a4e7d187e3b..24969991fb8 100644 --- a/app/component-library/components/BottomSheets/BottomSheetFooter/README.md +++ b/app/component-library/components/BottomSheets/BottomSheetFooter/README.md @@ -1,4 +1,5 @@ -# [BottomSheetFooter](https://metamask-consensys.notion.site/Footer-b0eacc3951bf4962b75f6c4f95a8c2df) +# BottomSheetFooter + ![BottomSheetFooter](./BottomSheetFooter.png) BottomSheetFooter is a Footer component specifically used for BottomSheets. diff --git a/app/component-library/components/BottomSheets/BottomSheetFooter/__snapshots__/BottomSheetFooter.test.tsx.snap b/app/component-library/components/BottomSheets/BottomSheetFooter/__snapshots__/BottomSheetFooter.test.tsx.snap index 48120778bff..2a12274955b 100644 --- a/app/component-library/components/BottomSheets/BottomSheetFooter/__snapshots__/BottomSheetFooter.test.tsx.snap +++ b/app/component-library/components/BottomSheets/BottomSheetFooter/__snapshots__/BottomSheetFooter.test.tsx.snap @@ -78,7 +78,7 @@ exports[`BottomSheetFooter should render snapshot correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", diff --git a/app/component-library/components/Buttons/Button/README.md b/app/component-library/components/Buttons/Button/README.md index 12d3563a188..5ea2d3dc0e2 100644 --- a/app/component-library/components/Buttons/Button/README.md +++ b/app/component-library/components/Buttons/Button/README.md @@ -1,4 +1,4 @@ -# [Button](https://metamask-consensys.notion.site/Button-88af1ddc075b40e3bb38a6d0c098d9b6) +# Button ![Button](./Button.png) diff --git a/app/component-library/components/Buttons/ButtonIcon/README.md b/app/component-library/components/Buttons/ButtonIcon/README.md index 6313fd85b13..4e87e3fac80 100644 --- a/app/component-library/components/Buttons/ButtonIcon/README.md +++ b/app/component-library/components/Buttons/ButtonIcon/README.md @@ -1,4 +1,4 @@ -# [ButtonIcon](https://metamask-consensys.notion.site/Button-Icon-52fa285ebd8b4d56a22b6eabd08a8cf0) +# ButtonIcon ![ButtonIcon](./ButtonIcon.png) diff --git a/app/component-library/components/Checkbox/README.md b/app/component-library/components/Checkbox/README.md index 71da58f812a..b5a14884f2d 100644 --- a/app/component-library/components/Checkbox/README.md +++ b/app/component-library/components/Checkbox/README.md @@ -1,4 +1,4 @@ -# [Checkbox](https://metamask-consensys.notion.site/Checkbox-359c236367eb4058876fc12189c06824) +# Checkbox ![Checkbox](./Checkbox.png) diff --git a/app/component-library/components/Form/HelpText/README.md b/app/component-library/components/Form/HelpText/README.md index fecb7f35685..8d32b3d84c2 100644 --- a/app/component-library/components/Form/HelpText/README.md +++ b/app/component-library/components/Form/HelpText/README.md @@ -1,4 +1,4 @@ -# [HelpText](https://metamask-consensys.notion.site/Help-Text-d3c5f6284df84d598e2c2d586083eef0) +# HelpText ![HelpText](./HelpText.png) diff --git a/app/component-library/components/Form/Label/README.md b/app/component-library/components/Form/Label/README.md index 1e025a04d92..dd85166181d 100644 --- a/app/component-library/components/Form/Label/README.md +++ b/app/component-library/components/Form/Label/README.md @@ -1,4 +1,4 @@ -# [Label](https://metamask-consensys.notion.site/Label-d6aa56ac40044195a5078d37d3118223) +# Label ![Label](./Label.png) diff --git a/app/component-library/components/Form/TextField/README.md b/app/component-library/components/Form/TextField/README.md index e4518b8979e..11c976c1bc4 100644 --- a/app/component-library/components/Form/TextField/README.md +++ b/app/component-library/components/Form/TextField/README.md @@ -1,4 +1,4 @@ -# [TextField](https://metamask-consensys.notion.site/Text-Field-73e2b9b748404901ab2c9fba13eb7785) +# TextField ![TextField](./TextField.png) diff --git a/app/component-library/components/Form/TextFieldSearch/README.md b/app/component-library/components/Form/TextFieldSearch/README.md index 0eadc0378aa..a2e256125dd 100644 --- a/app/component-library/components/Form/TextFieldSearch/README.md +++ b/app/component-library/components/Form/TextFieldSearch/README.md @@ -1,4 +1,4 @@ -# [TextFieldSearch](https://metamask-consensys.notion.site/Text-Field-Search-de685317eeaf413f9682363128ffe673) +# TextFieldSearch ![TextFieldSearch](./TextFieldSearch.png) diff --git a/app/component-library/components/HeaderBase/README.md b/app/component-library/components/HeaderBase/README.md index c5766b54932..de83961f28a 100644 --- a/app/component-library/components/HeaderBase/README.md +++ b/app/component-library/components/HeaderBase/README.md @@ -1,4 +1,4 @@ -# [HeaderBase](https://metamask-consensys.notion.site/Header-Base-2e96e1ac4c2b4816bb7bd3c594c72538) +# HeaderBase ![HeaderBase](./HeaderBase.png) diff --git a/app/component-library/components/Icons/Icon/README.md b/app/component-library/components/Icons/Icon/README.md index 9df7fff346a..df26b39e04d 100644 --- a/app/component-library/components/Icons/Icon/README.md +++ b/app/component-library/components/Icons/Icon/README.md @@ -1,4 +1,4 @@ -# [Icon](https://metamask-consensys.notion.site/Icon-140cbe6ea9044c189e75b795fef99dd6) +# Icon ![Icon](./Icon.png) diff --git a/app/component-library/components/List/ListItem/README.md b/app/component-library/components/List/ListItem/README.md index dfb736636ad..cd15c1130cc 100644 --- a/app/component-library/components/List/ListItem/README.md +++ b/app/component-library/components/List/ListItem/README.md @@ -1,4 +1,4 @@ -# [ListItem](https://metamask-consensys.notion.site/List-Item-e3ddf0999a1844288b0a152e9d2a54b3) +# ListItem ![ListItem](./ListItem.png) diff --git a/app/component-library/components/List/ListItemMultiSelect/README.md b/app/component-library/components/List/ListItemMultiSelect/README.md index 9c46dcc2f8f..0e083dad054 100644 --- a/app/component-library/components/List/ListItemMultiSelect/README.md +++ b/app/component-library/components/List/ListItemMultiSelect/README.md @@ -1,4 +1,4 @@ -# [ListItemMultiSelect](https://metamask-consensys.notion.site/List-Item-MultiSelect-8ffafd9e99114e588c5c28ee5e4f0b10) +# ListItemMultiSelect ![ListItemMultiSelect](./ListItemMultiSelect.png) diff --git a/app/component-library/components/List/ListItemSelect/README.md b/app/component-library/components/List/ListItemSelect/README.md index da661f535fb..3ffa4fdb7e4 100644 --- a/app/component-library/components/List/ListItemSelect/README.md +++ b/app/component-library/components/List/ListItemSelect/README.md @@ -1,4 +1,4 @@ -# [ListItemSelect](https://metamask-consensys.notion.site/List-Item-Select-e9173552eb1c4723b9549a021624c536) +# ListItemSelect ![ListItemSelect](./ListItemSelect.png) diff --git a/app/component-library/components/Navigation/TabBar/TabBar.tsx b/app/component-library/components/Navigation/TabBar/TabBar.tsx index 40bb34e29f3..817a41d665c 100644 --- a/app/component-library/components/Navigation/TabBar/TabBar.tsx +++ b/app/component-library/components/Navigation/TabBar/TabBar.tsx @@ -15,7 +15,6 @@ import { useTheme } from '../../../../util/theme'; import Analytics from '../../../../core/Analytics/Analytics'; import { MetaMetricsEvents } from '../../../../core/Analytics'; import { selectChainId } from '../../../../selectors/networkController'; -import { getDecimalChainId } from '../../../../util/networks'; // Internal dependencies. import { TabBarProps } from './TabBar.types'; @@ -77,7 +76,7 @@ const TabBar = ({ state, descriptors, navigation }: TabBarProps) => { MetaMetricsEvents.ACTIONS_BUTTON_CLICKED, { text: '', - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }, ); break; diff --git a/app/component-library/components/Navigation/TabBar/__snapshots__/TabBar.test.tsx.snap b/app/component-library/components/Navigation/TabBar/__snapshots__/TabBar.test.tsx.snap index f658bbc2270..d5dde280fdd 100644 --- a/app/component-library/components/Navigation/TabBar/__snapshots__/TabBar.test.tsx.snap +++ b/app/component-library/components/Navigation/TabBar/__snapshots__/TabBar.test.tsx.snap @@ -127,7 +127,7 @@ Array [ } > - StyleSheet.create({ - actionsContainer: { - alignItems: 'flex-start', - justifyContent: 'center', - }, - }); - -export default styleSheet; diff --git a/app/components/Approvals/AddChainApproval/AddChainApproval.test.tsx b/app/components/Approvals/AddChainApproval/AddChainApproval.test.tsx index ab165ddae69..79da3bde5b3 100644 --- a/app/components/Approvals/AddChainApproval/AddChainApproval.test.tsx +++ b/app/components/Approvals/AddChainApproval/AddChainApproval.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; import AddChainApproval from './AddChainApproval'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/AddChainApproval/AddChainApproval.tsx b/app/components/Approvals/AddChainApproval/AddChainApproval.tsx index a0798e0155b..30084afc69e 100644 --- a/app/components/Approvals/AddChainApproval/AddChainApproval.tsx +++ b/app/components/Approvals/AddChainApproval/AddChainApproval.tsx @@ -1,29 +1,56 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import NetworkVerificationInfo from '../../UI/NetworkVerificationInfo'; import BottomSheet from '../../../component-library/components/BottomSheets/BottomSheet'; -import { useStyles } from '../../../component-library/hooks'; -import { View } from 'react-native'; - -// Internal dependencies -import styleSheet from './AddChainApproval.styles'; +import BottomSheetHeader from '../../../component-library/components/BottomSheets/BottomSheetHeader'; +import Text, { + TextVariant, +} from '../../../component-library/components/Texts/Text'; +import BottomSheetFooter, { + ButtonsAlignment, +} from '../../../component-library/components/BottomSheets/BottomSheetFooter'; +import { + ButtonSize, + ButtonVariants, +} from '../../../component-library/components/Buttons/Button'; +import { strings } from '../../../../locales/i18n'; +import { CommonSelectorsIDs } from '../../../../e2e/selectors/Common.selectors'; const AddChainApproval = () => { const { approvalRequest, onConfirm, onReject } = useApprovalRequest(); - const { styles } = useStyles(styleSheet, {}); if (approvalRequest?.type !== ApprovalTypes.ADD_ETHEREUM_CHAIN) return null; return ( - - - + + + {strings('add_custom_network.title')} + + + + ); }; diff --git a/app/components/Approvals/AddChainApproval/__snapshots__/AddChainApproval.test.tsx.snap b/app/components/Approvals/AddChainApproval/__snapshots__/AddChainApproval.test.tsx.snap index c47a70a4136..33e674a7bdf 100644 --- a/app/components/Approvals/AddChainApproval/__snapshots__/AddChainApproval.test.tsx.snap +++ b/app/components/Approvals/AddChainApproval/__snapshots__/AddChainApproval.test.tsx.snap @@ -4,16 +4,35 @@ exports[`AddChainApproval renders 1`] = ` - + + Allow this site to add a network? + + + + - - + buttonsAlignment="Horizontal" + /> `; diff --git a/app/components/Approvals/ConnectApproval/ConnectApproval.test.tsx b/app/components/Approvals/ConnectApproval/ConnectApproval.test.tsx index 2fed0ef1ce9..b3761df3bea 100644 --- a/app/components/Approvals/ConnectApproval/ConnectApproval.test.tsx +++ b/app/components/Approvals/ConnectApproval/ConnectApproval.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import ConnectApproval from './ConnectApproval'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/ConnectApproval/ConnectApproval.tsx b/app/components/Approvals/ConnectApproval/ConnectApproval.tsx index a95ee20254c..a9ed10e17b5 100644 --- a/app/components/Approvals/ConnectApproval/ConnectApproval.tsx +++ b/app/components/Approvals/ConnectApproval/ConnectApproval.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import ApprovalModal from '../ApprovalModal'; import AccountApproval from '../../UI/AccountApproval'; diff --git a/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.test.tsx b/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.test.tsx index bc4ac05ca3d..57f4789d8e1 100644 --- a/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.test.tsx +++ b/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.test.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { @@ -7,10 +7,10 @@ import { ApprovalRequest, } from '@metamask/approval-controller'; import FlowLoaderModal from './FlowLoaderModal'; -import useApprovalFlow from '../../Views/confirmations/hooks/useApprovalFlow'; +import useApprovalFlow from '../../hooks/useApprovalFlow'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); -jest.mock('../../Views/confirmations/hooks/useApprovalFlow'); +jest.mock('../../hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalFlow'); const APPROVAL_FLOW_MOCK: ApprovalFlowState = { id: 'testId1', diff --git a/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.tsx b/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.tsx index 302f5ea2725..6a579dfecee 100644 --- a/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.tsx +++ b/app/components/Approvals/FlowLoaderModal/FlowLoaderModal.tsx @@ -1,8 +1,8 @@ import React, { useCallback } from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import ApprovalModal from '../ApprovalModal'; -import useApprovalFlow from '../../Views/confirmations/hooks/useApprovalFlow'; -import ApprovalFlowLoader from '../../Views/confirmations/components/Approval/ApprovalFlowLoader'; +import useApprovalFlow from '../../hooks/useApprovalFlow'; +import ApprovalFlowLoader from '../../UI/Approval/ApprovalFlowLoader'; const FlowLoaderModal = () => { const { approvalRequest } = useApprovalRequest(); diff --git a/app/components/Approvals/InstallSnapApproval/InstallSnapApproval.tsx b/app/components/Approvals/InstallSnapApproval/InstallSnapApproval.tsx index a4b0ee63132..ab9ef322a6d 100644 --- a/app/components/Approvals/InstallSnapApproval/InstallSnapApproval.tsx +++ b/app/components/Approvals/InstallSnapApproval/InstallSnapApproval.tsx @@ -1,7 +1,7 @@ ///: BEGIN:ONLY_INCLUDE_IF(snaps) import React, { useEffect, useState } from 'react'; import ApprovalModal from '../ApprovalModal'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import Logger from '../../../util/Logger'; import { SnapInstallState } from './InstallSnapApproval.types'; diff --git a/app/components/Approvals/InstallSnapApproval/test/InstallSnapApproval.test.tsx b/app/components/Approvals/InstallSnapApproval/test/InstallSnapApproval.test.tsx index 965dce1b3c2..a8df01d6320 100644 --- a/app/components/Approvals/InstallSnapApproval/test/InstallSnapApproval.test.tsx +++ b/app/components/Approvals/InstallSnapApproval/test/InstallSnapApproval.test.tsx @@ -3,7 +3,7 @@ import React from 'react'; import { render, fireEvent, waitFor } from '@testing-library/react-native'; import InstallSnapApproval from '../InstallSnapApproval'; import { ApprovalRequest } from '@metamask/approval-controller'; -import useApprovalRequest from '../../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../../hooks/useApprovalRequest'; import { SNAP_INSTALL_CANCEL, SNAP_INSTALL_CONNECTION_REQUEST, @@ -15,7 +15,7 @@ import { import SNAP_INSTALL_SUCCESS from '../components/InstallSnapSuccess/InstallSnapSuccess.constants'; import SNAP_INSTALL_ERROR from '../components/InstallSnapError/InstallSnapError.constants'; -jest.mock('../../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../../hooks/useApprovalRequest'); const onConfirm = jest.fn(); const onReject = jest.fn(); diff --git a/app/components/Approvals/PermissionApproval/PermissionApproval.test.tsx b/app/components/Approvals/PermissionApproval/PermissionApproval.test.tsx index c43c389ff5b..b22b6c8d366 100644 --- a/app/components/Approvals/PermissionApproval/PermissionApproval.test.tsx +++ b/app/components/Approvals/PermissionApproval/PermissionApproval.test.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import PermissionApproval from './PermissionApproval'; @@ -10,7 +10,7 @@ import { MetaMetricsEvents } from '../../../core/Analytics'; import initialBackgroundState from '../../../util/test/initial-background-state.json'; import { render } from '@testing-library/react-native'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); jest.mock('../../../util/analyticsV2'); jest.mock('../../Views/AccountConnect', () => ({ diff --git a/app/components/Approvals/PermissionApproval/PermissionApproval.tsx b/app/components/Approvals/PermissionApproval/PermissionApproval.tsx index f93fb7b230a..f70db700caa 100644 --- a/app/components/Approvals/PermissionApproval/PermissionApproval.tsx +++ b/app/components/Approvals/PermissionApproval/PermissionApproval.tsx @@ -1,6 +1,6 @@ // eslint-disable-next-line @typescript-eslint/no-unused-vars import { useEffect, useRef } from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import AnalyticsV2 from '../../../util/analyticsV2'; import { MetaMetricsEvents } from '../../../core/Analytics'; diff --git a/app/components/Approvals/SignatureApproval/SignatureApproval.test.tsx b/app/components/Approvals/SignatureApproval/SignatureApproval.test.tsx index baaaf4a9573..2e30b54ff87 100644 --- a/app/components/Approvals/SignatureApproval/SignatureApproval.test.tsx +++ b/app/components/Approvals/SignatureApproval/SignatureApproval.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import SignatureApproval from './SignatureApproval'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/SignatureApproval/SignatureApproval.tsx b/app/components/Approvals/SignatureApproval/SignatureApproval.tsx index a22a06cd04d..38ec7daa721 100644 --- a/app/components/Approvals/SignatureApproval/SignatureApproval.tsx +++ b/app/components/Approvals/SignatureApproval/SignatureApproval.tsx @@ -1,7 +1,7 @@ import React, { useCallback } from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; -import SignatureRequestRoot from '../../Views/confirmations/components/SignatureRequest/Root'; +import SignatureRequestRoot from '../../UI/SignatureRequest/Root'; const SignatureApproval = () => { const { approvalRequest, onReject, onConfirm } = useApprovalRequest(); diff --git a/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.test.tsx b/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.test.tsx index ac57bba0e20..85884bcace2 100644 --- a/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.test.tsx +++ b/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.test.tsx @@ -1,12 +1,12 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import SwitchChainApproval from './SwitchChainApproval'; import { networkSwitched } from '../../../actions/onboardNetwork'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); jest.mock('../../../actions/onboardNetwork'); jest.mock('react-redux', () => ({ diff --git a/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.tsx b/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.tsx index 9a3310addf9..7a97187c082 100644 --- a/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.tsx +++ b/app/components/Approvals/SwitchChainApproval/SwitchChainApproval.tsx @@ -1,5 +1,5 @@ import React, { useCallback } from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import ApprovalModal from '../ApprovalModal'; import SwitchCustomNetwork from '../../UI/SwitchCustomNetwork'; diff --git a/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.test.tsx b/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.test.tsx index 5f8b8097da8..49ee66f0334 100644 --- a/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.test.tsx +++ b/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import TemplateConfirmationModal from './TemplateConfirmationModal'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.tsx b/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.tsx index f527fb52b41..25795c64e64 100644 --- a/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.tsx +++ b/app/components/Approvals/TemplateConfirmationModal/TemplateConfirmationModal.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import ApprovalModal from '../ApprovalModal'; -import TemplateConfirmation from '../../Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation'; -import { TEMPLATED_CONFIRMATION_APPROVAL_TYPES } from '../../Views/confirmations/components/Approval/TemplateConfirmation/Templates'; +import TemplateConfirmation from '../../UI/Approval/TemplateConfirmation/TemplateConfirmation'; +import { TEMPLATED_CONFIRMATION_APPROVAL_TYPES } from '../../UI/Approval/TemplateConfirmation/Templates'; const TemplateConfirmationModal = () => { const { approvalRequest, onConfirm, onReject } = useApprovalRequest(); diff --git a/app/components/Approvals/TransactionApproval/TransactionApproval.test.tsx b/app/components/Approvals/TransactionApproval/TransactionApproval.test.tsx index 3c9eafa35b2..715a0f3b0dc 100644 --- a/app/components/Approvals/TransactionApproval/TransactionApproval.test.tsx +++ b/app/components/Approvals/TransactionApproval/TransactionApproval.test.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; @@ -8,7 +8,7 @@ import { TransactionModalType, } from './TransactionApproval'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); jest.mock('../../UI/QRHardware/withQRHardwareAwareness', () => jest.fn((component) => component), diff --git a/app/components/Approvals/TransactionApproval/TransactionApproval.tsx b/app/components/Approvals/TransactionApproval/TransactionApproval.tsx index 4ee7b9e8d74..de00e6efbf8 100644 --- a/app/components/Approvals/TransactionApproval/TransactionApproval.tsx +++ b/app/components/Approvals/TransactionApproval/TransactionApproval.tsx @@ -1,8 +1,8 @@ import React, { useCallback, useState } from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; -import Approval from '../../Views/confirmations/Approval'; -import Approve from '../../Views/confirmations/ApproveView/Approve'; +import Approval from '../../Views/Approval'; +import Approve from '../../Views/ApproveView/Approve'; import QRSigningModal from '../../UI/QRHardware/QRSigningModal'; import withQRHardwareAwareness from '../../UI/QRHardware/withQRHardwareAwareness'; import { IQRState } from '../../UI/QRHardware/types'; diff --git a/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.test.tsx b/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.test.tsx index f773d5bb200..8a1218e4238 100644 --- a/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.test.tsx +++ b/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import WalletConnectApproval from './WalletConnectApproval'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.tsx b/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.tsx index b34b35fe4e7..4b9ca9cdb32 100644 --- a/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.tsx +++ b/app/components/Approvals/WalletConnectApproval/WalletConnectApproval.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import ApprovalModal from '../ApprovalModal'; import AccountApproval from '../../UI/AccountApproval'; diff --git a/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.test.tsx b/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.test.tsx index be4cc50719c..1a4d97b8b32 100644 --- a/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.test.tsx +++ b/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; import { shallow } from 'enzyme'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; import WatchAssetApproval from './WatchAssetApproval'; -jest.mock('../../Views/confirmations/hooks/useApprovalRequest'); +jest.mock('../../hooks/useApprovalRequest'); const mockApprovalRequest = (approvalRequest?: ApprovalRequest) => { ( diff --git a/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.tsx b/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.tsx index a402c54987f..06bfe9d861b 100644 --- a/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.tsx +++ b/app/components/Approvals/WatchAssetApproval/WatchAssetApproval.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import useApprovalRequest from '../../Views/confirmations/hooks/useApprovalRequest'; -import WatchAssetRequest from '../../Views/confirmations/components/WatchAssetRequest'; +import useApprovalRequest from '../../hooks/useApprovalRequest'; +import WatchAssetRequest from '../../UI/WatchAssetRequest'; import { ApprovalTypes } from '../../../core/RPCMethods/RPCMethodMiddleware'; import ApprovalModal from '../ApprovalModal'; diff --git a/app/components/Base/DetailsModal.js b/app/components/Base/DetailsModal.js index da1b0096359..a5ca13c1937 100644 --- a/app/components/Base/DetailsModal.js +++ b/app/components/Base/DetailsModal.js @@ -5,7 +5,10 @@ import Ionicons from 'react-native-vector-icons/Ionicons'; import { fontStyles } from '../../styles/common'; import Text from './Text'; import { useTheme } from '../../util/theme'; -import { TransactionDetailsModalSelectorsIDs } from '../../../e2e/selectors/Modals/TransactionDetailsModal.selectors'; +import { + DETAILS_MODAL_TITLE, + DETAILS_MODAL_CLOSE_ICON, +} from '../../../wdio/screen-objects/testIDs/Components/DetailsModal.js'; const createStyles = (colors) => StyleSheet.create({ @@ -82,7 +85,7 @@ const DetailsModalTitle = ({ style, ...props }) => { return ( @@ -96,7 +99,7 @@ const DetailsModalCloseIcon = ({ style, ...props }) => { @@ -106,13 +109,7 @@ const DetailsModalBody = ({ style, ...props }) => { const { colors } = useTheme(); const styles = createStyles(colors); - return ( - - ); + return ; }; const DetailsModalSection = ({ style, borderBottom, ...props }) => { const { colors } = useTheme(); diff --git a/app/components/Base/ScreenView.tsx b/app/components/Base/ScreenView.tsx index 857f2753c2b..3f08008b39e 100644 --- a/app/components/Base/ScreenView.tsx +++ b/app/components/Base/ScreenView.tsx @@ -1,4 +1,4 @@ -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; import React from 'react'; import { SafeAreaView, StyleSheet, ScrollView } from 'react-native'; import { useTheme } from '../../util/theme'; diff --git a/app/components/Base/StatusText.js b/app/components/Base/StatusText.js index 0de17d43962..83f1ffc1966 100644 --- a/app/components/Base/StatusText.js +++ b/app/components/Base/StatusText.js @@ -5,7 +5,7 @@ import { StyleSheet } from 'react-native'; import { FIAT_ORDER_STATES } from '../../constants/on-ramp'; import { strings } from '../../../locales/i18n'; import { useTheme } from '../../util/theme'; -import { CommonSelectorsIDs } from '../../../e2e/selectors/Common.selectors'; +import { DETAILS_MODAL_TITLE } from '../../../wdio/screen-objects/testIDs/Components/DetailsModal.js'; const styles = StyleSheet.create({ status: { @@ -17,7 +17,7 @@ const styles = StyleSheet.create({ export const ConfirmedText = (props) => ( { useEffect(() => { const initAnalytics = async () => { - await MetaMetrics.getInstance().configure(); await Analytics.init(); }; diff --git a/app/components/Nav/Main/MainNavigator.js b/app/components/Nav/Main/MainNavigator.js index 34b10a8f555..3825e27697a 100644 --- a/app/components/Nav/Main/MainNavigator.js +++ b/app/components/Nav/Main/MainNavigator.js @@ -1,10 +1,11 @@ import React, { useRef, useState, useEffect } from 'react'; import { Image, StyleSheet, Keyboard, Platform } from 'react-native'; +import PropTypes from 'prop-types'; import { createStackNavigator } from '@react-navigation/stack'; import { useSelector } from 'react-redux'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import Browser from '../../Views/Browser'; -import { ChainId } from '@metamask/controller-utils'; +import { NetworksChainId } from '@metamask/controller-utils'; import AddBookmark from '../../Views/AddBookmark'; import SimpleWebview from '../../Views/SimpleWebview'; import Settings from '../../Views/Settings'; @@ -20,8 +21,8 @@ import Asset from '../../Views/Asset'; import AssetDetails from '../../Views/AssetDetails'; import AddAsset from '../../Views/AddAsset'; import Collectible from '../../Views/Collectible'; -import Send from '../../Views/confirmations/Send'; -import SendTo from '../../Views/confirmations/SendFlow/SendTo'; +import Send from '../../Views/Send'; +import SendTo from '../../Views/SendFlow/SendTo'; import { RevealPrivateCredential } from '../../Views/RevealPrivateCredential'; import WalletConnectSessions from '../../Views/WalletConnectSessions'; import OfflineMode from '../../Views/OfflineMode'; @@ -36,8 +37,8 @@ import ManualBackupStep2 from '../../Views/ManualBackupStep2'; import ManualBackupStep3 from '../../Views/ManualBackupStep3'; import PaymentRequest from '../../UI/PaymentRequest'; import PaymentRequestSuccess from '../../UI/PaymentRequestSuccess'; -import Amount from '../../Views/confirmations/SendFlow/Amount'; -import Confirm from '../../Views/confirmations/SendFlow/Confirm'; +import Amount from '../../Views/SendFlow/Amount'; +import Confirm from '../../Views/SendFlow/Confirm'; import ContactForm from '../../Views/Settings/Contacts/ContactForm'; import ActivityView from '../../Views/ActivityView'; import SwapsAmountView from '../../UI/Swaps'; @@ -46,11 +47,17 @@ import CollectiblesDetails from '../../UI/CollectibleModal'; import OptinMetrics from '../../UI/OptinMetrics'; import Drawer from '../../UI/Drawer'; -import RampRoutes from '../../UI/Ramp/routes'; +import { RampSDKProvider } from '../../UI/Ramp/sdk'; import { RampType } from '../../UI/Ramp/types'; +import GetStarted from '../../UI/Ramp/Views/GetStarted'; +import PaymentMethods from '../../UI/Ramp/Views/PaymentMethods/PaymentMethods'; +import BuildQuote from '../../UI/Ramp/Views/BuildQuote/BuildQuote'; +import Quotes from '../../UI/Ramp/Views/Quotes'; +import CheckoutWebView from '../../UI/Ramp/Views/Checkout'; import RampSettings from '../../UI/Ramp/Views/Settings'; +import NetworkSwitcher from '../../UI/Ramp/Views/NetworkSwitcher'; import RampAddActivationKey from '../../UI/Ramp/Views/Settings/AddActivationKey'; - +import Regions from '../../UI/Ramp/Views/Regions'; import { colors as importedColors } from '../../../styles/common'; import OrderDetails from '../../UI/Ramp/Views/OrderDetails'; import SendTransaction from '../../UI/Ramp/Views/SendTransaction'; @@ -73,7 +80,6 @@ import isUrl from 'is-url'; import SDKSessionsManager from '../../Views/SDKSessionsManager/SDKSessionsManager'; import URL from 'url-parse'; import Logger from '../../../util/Logger'; -import { getDecimalChainId } from '../../../util/networks'; const Stack = createStackNavigator(); const Tab = createBottomTabNavigator(); @@ -333,7 +339,7 @@ const HomeTabs = () => { const chainId = useSelector((state) => { const providerConfig = selectProviderConfig(state); - return ChainId[providerConfig.type]; + return NetworksChainId[providerConfig.type]; }); const amountOfBrowserOpenTabs = useSelector( @@ -367,7 +373,7 @@ const HomeTabs = () => { callback: () => { AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_OPENED, { number_of_accounts: accountsLength, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }); }, rootScreenName: Routes.WALLET_VIEW, @@ -381,7 +387,7 @@ const HomeTabs = () => { callback: () => { AnalyticsV2.trackEvent(MetaMetricsEvents.BROWSER_OPENED, { number_of_accounts: accountsLength, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, source: 'Navigation Tab', active_connected_dapp: activeConnectedDapp, number_of_open_tabs: amountOfBrowserOpenTabs, @@ -549,6 +555,46 @@ const PaymentRequestView = () => ( ); +const Ramps = ({ rampType }) => ( + + + + + + + + + + + + + + +); + +Ramps.propTypes = { + rampType: PropTypes.string, +}; + const Swaps = () => ( ( - {() => } + {() => } - {() => } + {() => } { ); await KeyringController.resetQRKeyringState(); - const isLedgerAccount = isHardwareAccount( - transactionMeta.transaction.from, - [ExtendedKeyringTypes.ledger], - ); - - // For Ledger Accounts we handover the signing to the confirmation flow - if (isLedgerAccount) { - const ledgerKeyring = await getLedgerKeyring(); - - props.navigation.navigate( - ...createLedgerTransactionModalNavDetails({ - transactionId: transactionMeta.id, - deviceId: ledgerKeyring.deviceId, - // eslint-disable-next-line no-empty-function - onConfirmationComplete: () => {}, - type: 'signTransaction', - }), - ); - } else { - Engine.acceptPendingApproval(transactionMeta.id); - } + Engine.acceptPendingApproval(transactionMeta.id); } catch (error) { if (!error?.message.startsWith(KEYSTONE_TX_CANCELED)) { Alert.alert( @@ -254,7 +227,7 @@ const RootRPCMethodsUI = (props) => { } } }, - [props.navigation, props.swapsTransactions, trackSwaps], + [props.swapsTransactions, trackSwaps], ); const onUnapprovedTransaction = useCallback( diff --git a/app/components/Nav/Main/index.js b/app/components/Nav/Main/index.js index a497ca6e4cf..97a9557a300 100644 --- a/app/components/Nav/Main/index.js +++ b/app/components/Nav/Main/index.js @@ -69,14 +69,10 @@ import { selectProviderType, } from '../../../selectors/networkController'; import { selectShowIncomingTransactionNetworks } from '../../../selectors/preferencesController'; -import { DEPRECATED_NETWORKS } from '../../../constants/network'; +import { addHexPrefix, toHexadecimal } from '../../../util/number'; +import { NETWORKS_CHAIN_ID } from '../../../constants/network'; import WarningAlert from '../../../components/UI/WarningAlert'; import { GOERLI_DEPRECATED_ARTICLE } from '../../../constants/urls'; -import { - updateIncomingTransactions, - startIncomingTransactionPolling, - stopIncomingTransactionPolling, -} from '../../../util/transaction-controller'; ///: BEGIN:ONLY_INCLUDE_IF(snaps) import { SnapsExecutionWebView } from '../../UI/SnapsExecutionWebView'; ///: END:ONLY_INCLUDE_IF @@ -115,20 +111,13 @@ const Main = (props) => { useMinimumVersions(); useEffect(() => { - if (DEPRECATED_NETWORKS.includes(props.chainId)) { - setShowDeprecatedAlert(true); - } else { - setShowDeprecatedAlert(false); - } - }, [props.chainId]); - - useEffect(() => { - const chainId = props.chainId; + const { TransactionController } = Engine.context; + const currentHexChainId = addHexPrefix(toHexadecimal(props.chainId)); - if (props.showIncomingTransactionsNetworks[chainId]) { - startIncomingTransactionPolling(); + if (props.showIncomingTransactionsNetworks[currentHexChainId]) { + TransactionController.startIncomingTransactionPolling(); } else { - stopIncomingTransactionPolling(); + TransactionController.stopIncomingTransactionPolling(); } }, [props.showIncomingTransactionsNetworks, props.chainId]); @@ -173,6 +162,7 @@ const Main = (props) => { const handleAppStateChange = useCallback( (appState) => { const newModeIsBackground = appState === 'background'; + const { TransactionController } = Engine.context; // If it was in background and it's not anymore // we need to stop the Background timer @@ -188,7 +178,7 @@ const Main = (props) => { removeNotVisibleNotifications(); BackgroundTimer.runBackgroundTimer(async () => { - await updateIncomingTransactions(); + await TransactionController.updateIncomingTransactions(); }, AppConstants.TX_CHECK_BACKGROUND_FREQUENCY); } }, @@ -344,7 +334,7 @@ const Main = (props) => { }; const renderDeprecatedNetworkAlert = (chainId, backUpSeedphraseVisible) => { - if (DEPRECATED_NETWORKS.includes(chainId) && showDeprecatedAlert) { + if (chainId === NETWORKS_CHAIN_ID.GOERLI && showDeprecatedAlert) { return ( StyleSheet.create({ diff --git a/app/components/UI/AccountFromToInfoCard/__snapshots__/AccountFromToInfoCard.test.tsx.snap b/app/components/UI/AccountFromToInfoCard/__snapshots__/AccountFromToInfoCard.test.tsx.snap index 31542fbafc7..923b2a198ff 100644 --- a/app/components/UI/AccountFromToInfoCard/__snapshots__/AccountFromToInfoCard.test.tsx.snap +++ b/app/components/UI/AccountFromToInfoCard/__snapshots__/AccountFromToInfoCard.test.tsx.snap @@ -392,7 +392,7 @@ Array [ style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 15, }, undefined, diff --git a/app/components/UI/AccountInfoCard/index.js b/app/components/UI/AccountInfoCard/index.js index 67a5bf2b5b5..748b2a3b7c3 100644 --- a/app/components/UI/AccountInfoCard/index.js +++ b/app/components/UI/AccountInfoCard/index.js @@ -26,7 +26,7 @@ import { } from '../../../selectors/currencyRateController'; import { selectAccounts } from '../../../selectors/accountTrackerController'; import { selectIdentities } from '../../../selectors/preferencesController'; -import ApproveTransactionHeader from '../../Views/confirmations/components/ApproveTransactionHeader'; +import ApproveTransactionHeader from '../ApproveTransactionHeader'; import Text, { TextVariant, } from '../../../component-library/components/Texts/Text'; diff --git a/app/components/UI/AccountSelectorList/AccountSelector.test.tsx b/app/components/UI/AccountSelectorList/AccountSelector.test.tsx index cbe7eadb5bd..4bdf609e0fc 100644 --- a/app/components/UI/AccountSelectorList/AccountSelector.test.tsx +++ b/app/components/UI/AccountSelectorList/AccountSelector.test.tsx @@ -41,7 +41,7 @@ const initialState = { providerConfig: { ticker: 'ETH', type: 'mainnet', - chainId: '0x1', + chainId: '1', }, }, AccountTrackerController: { diff --git a/app/components/UI/ActionView/__snapshots__/index.test.tsx.snap b/app/components/UI/ActionView/__snapshots__/index.test.tsx.snap index 16cd8c27df3..7a89c89fd57 100644 --- a/app/components/UI/ActionView/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/ActionView/__snapshots__/index.test.tsx.snap @@ -86,8 +86,6 @@ exports[`ActionView should render correctly 1`] = ` Object { "marginLeft": 8, }, - Object {}, - Object {}, ] } disabled={false} diff --git a/app/components/UI/ActionView/index.js b/app/components/UI/ActionView/index.js index da9fc1fb566..24634500430 100644 --- a/app/components/UI/ActionView/index.js +++ b/app/components/UI/ActionView/index.js @@ -13,38 +13,23 @@ import { strings } from '../../../../locales/i18n'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { useTheme } from '../../../util/theme'; -export const ConfirmButtonState = { - Error: 'error', - Warning: 'warning', - Normal: 'normal', -}; - -const getStyles = (colors) => - StyleSheet.create({ - actionContainer: { - flex: 0, - flexDirection: 'row', - paddingVertical: 16, - paddingHorizontal: 24, - }, - button: { - flex: 1, - }, - cancel: { - marginRight: 8, - }, - confirm: { - marginLeft: 8, - }, - confirmButtonError: { - backgroundColor: colors.error.default, - borderColor: colors.error.default, - }, - confirmButtonWarning: { - backgroundColor: colors.warning.default, - borderColor: colors.warning.default, - }, - }); +const styles = StyleSheet.create({ + actionContainer: { + flex: 0, + flexDirection: 'row', + paddingVertical: 16, + paddingHorizontal: 24, + }, + button: { + flex: 1, + }, + cancel: { + marginRight: 8, + }, + confirm: { + marginLeft: 8, + }, +}); /** * PureComponent that renders scrollable content above configurable buttons @@ -66,12 +51,10 @@ export default function ActionView({ loading = false, keyboardShouldPersistTaps = 'never', style = undefined, - confirmButtonState = ConfirmButtonState.Normal, }) { const { colors } = useTheme(); confirmText = confirmText || strings('action_view.confirm'); cancelText = cancelText || strings('action_view.cancel'); - const styles = getStyles(colors); return ( @@ -110,16 +93,7 @@ export default function ActionView({ testID={confirmTestID} type={confirmButtonMode} onPress={onConfirmPress} - containerStyle={[ - styles.button, - styles.confirm, - confirmButtonState === ConfirmButtonState.Error - ? styles.confirmButtonError - : {}, - confirmButtonState === ConfirmButtonState.Warning - ? styles.confirmButtonWarning - : {}, - ]} + containerStyle={[styles.button, styles.confirm]} disabled={confirmed || confirmDisabled || loading} > {confirmed || loading ? ( @@ -215,8 +189,4 @@ ActionView.propTypes = { * Optional View styles. Applies to scroll view */ style: PropTypes.object, - /** - * Optional Confirm button state - this can be Error/Warning/Normal. - */ - confirmButtonState: PropTypes.string, }; diff --git a/app/components/UI/AddCustomCollectible/index.tsx b/app/components/UI/AddCustomCollectible/index.tsx index a0c5b05e056..1d0c5646810 100644 --- a/app/components/UI/AddCustomCollectible/index.tsx +++ b/app/components/UI/AddCustomCollectible/index.tsx @@ -29,7 +29,6 @@ import { } from '../../../../wdio/screen-objects/testIDs/Screens/NFTImportScreen.testIds'; import { selectChainId } from '../../../selectors/networkController'; import { selectSelectedAddress } from '../../../selectors/preferencesController'; -import { getDecimalChainId } from '../../../util/networks'; const createStyles = (colors: any) => StyleSheet.create({ @@ -103,7 +102,7 @@ const AddCustomCollectible = ({ const getAnalyticsParams = () => { try { return { - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; } catch (error) { return {}; diff --git a/app/components/UI/AddCustomToken/index.js b/app/components/UI/AddCustomToken/index.js index 3814c94fcb0..da39db882fc 100644 --- a/app/components/UI/AddCustomToken/index.js +++ b/app/components/UI/AddCustomToken/index.js @@ -20,7 +20,7 @@ import AnalyticsV2 from '../../../util/analyticsV2'; import AppConstants from '../../../core/AppConstants'; import Alert, { AlertType } from '../../Base/Alert'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; -import WarningMessage from '../../Views/confirmations/SendFlow/WarningMessage'; +import WarningMessage from '../../Views/SendFlow/WarningMessage'; import NotificationManager from '../../../core/NotificationManager'; import { ThemeContext, mockTheme } from '../../../util/theme'; import generateTestId from '../../../../wdio/utils/generateTestId'; @@ -35,7 +35,6 @@ import { import { NFT_IDENTIFIER_INPUT_BOX_ID } from '../../../../wdio/screen-objects/testIDs/Screens/NFTImportScreen.testIds'; import { regex } from '../../../../app/util/regex'; import { AddCustomTokenViewSelectorsIDs } from '../../../../e2e/selectors/AddCustomTokenView.selectors'; -import { getDecimalChainId } from '../../../util/networks'; const createStyles = (colors) => StyleSheet.create({ @@ -113,7 +112,7 @@ export default class AddCustomToken extends PureComponent { return { token_address: address, token_symbol: symbol, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, source: 'Custom token', }; } catch (error) { diff --git a/app/components/UI/AddToAddressBookWrapper/AddToAddressBookWrapper.test.tsx b/app/components/UI/AddToAddressBookWrapper/AddToAddressBookWrapper.test.tsx index b2ce68ace60..7e0c018eff5 100644 --- a/app/components/UI/AddToAddressBookWrapper/AddToAddressBookWrapper.test.tsx +++ b/app/components/UI/AddToAddressBookWrapper/AddToAddressBookWrapper.test.tsx @@ -27,7 +27,7 @@ const initialState = { }, AddressBookController: { addressBook: { - '0x1': { + 1: { '0x1': { address: '0x1', name: 'Account 2', diff --git a/app/components/UI/AddressInputs/__snapshots__/index.test.jsx.snap b/app/components/UI/AddressInputs/__snapshots__/index.test.jsx.snap index aed648215f3..6a8faaa2c0f 100644 --- a/app/components/UI/AddressInputs/__snapshots__/index.test.jsx.snap +++ b/app/components/UI/AddressInputs/__snapshots__/index.test.jsx.snap @@ -605,7 +605,7 @@ exports[`AddressInputs AddressTo should match default snapshot 1`] = ` style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 15, }, undefined, @@ -876,7 +876,7 @@ exports[`AddressInputs AddressTo should match snapshot when layout is vertical 1 style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 15, }, undefined, diff --git a/app/components/UI/AddressInputs/index.js b/app/components/UI/AddressInputs/index.js index cf2e5773561..90ebe91cae4 100644 --- a/app/components/UI/AddressInputs/index.js +++ b/app/components/UI/AddressInputs/index.js @@ -93,6 +93,7 @@ const createStyles = (colors, layout = 'horizontal') => { }, accountNameLabelText: { marginLeft: 4, + horizontalAlign: 'center', textAlign: 'center', paddingHorizontal: 8, color: colors.text.alternative, diff --git a/app/components/UI/AddressInputs/index.test.jsx b/app/components/UI/AddressInputs/index.test.jsx index a32e4577c0d..bd5230f819e 100644 --- a/app/components/UI/AddressInputs/index.test.jsx +++ b/app/components/UI/AddressInputs/index.test.jsx @@ -26,7 +26,7 @@ const initialState = { }, AddressBookController: { addressBook: { - '0x1': { + 1: { '0x519d2CE57898513F676a5C3b66496c3C394c9CC7': { address: '0x519d2CE57898513F676a5C3b66496c3C394c9CC7', name: 'Account 2', diff --git a/app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/__snapshots__/index.test.tsx.snap b/app/components/UI/Approval/ApprovalFlowLoader/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/__snapshots__/index.test.tsx.snap rename to app/components/UI/Approval/ApprovalFlowLoader/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/index.js b/app/components/UI/Approval/ApprovalFlowLoader/index.js similarity index 84% rename from app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/index.js rename to app/components/UI/Approval/ApprovalFlowLoader/index.js index fadd33da38b..637e05eb536 100644 --- a/app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/index.js +++ b/app/components/UI/Approval/ApprovalFlowLoader/index.js @@ -1,10 +1,10 @@ import React from 'react'; import { StyleSheet, View } from 'react-native'; import PropTypes from 'prop-types'; -import Device from '../../../../../../util/device'; -import { useTheme } from '../../../../../../util/theme'; -import Text from '../../../../../Base/Text'; -import Spinner from '../../../../../UI/AnimatedSpinner'; +import Device from '../../../../util/device'; +import { useTheme } from '../../../../util/theme'; +import Text from '../../../Base/Text'; +import Spinner from '../../AnimatedSpinner'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/index.test.tsx b/app/components/UI/Approval/ApprovalFlowLoader/index.test.tsx similarity index 100% rename from app/components/Views/confirmations/components/Approval/ApprovalFlowLoader/index.test.tsx rename to app/components/UI/Approval/ApprovalFlowLoader/index.test.tsx diff --git a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts b/app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts similarity index 86% rename from app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts rename to app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts index 0d0ac0642a8..bf561cdd258 100644 --- a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts +++ b/app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.styles.ts @@ -1,6 +1,6 @@ import { StyleSheet } from 'react-native'; -import { Theme } from '../../../../../../util/theme/models'; -import Device from '../../../../../../util/device'; +import { Theme } from '../../../../util/theme/models'; +import Device from '../../../../util/device'; /** * diff --git a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.tsx b/app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.tsx similarity index 85% rename from app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.tsx rename to app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.tsx index 9c8de750a4d..a2742c4a562 100644 --- a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/TemplateConfirmation.tsx +++ b/app/components/UI/Approval/TemplateConfirmation/TemplateConfirmation.tsx @@ -1,18 +1,18 @@ import React, { useEffect, useMemo } from 'react'; -import { strings } from '../../../../../../../locales/i18n'; -import TemplateRenderer from '../../../../../UI/TemplateRenderer'; +import { strings } from '../../../../../locales/i18n'; +import TemplateRenderer from '../../TemplateRenderer'; import { ConfirmationTemplateValues, getTemplateValues } from './Templates'; -import { useStyles } from '../../../../../hooks/useStyles'; +import { useStyles } from '../../../hooks/useStyles'; import stylesheet from './TemplateConfirmation.styles'; import { View } from 'react-native-animatable'; import BottomSheetFooter, { ButtonsAlignment, -} from '../../../../../../component-library/components/BottomSheets/BottomSheetFooter'; +} from '../../../../component-library/components/BottomSheets/BottomSheetFooter'; import { ButtonSize, ButtonVariants, -} from '../../../../../../component-library/components/Buttons/Button'; -import { useAppThemeFromContext } from '../../../../../../util/theme'; +} from '../../../../component-library/components/Buttons/Button'; +import { useAppThemeFromContext } from '../../../../util/theme'; import { AcceptOptions, ApprovalRequest } from '@metamask/approval-controller'; export interface TemplateConfirmationProps { diff --git a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx b/app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx similarity index 93% rename from app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx rename to app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx index 2cb175e6315..241068e166d 100644 --- a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx +++ b/app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.test.tsx @@ -3,7 +3,7 @@ import { render } from '@testing-library/react-native'; import TemplateConfirmation, { TemplateConfirmationProps, } from '../TemplateConfirmation'; -import { ApprovalTypes } from '../../../../../../../core/RPCMethods/RPCMethodMiddleware'; +import { ApprovalTypes } from '../../../../../core/RPCMethods/RPCMethodMiddleware'; describe('ApprovalResult', () => { const mockProps: TemplateConfirmationProps = { diff --git a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.ts b/app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.ts similarity index 93% rename from app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.ts rename to app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.ts index 43e246e2a92..85856762ed5 100644 --- a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/ApprovalResult.ts +++ b/app/components/UI/Approval/TemplateConfirmation/Templates/ApprovalResult.ts @@ -2,11 +2,11 @@ import { IconColor, IconName, IconSize, -} from '../../../../../../../component-library/components/Icons/Icon'; +} from '../../../../../component-library/components/Icons/Icon'; import { processHeader, processError, processString } from '../util'; -import { ApprovalTypes } from '../../../../../../../core/RPCMethods/RPCMethodMiddleware'; +import { ApprovalTypes } from '../../../../../core/RPCMethods/RPCMethodMiddleware'; import { ApprovalRequest } from '@metamask/approval-controller'; -import { Colors } from '../../../../../../../util/theme/models'; +import { Colors } from '../../../../../util/theme/models'; import { Actions } from '../TemplateConfirmation'; import { ConfirmationTemplateValues, ConfirmationTemplate } from '.'; diff --git a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap b/app/components/UI/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap similarity index 98% rename from app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap rename to app/components/UI/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap index 6e917d7644f..b1003681d39 100644 --- a/app/components/Views/confirmations/components/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap +++ b/app/components/UI/Approval/TemplateConfirmation/Templates/__snapshots__/ApprovalResult.test.tsx.snap @@ -193,7 +193,7 @@ exports[`ApprovalResult renders approval result with error type 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -257,7 +257,7 @@ exports[`ApprovalResult renders approval result with success type 1`] = ` style={ Object { "alignItems": "center", - "backgroundColor": "#1C823419", + "backgroundColor": "#28A74519", "borderRadius": 24, "height": 48, "justifyContent": "center", @@ -266,7 +266,7 @@ exports[`ApprovalResult renders approval result with success type 1`] = ` } > ({ +jest.mock('../../../core/Engine', () => ({ context: { TokensController: { addToken: () => undefined, diff --git a/app/components/Views/confirmations/components/ApproveTransactionHeader/ApproveTransactionHeader.tsx b/app/components/UI/ApproveTransactionHeader/ApproveTransactionHeader.tsx similarity index 76% rename from app/components/Views/confirmations/components/ApproveTransactionHeader/ApproveTransactionHeader.tsx rename to app/components/UI/ApproveTransactionHeader/ApproveTransactionHeader.tsx index 2fab02aa6f9..6575b812db0 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionHeader/ApproveTransactionHeader.tsx +++ b/app/components/UI/ApproveTransactionHeader/ApproveTransactionHeader.tsx @@ -3,27 +3,27 @@ import React, { useEffect, useMemo, useState } from 'react'; import { View } from 'react-native'; import { useSelector } from 'react-redux'; -import AppConstants from '../../../../../core/AppConstants'; -import { strings } from '../../../../../../locales/i18n'; -import AccountBalance from '../../../../../component-library/components-temp/Accounts/AccountBalance'; -import { BadgeVariant } from '../../../../../component-library/components/Badges/Badge'; -import TagUrl from '../../../../../component-library/components/Tags/TagUrl'; -import { useStyles } from '../../../../../component-library/hooks'; -import { selectProviderConfig } from '../../../../../selectors/networkController'; -import { selectIdentities } from '../../../../../selectors/preferencesController'; -import { selectAccountsByChainId } from '../../../../../selectors/accountTrackerController'; +import AppConstants from '../../../../app/core/AppConstants'; +import { strings } from '../../../../locales/i18n'; +import AccountBalance from '../../../component-library/components-temp/Accounts/AccountBalance'; +import { BadgeVariant } from '../../../component-library/components/Badges/Badge'; +import TagUrl from '../../../component-library/components/Tags/TagUrl'; +import { useStyles } from '../../../component-library/hooks'; +import { selectAccounts } from '../../../selectors/accountTrackerController'; +import { selectProviderConfig } from '../../../selectors/networkController'; +import { selectIdentities } from '../../../selectors/preferencesController'; import { getLabelTextByAddress, renderAccountName, -} from '../../../../../util/address'; -import { getUrlObj, prefixUrlWithProtocol } from '../../../../../util/browser'; +} from '../../../util/address'; +import { getUrlObj, prefixUrlWithProtocol } from '../../../util/browser'; import { getNetworkImageSource, getNetworkNameFromProviderConfig, -} from '../../../../../util/networks'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import useAddressBalance from '../../../../hooks/useAddressBalance/useAddressBalance'; -import useFavicon from '../../../../hooks/useFavicon/useFavicon'; +} from '../../../util/networks'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; +import useAddressBalance from '../../hooks/useAddressBalance/useAddressBalance'; +import useFavicon from '../../hooks/useFavicon/useFavicon'; import { APPROVE_TRANSACTION_ORIGIN_PILL, ORIGIN_DEEPLINK, @@ -49,7 +49,7 @@ const ApproveTransactionHeader = ({ const { styles } = useStyles(stylesheet, {}); const { addressBalance } = useAddressBalance(asset, from, dontWatchAsset); - const accountsByChainId = useSelector(selectAccountsByChainId); + const accounts = useSelector(selectAccounts); const identities = useSelector(selectIdentities); const activeAddress = toChecksumAddress(from); @@ -83,7 +83,7 @@ const ApproveTransactionHeader = ({ setIsOriginMMSDKRemoteConn( origin.startsWith(AppConstants.MM_SDK.SDK_REMOTE_ORIGIN), ); - }, [accountsByChainId, identities, activeAddress, origin]); + }, [accounts, identities, activeAddress, origin]); const networkImage = getNetworkImageSource({ networkType: providerConfig.type, diff --git a/app/components/Views/confirmations/components/ApproveTransactionHeader/ApproveTransactionHeader.types.ts b/app/components/UI/ApproveTransactionHeader/ApproveTransactionHeader.types.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionHeader/ApproveTransactionHeader.types.ts rename to app/components/UI/ApproveTransactionHeader/ApproveTransactionHeader.types.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionHeader/__snapshots__/ApproveTransactionHeader.test.tsx.snap b/app/components/UI/ApproveTransactionHeader/__snapshots__/ApproveTransactionHeader.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionHeader/__snapshots__/ApproveTransactionHeader.test.tsx.snap rename to app/components/UI/ApproveTransactionHeader/__snapshots__/ApproveTransactionHeader.test.tsx.snap diff --git a/app/components/Views/confirmations/components/ApproveTransactionHeader/index.ts b/app/components/UI/ApproveTransactionHeader/index.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionHeader/index.ts rename to app/components/UI/ApproveTransactionHeader/index.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickNameHeader/index.tsx b/app/components/UI/ApproveTransactionReview/AddNickNameHeader/index.tsx similarity index 85% rename from app/components/Views/confirmations/components/ApproveTransactionReview/AddNickNameHeader/index.tsx rename to app/components/UI/ApproveTransactionReview/AddNickNameHeader/index.tsx index 4681c5eeaf6..5671df5da8a 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickNameHeader/index.tsx +++ b/app/components/UI/ApproveTransactionReview/AddNickNameHeader/index.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { View } from 'react-native'; -import Text from '../../../../../../component-library/components/Texts/Text'; -import { strings } from '../../../../../../../locales/i18n'; +import Text from '../../../../component-library/components/Texts/Text'; +import { strings } from '../../../../../locales/i18n'; import AntDesignIcon from 'react-native-vector-icons/AntDesign'; interface HeaderProps { diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/index.tsx b/app/components/UI/ApproveTransactionReview/AddNickname/index.tsx similarity index 87% rename from app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/index.tsx rename to app/components/UI/ApproveTransactionReview/AddNickname/index.tsx index 39fbb85f0fb..330894b4d49 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/index.tsx +++ b/app/components/UI/ApproveTransactionReview/AddNickname/index.tsx @@ -1,44 +1,44 @@ import React, { useState, useEffect, useCallback } from 'react'; import { SafeAreaView, View, TextInput, TouchableOpacity } from 'react-native'; import AntDesignIcon from 'react-native-vector-icons/AntDesign'; -import EthereumAddress from '../../../../../UI/EthereumAddress'; -import Engine from '../../../../../../core/Engine'; -import { MetaMetricsEvents } from '../../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../../util/analyticsV2'; +import EthereumAddress from '../../EthereumAddress'; +import Engine from '../../../../core/Engine'; +import { MetaMetricsEvents } from '../../../../core/Analytics'; +import AnalyticsV2 from '../../../../util/analyticsV2'; import { toChecksumAddress } from 'ethereumjs-util'; import { connect } from 'react-redux'; -import StyledButton from '../../../../../UI/StyledButton'; -import Text from '../../../../../../component-library/components/Texts/Text'; -import InfoModal from '../../../../../UI/Swaps/components/InfoModal'; -import Identicon from '../../../../../UI/Identicon'; +import StyledButton from '../../StyledButton'; +import Text from '../../../../component-library/components/Texts/Text'; +import InfoModal from '../../Swaps/components/InfoModal'; +import Identicon from '../../../UI/Identicon'; import Feather from 'react-native-vector-icons/Feather'; -import { strings } from '../../../../../../../locales/i18n'; -import GlobalAlert from '../../../../../UI/GlobalAlert'; -import { showAlert } from '../../../../../../actions/alert'; -import ClipboardManager from '../../../../../../core/ClipboardManager'; +import { strings } from '../../../../../locales/i18n'; +import GlobalAlert from '../../../UI/GlobalAlert'; +import { showAlert } from '../../../../actions/alert'; +import ClipboardManager from '../../../../core/ClipboardManager'; import Header from '../AddNickNameHeader'; import ShowBlockExplorer from '../ShowBlockExplorer'; -import { useTheme } from '../../../../../../util/theme'; +import { useTheme } from '../../../../util/theme'; import createStyles from './styles'; import { AddNicknameProps } from './types'; import { validateAddressOrENS, shouldShowBlockExplorer, -} from '../../../../../../util/address'; -import ErrorMessage from '../../../SendFlow/ErrorMessage'; +} from '../../../../util/address'; +import ErrorMessage from '../../../Views/SendFlow/ErrorMessage'; import { CONTACT_ALREADY_SAVED, SYMBOL_ERROR, -} from '../../../../../../constants/error'; +} from '../../../../constants/error'; import { selectChainId, selectNetworkConfigurations, selectProviderType, - selectRpcUrl, -} from '../../../../../../selectors/networkController'; -import { selectIdentities } from '../../../../../../selectors/preferencesController'; -import { ContractNickNameViewSelectorsIDs } from '../../../../../../../e2e/selectors/ContractNickNameView.selectors'; + selectRpcTarget, +} from '../../../../selectors/networkController'; +import { selectIdentities } from '../../../../selectors/preferencesController'; +import { ContractNickNameViewSelectorsIDs } from '../../../../../e2e/selectors/ContractNickNameView.selectors'; const getAnalyticsParams = () => ({}); @@ -263,7 +263,7 @@ const AddNickname = (props: AddNicknameProps) => { const mapStateToProps = (state: any) => ({ providerType: selectProviderType(state), - providerRpcTarget: selectRpcUrl(state), + providerRpcTarget: selectRpcTarget(state), providerChainId: selectChainId(state), addressBook: state.engine.backgroundState.AddressBookController.addressBook, identities: selectIdentities(state), diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/styles.ts b/app/components/UI/ApproveTransactionReview/AddNickname/styles.ts similarity index 96% rename from app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/styles.ts rename to app/components/UI/ApproveTransactionReview/AddNickname/styles.ts index fe4465a827d..1db8f03dff3 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/styles.ts +++ b/app/components/UI/ApproveTransactionReview/AddNickname/styles.ts @@ -1,5 +1,5 @@ import { StyleSheet } from 'react-native'; -import { fontStyles } from '../../../../../../styles/common'; +import { fontStyles } from '../../../../styles/common'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/types.ts b/app/components/UI/ApproveTransactionReview/AddNickname/types.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionReview/AddNickname/types.ts rename to app/components/UI/ApproveTransactionReview/AddNickname/types.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/EditPermission/index.tsx b/app/components/UI/ApproveTransactionReview/EditPermission/index.tsx similarity index 93% rename from app/components/Views/confirmations/components/ApproveTransactionReview/EditPermission/index.tsx rename to app/components/UI/ApproveTransactionReview/EditPermission/index.tsx index 9098eb0d0a5..acfda80d8d6 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/EditPermission/index.tsx +++ b/app/components/UI/ApproveTransactionReview/EditPermission/index.tsx @@ -6,15 +6,15 @@ import { TouchableOpacity, TextInput, } from 'react-native'; -import { fontStyles } from '../../../../../../styles/common'; -import StyledButton from '../../../../../UI/StyledButton'; -import { strings } from '../../../../../../../locales/i18n'; -import { isNumber } from '../../../../../../util/number'; -import ConnectHeader from '../../../../../UI/ConnectHeader'; -import Device from '../../../../../../util/device'; -import ErrorMessage from '../../../SendFlow/ErrorMessage'; -import { useTheme } from '../../../../../../util/theme'; -import formatNumber from '../../../../../../util/formatNumber'; +import { fontStyles } from '../../../../styles/common'; +import StyledButton from '../../StyledButton'; +import { strings } from '../../../../../locales/i18n'; +import { isNumber } from '../../../../util/number'; +import ConnectHeader from '../../ConnectHeader'; +import Device from '../../../../util/device'; +import ErrorMessage from '../../../Views/SendFlow/ErrorMessage'; +import { useTheme } from '../../../../util/theme'; +import formatNumber from '../../../../util/formatNumber'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/ShowBlockExplorer/index.tsx b/app/components/UI/ApproveTransactionReview/ShowBlockExplorer/index.tsx similarity index 89% rename from app/components/Views/confirmations/components/ApproveTransactionReview/ShowBlockExplorer/index.tsx rename to app/components/UI/ApproveTransactionReview/ShowBlockExplorer/index.tsx index 43698e04a31..2453af37d72 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/ShowBlockExplorer/index.tsx +++ b/app/components/UI/ApproveTransactionReview/ShowBlockExplorer/index.tsx @@ -6,14 +6,14 @@ import type { NetworkState } from '@metamask/network-controller'; import Text, { TextVariant, -} from '../../../../../../component-library/components/Texts/Text'; -import { RPC } from '../../../../../../constants/network'; +} from '../../../../component-library/components/Texts/Text'; +import { RPC } from '../../../../constants/network'; import { getEtherscanAddressUrl, getEtherscanBaseUrl, -} from '../../../../../../util/etherscan'; -import { findBlockExplorerForRpc } from '../../../../../../util/networks'; -import WebviewProgressBar from '../../../../../UI/WebviewProgressBar'; +} from '../../../../util/etherscan'; +import { findBlockExplorerForRpc } from '../../../../util/networks'; +import WebviewProgressBar from '../../../UI/WebviewProgressBar'; const styles = StyleSheet.create({ progressBarWrapper: { diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.styles.ts b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.styles.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.styles.ts rename to app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.styles.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx similarity index 75% rename from app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx rename to app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx index 323db752d63..22e44f85693 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx +++ b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.test.tsx @@ -1,7 +1,7 @@ import React from 'react'; -import renderWithProvider from '../../../../../../util/test/renderWithProvider'; +import renderWithProvider from '../../../../util/test/renderWithProvider'; import VerifyContractDetails from './VerifyContractDetails'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const initialState = { engine: { @@ -12,6 +12,13 @@ const initialState = { }, }; +const DUMMY_COMPONENT = () => 'DUMMY'; + +jest.mock( + '../../../../component-library/components/Icons/Icon/Icon', + () => DUMMY_COMPONENT, +); + describe('VerifyContractDetails', () => { it('should show the token symbol', () => { const { getByText } = renderWithProvider( diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx similarity index 85% rename from app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx rename to app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx index fb4984753b4..7f5b77e3813 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx +++ b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.tsx @@ -2,22 +2,19 @@ import React, { useEffect, useMemo, useCallback } from 'react'; import { View } from 'react-native'; import Text, { TextVariant, -} from '../../../../../../component-library/components/Texts/Text'; +} from '../../../../component-library/components/Texts/Text'; import { useSelector } from 'react-redux'; -import { strings } from '../../../../../../../locales/i18n'; -import { - useAppThemeFromContext, - mockTheme, -} from '../../../../../../util/theme'; -import ConnectHeader from '../../../../../UI/ConnectHeader'; -import ContractBox from '../../../../../../component-library/components-temp/Contracts/ContractBox'; +import { strings } from '../../../../../locales/i18n'; +import { useAppThemeFromContext, mockTheme } from '../../../../util/theme'; +import ConnectHeader from '../../ConnectHeader'; +import ContractBox from '../../../../component-library/components-temp/Contracts/ContractBox'; import createStyles from './VerifyContractDetails.styles'; import { VerifyContractDetailsProps } from './VerifyContractDetails.types'; -import { findBlockExplorerForRpc } from '../../../../../../util/networks'; -import { RPC } from '../../../../../../constants/network'; -import TransactionTypes from '../../../../../../core/TransactionTypes'; -import { safeToChecksumAddress } from '../../../../../../util/address'; -import { selectTokens } from '../../../../../../selectors/tokensController'; +import { findBlockExplorerForRpc } from '../../../../util/networks'; +import { RPC } from '../../../../constants/network'; +import TransactionTypes from '../../../../core/TransactionTypes'; +import { safeToChecksumAddress } from '../../../../util/address'; +import { selectTokens } from '../../../../selectors/tokensController'; const { ASSET: { ERC20, ERC1155, ERC721 }, diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.types.ts b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.types.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.types.ts rename to app/components/UI/ApproveTransactionReview/VerifyContractDetails/VerifyContractDetails.types.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/index.ts b/app/components/UI/ApproveTransactionReview/VerifyContractDetails/index.ts similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionReview/VerifyContractDetails/index.ts rename to app/components/UI/ApproveTransactionReview/VerifyContractDetails/index.ts diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/__snapshots__/index.test.tsx.snap b/app/components/UI/ApproveTransactionReview/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/ApproveTransactionReview/__snapshots__/index.test.tsx.snap rename to app/components/UI/ApproveTransactionReview/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/index.js b/app/components/UI/ApproveTransactionReview/index.js similarity index 90% rename from app/components/Views/confirmations/components/ApproveTransactionReview/index.js rename to app/components/UI/ApproveTransactionReview/index.js index 967a06da650..59ee4bf7346 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/index.js +++ b/app/components/UI/ApproveTransactionReview/index.js @@ -7,27 +7,27 @@ import { ScrollView, } from 'react-native'; import Eth from 'ethjs-query'; -import ActionView, { ConfirmButtonState } from '../../../../UI/ActionView'; +import ActionView from '../../UI/ActionView'; import PropTypes from 'prop-types'; -import { getApproveNavbar } from '../../../../UI/Navbar'; +import { getApproveNavbar } from '../Navbar'; import { connect } from 'react-redux'; -import { getHost } from '../../../../../util/browser'; +import { getHost } from '../../../util/browser'; import { safeToChecksumAddress, getAddressAccountType, getTokenDetails, shouldShowBlockExplorer, -} from '../../../../../util/address'; -import Engine from '../../../../../core/Engine'; -import { strings } from '../../../../../../locales/i18n'; -import { setTransactionObject } from '../../../../../actions/transaction'; +} from '../../../util/address'; +import Engine from '../../../core/Engine'; +import { strings } from '../../../../locales/i18n'; +import { setTransactionObject } from '../../../actions/transaction'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; import { fromTokenMinimalUnit, hexToBN, isNumber, renderFromTokenMinimalUnit, -} from '../../../../../util/number'; +} from '../../../util/number'; import { getTicker, getNormalizedTxState, @@ -37,23 +37,23 @@ import { generateTxWithNewTokenAllowance, minimumTokenAllowance, generateApproveData, -} from '../../../../../util/transactions'; +} from '../../../util/transactions'; import Avatar, { AvatarSize, AvatarVariant, -} from '../../../../../component-library/components/Avatars/Avatar'; -import Identicon from '../../../../UI/Identicon'; -import TransactionTypes from '../../../../../core/TransactionTypes'; -import { showAlert } from '../../../../../actions/alert'; -import Analytics from '../../../../../core/Analytics/Analytics'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import TransactionHeader from '../../../../UI/TransactionHeader'; -import TransactionReviewDetailsCard from '../TransactionReview/TransactionReviewDetailsCard'; -import AppConstants from '../../../../../core/AppConstants'; -import { UINT256_HEX_MAX_VALUE } from '../../../../../constants/transaction'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import { getBlockaidMetricsParams } from '../../../../../util/blockaid'; +} from '../../../component-library/components/Avatars/Avatar'; +import Identicon from '../../UI/Identicon'; +import TransactionTypes from '../../../core/TransactionTypes'; +import { showAlert } from '../../../actions/alert'; +import Analytics from '../../../core/Analytics/Analytics'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import TransactionHeader from '../../UI/TransactionHeader'; +import TransactionReviewDetailsCard from '../../UI/TransactionReview/TransactionReviewDetailsCard'; +import AppConstants from '../../../core/AppConstants'; +import { UINT256_HEX_MAX_VALUE } from '../../../constants/transaction'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; +import { getBlockaidMetricsParams } from '../../../util/blockaid'; import { withNavigation } from '@react-navigation/compat'; import { isTestNet, @@ -62,42 +62,40 @@ import { isMainnetByChainId, TESTNET_FAUCETS, isTestNetworkWithFaucet, - getDecimalChainId, -} from '../../../../../util/networks'; -import CustomSpendCap from '../../../../../component-library/components-temp/CustomSpendCap'; +} from '../../../util/networks'; +import CustomSpendCap from '../../../component-library/components-temp/CustomSpendCap'; import IonicIcon from 'react-native-vector-icons/Ionicons'; -import Logger from '../../../../../util/Logger'; -import ButtonLink from '../../../../../component-library/components/Buttons/Button/variants/ButtonLink'; -import TransactionReview from '../TransactionReview/TransactionReviewEIP1559Update'; -import ClipboardManager from '../../../../../core/ClipboardManager'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import withQRHardwareAwareness from '../../../../UI/QRHardware/withQRHardwareAwareness'; -import QRSigningDetails from '../../../../UI/QRHardware/QRSigningDetails'; -import Routes from '../../../../../constants/navigation/Routes'; +import Logger from '../../../util/Logger'; +import ButtonLink from '../../../component-library/components/Buttons/Button/variants/ButtonLink'; +import TransactionReview from '../../UI/TransactionReview/TransactionReviewEIP1559Update'; +import ClipboardManager from '../../../core/ClipboardManager'; +import { ThemeContext, mockTheme } from '../../../util/theme'; +import withQRHardwareAwareness from '../QRHardware/withQRHardwareAwareness'; +import QRSigningDetails from '../QRHardware/QRSigningDetails'; +import Routes from '../../../constants/navigation/Routes'; import createStyles from './styles'; import { selectChainId, selectNetworkConfigurations, selectProviderType, selectTicker, - selectRpcUrl, -} from '../../../../../selectors/networkController'; -import { selectTokenList } from '../../../../../selectors/tokenListController'; -import { selectTokensLength } from '../../../../../selectors/tokensController'; -import { selectAccountsLength } from '../../../../../selectors/accountTrackerController'; + selectRpcTarget, +} from '../../../selectors/networkController'; +import { selectTokenList } from '../../../selectors/tokenListController'; +import { selectTokensLength } from '../../../selectors/tokensController'; +import { selectAccountsLength } from '../../../selectors/accountTrackerController'; import Text, { TextVariant, -} from '../../../../../component-library/components/Texts/Text'; +} from '../../../component-library/components/Texts/Text'; import ApproveTransactionHeader from '../ApproveTransactionHeader'; import VerifyContractDetails from './VerifyContractDetails/VerifyContractDetails'; import ShowBlockExplorer from './ShowBlockExplorer'; -import { isNetworkRampNativeTokenSupported } from '../../../../../components/UI/Ramp/utils'; -import { getRampNetworks } from '../../../../../reducers/fiatOrders'; -import SkeletonText from '../../../../../components/UI/Ramp/components/SkeletonText'; -import InfoModal from '../../../../UI/Swaps/components/InfoModal'; -import { ResultType } from '../BlockaidBanner/BlockaidBanner.types'; +import { isNetworkRampNativeTokenSupported } from '../Ramp/utils'; +import { getRampNetworks } from '../../../reducers/fiatOrders'; +import SkeletonText from '../Ramp/components/SkeletonText'; +import InfoModal from '../../../components/UI/Swaps/components/InfoModal'; import TransactionBlockaidBanner from '../TransactionBlockaidBanner/TransactionBlockaidBanner'; -import { regex } from '../../../../../util/regex'; +import { regex } from '../../../util/regex'; const { ORIGIN_DEEPLINK, ORIGIN_QR_CODE } = AppConstants.DEEPLINKS; const POLLING_INTERVAL_ESTIMATED_L1_FEE = 30000; @@ -413,7 +411,6 @@ class ApproveTransactionReview extends PureComponent { const approveAmount = fromTokenMinimalUnit( hexToBN(encodedHexAmount), tokenDecimals, - false, ); const { name: method } = await getMethodData(data); @@ -537,7 +534,7 @@ class ApproveTransactionReview extends PureComponent { const params = { account_type: getAddressAccountType(transaction?.from), dapp_host_name: transaction?.origin, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, active_currency: { value: tokenSymbol, anonymous: true }, number_tokens_requested: { value: originalApproveAmount, @@ -702,30 +699,6 @@ class ApproveTransactionReview extends PureComponent { ); }; - getConfirmButtonState() { - const { transaction } = this.props; - const { id, currentTransactionSecurityAlertResponse } = transaction; - let confirmButtonState = ConfirmButtonState.Normal; - if ( - id && - currentTransactionSecurityAlertResponse?.id && - currentTransactionSecurityAlertResponse.id === id - ) { - if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Malicious - ) { - confirmButtonState = ConfirmButtonState.Error; - } else if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Warning - ) { - confirmButtonState = ConfirmButtonState.Warning; - } - } - return confirmButtonState; - } - renderDetails = () => { const { originalApproveAmount, @@ -839,7 +812,6 @@ class ApproveTransactionReview extends PureComponent { onCancelPress={this.onCancelPress} onConfirmPress={this.onConfirmPress} confirmDisabled={shouldDisableConfirmButton} - confirmButtonState={this.getConfirmButtonState()} > @@ -1266,7 +1238,7 @@ const mapStateToProps = (state) => ({ tokensLength: selectTokensLength(state), accountsLength: selectAccountsLength(state), providerType: selectProviderType(state), - providerRpcTarget: selectRpcUrl(state), + providerRpcTarget: selectRpcTarget(state), primaryCurrency: state.settings.primaryCurrency, activeTabUrl: getActiveTabUrl(state), chainId: selectChainId(state), diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/index.test.tsx b/app/components/UI/ApproveTransactionReview/index.test.tsx similarity index 85% rename from app/components/Views/confirmations/components/ApproveTransactionReview/index.test.tsx rename to app/components/UI/ApproveTransactionReview/index.test.tsx index 19a48381040..2f61f51496a 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/index.test.tsx +++ b/app/components/UI/ApproveTransactionReview/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { shallow } from 'enzyme'; -import ApproveTransactionModal from '.'; +import ApproveTransactionModal from './'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/ApproveTransactionReview/styles.ts b/app/components/UI/ApproveTransactionReview/styles.ts similarity index 97% rename from app/components/Views/confirmations/components/ApproveTransactionReview/styles.ts rename to app/components/UI/ApproveTransactionReview/styles.ts index d67d505af20..59321bfb64f 100644 --- a/app/components/Views/confirmations/components/ApproveTransactionReview/styles.ts +++ b/app/components/UI/ApproveTransactionReview/styles.ts @@ -1,7 +1,7 @@ import { StyleSheet } from 'react-native'; -import { fontStyles } from '../../../../../styles/common'; -import Device from '../../../../../util/device'; +import { fontStyles } from '../../../styles/common'; +import Device from '../../../util/device'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/UI/AssetOverview/AboutAsset/AboutAsset.styles.tsx b/app/components/UI/AssetOverview/AboutAsset/AboutAsset.styles.tsx index 2f8436f3bfc..f5daaad2d1e 100644 --- a/app/components/UI/AssetOverview/AboutAsset/AboutAsset.styles.tsx +++ b/app/components/UI/AssetOverview/AboutAsset/AboutAsset.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { theme: Theme }) => { diff --git a/app/components/UI/AssetOverview/AboutAsset/ContentDisplay.styles.tsx b/app/components/UI/AssetOverview/AboutAsset/ContentDisplay.styles.tsx index c5af1067484..6b29dbcf365 100644 --- a/app/components/UI/AssetOverview/AboutAsset/ContentDisplay.styles.tsx +++ b/app/components/UI/AssetOverview/AboutAsset/ContentDisplay.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { theme: Theme }) => { diff --git a/app/components/UI/AssetOverview/AssetActionButton/AssetActionButton.styles.tsx b/app/components/UI/AssetOverview/AssetActionButton/AssetActionButton.styles.tsx index 850cb3f0ccf..7db9c31b602 100644 --- a/app/components/UI/AssetOverview/AssetActionButton/AssetActionButton.styles.tsx +++ b/app/components/UI/AssetOverview/AssetActionButton/AssetActionButton.styles.tsx @@ -1,6 +1,6 @@ import { StyleSheet } from 'react-native'; import Device from '../../../../util/device'; -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; const createStyles = (params: { theme: Theme }) => { const { theme } = params; diff --git a/app/components/UI/AssetOverview/AssetActionButton/__snapshots__/index.test.tsx.snap b/app/components/UI/AssetOverview/AssetActionButton/__snapshots__/index.test.tsx.snap index b9f0ca1c80e..d195c0fb821 100644 --- a/app/components/UI/AssetOverview/AssetActionButton/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/AssetOverview/AssetActionButton/__snapshots__/index.test.tsx.snap @@ -84,7 +84,7 @@ exports[`AssetActionButtons should render type add correctly 1`] = ` style={ Object { "alignContent": "center", - "color": "#FFFFFF", + "color": "#FCFCFC", "justifyContent": "center", "textAlign": "center", } @@ -145,7 +145,7 @@ exports[`AssetActionButtons should render type information correctly 1`] = ` style={ Object { "alignContent": "center", - "color": "#FFFFFF", + "color": "#FCFCFC", "justifyContent": "center", "textAlign": "center", } @@ -201,14 +201,14 @@ exports[`AssetActionButtons should render type receive correctly 1`] = ` > { diff --git a/app/components/UI/AssetOverview/AssetOverview.tsx b/app/components/UI/AssetOverview/AssetOverview.tsx index a946a79f9aa..94f78f96209 100644 --- a/app/components/UI/AssetOverview/AssetOverview.tsx +++ b/app/components/UI/AssetOverview/AssetOverview.tsx @@ -26,7 +26,7 @@ import { selectCurrentCurrency, } from '../../../selectors/currencyRateController'; import { selectContractExchangeRates } from '../../../selectors/tokenRatesController'; -import { selectAccountsByChainId } from '../../../selectors/accountTrackerController'; +import { selectAccounts } from '../../../selectors/accountTrackerController'; import { selectContractBalances } from '../../../selectors/tokenBalancesController'; import { selectSelectedAddress } from '../../../selectors/preferencesController'; import Logger from '../../../util/Logger'; @@ -36,7 +36,6 @@ import { hexToBN, renderFromTokenMinimalUnit, renderFromWei, - toHexadecimal, weiToFiat, } from '../../../util/number'; import { getEther } from '../../../util/transactions'; @@ -66,7 +65,7 @@ const AssetOverview: React.FC = ({ const [timePeriod, setTimePeriod] = React.useState('1d'); const currentCurrency = useSelector(selectCurrentCurrency); const conversionRate = useSelector(selectConversionRate); - const accountsByChainId = useSelector(selectAccountsByChainId); + const accounts = useSelector(selectAccounts); const primaryCurrency = useSelector( (state: RootStateOrAny) => state.settings.primaryCurrency, ); @@ -166,13 +165,9 @@ const AssetOverview: React.FC = ({ let balance, balanceFiat; if (asset.isETH) { - balance = renderFromWei( - accountsByChainId[toHexadecimal(chainId)][selectedAddress]?.balance, - ); + balance = renderFromWei(accounts[selectedAddress]?.balance); balanceFiat = weiToFiat( - hexToBN( - accountsByChainId[toHexadecimal(chainId)][selectedAddress]?.balance, - ), + hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency, ); diff --git a/app/components/UI/AssetOverview/Balance/Balance.styles.tsx b/app/components/UI/AssetOverview/Balance/Balance.styles.tsx index 3944c0da057..97d6431ca33 100644 --- a/app/components/UI/AssetOverview/Balance/Balance.styles.tsx +++ b/app/components/UI/AssetOverview/Balance/Balance.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { theme: Theme }) => { diff --git a/app/components/UI/AssetOverview/ChartNavigationButton/ChartNavigationButton.styles.tsx b/app/components/UI/AssetOverview/ChartNavigationButton/ChartNavigationButton.styles.tsx index d468e7e2502..fbf94b7a0bf 100644 --- a/app/components/UI/AssetOverview/ChartNavigationButton/ChartNavigationButton.styles.tsx +++ b/app/components/UI/AssetOverview/ChartNavigationButton/ChartNavigationButton.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { diff --git a/app/components/UI/AssetOverview/Price/Price.styles.tsx b/app/components/UI/AssetOverview/Price/Price.styles.tsx index cea4c101423..780d9677571 100644 --- a/app/components/UI/AssetOverview/Price/Price.styles.tsx +++ b/app/components/UI/AssetOverview/Price/Price.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { diff --git a/app/components/UI/AssetOverview/PriceChart/PriceChart.styles.tsx b/app/components/UI/AssetOverview/PriceChart/PriceChart.styles.tsx index d027fbcc803..b4b304794c0 100644 --- a/app/components/UI/AssetOverview/PriceChart/PriceChart.styles.tsx +++ b/app/components/UI/AssetOverview/PriceChart/PriceChart.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { Dimensions, StyleSheet, TextStyle } from 'react-native'; export const CHART_HEIGHT = Dimensions.get('screen').height * 0.44; diff --git a/app/components/UI/BackupAlert/BackupAlert.constants.ts b/app/components/UI/BackupAlert/BackupAlert.constants.ts deleted file mode 100644 index 41de0e70ca6..00000000000 --- a/app/components/UI/BackupAlert/BackupAlert.constants.ts +++ /dev/null @@ -1,2 +0,0 @@ -// eslint-disable-next-line import/prefer-default-export -export const PROTECT_WALLET_BUTTON = 'protect-your-wallet-button'; diff --git a/app/components/UI/BackupAlert/BackupAlert.styles.ts b/app/components/UI/BackupAlert/BackupAlert.styles.ts deleted file mode 100644 index cfa88b311b4..00000000000 --- a/app/components/UI/BackupAlert/BackupAlert.styles.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { StyleSheet } from 'react-native'; -import Device from '../../../util/device'; -import { Theme } from '../../../util/theme/models'; - -/** - * Style sheet function for BackupAlert component. - * - * @param params Style sheet params. - * @param params.theme App theme from ThemeContext. - * @returns StyleSheet object. - */ -const styleSheet = (params: { theme: Theme }) => { - const { theme } = params; - const { colors } = theme; - - return StyleSheet.create({ - container: { - backgroundColor: colors.background.default, - position: 'absolute', - left: 16, - right: 16, - borderRadius: 8, - borderColor: colors.warning.default, - borderWidth: 1, - }, - backupAlertWrapper: { - flex: 1, - backgroundColor: colors.warning.muted, - padding: 14, - }, - backupAlertIconWrapper: { - marginRight: 10, - }, - backupAlertIcon: { - fontSize: 22, - color: colors.text.default, - }, - backupAlertTitle: { - marginBottom: 14, - }, - backupAlertMessage: { - color: colors.primary.default, - marginLeft: 14, - flex: 1, - textAlign: 'right', - }, - touchableView: { - flexDirection: 'row', - }, - modalViewInBrowserView: { - bottom: Device.isIphoneX() ? 180 : 170, - }, - modalViewNotInBrowserView: { - bottom: Device.isIphoneX() ? 120 : 110, - }, - buttonsWrapper: { - flexDirection: 'row-reverse', - alignContent: 'flex-end', - flex: 1, - }, - dismissButton: { - flex: 1, - }, - }); -}; - -export default styleSheet; diff --git a/app/components/UI/BackupAlert/BackupAlert.test.tsx b/app/components/UI/BackupAlert/BackupAlert.test.tsx deleted file mode 100644 index 2526d5ef9fc..00000000000 --- a/app/components/UI/BackupAlert/BackupAlert.test.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import React from 'react'; - -import BackupAlert from '.'; -import renderWithProvider from '../../../util/test/renderWithProvider'; -import Engine from '../../../core/Engine'; -import { fireEvent } from '@testing-library/react-native'; - -const mockEngine = Engine; - -const initialState = { - user: { - seedphraseBackedUp: false, - passwordSet: false, - backUpSeedphraseVisible: true, - }, - wizard: { - step: 0, - }, -}; -const mockNavigation = { - navigate: jest.fn(), - dangerouslyGetState: jest.fn(() => ({ routes: [{ name: 'WalletView' }] })), -}; -jest.mock('../../../core/Engine', () => ({ - init: () => mockEngine.init({}), -})); - -jest.mock('react-redux', () => ({ - ...jest.requireActual('react-redux'), - useSelector: jest - .fn() - .mockImplementation((callback) => callback(initialState)), -})); - -describe('BackupAlert', () => { - it('should render correctly', () => { - const { toJSON } = renderWithProvider( - null} />, - { - state: initialState, - }, - ); - expect(toJSON()).toMatchSnapshot(); - }); - - it('navigates to backup flow when right button is pressed', () => { - const { getByTestId } = renderWithProvider( - null} />, - { - state: initialState, - }, - ); - const rightButton = getByTestId('protect-your-wallet-button'); - fireEvent.press(rightButton); - expect(mockNavigation.navigate).toHaveBeenCalledWith('SetPasswordFlow', { - screen: 'AccountBackupStep1', - }); - }); -}); diff --git a/app/components/UI/BackupAlert/BackupAlert.tsx b/app/components/UI/BackupAlert/BackupAlert.tsx deleted file mode 100644 index 832f9839824..00000000000 --- a/app/components/UI/BackupAlert/BackupAlert.tsx +++ /dev/null @@ -1,180 +0,0 @@ -/* eslint-disable react/prop-types */ -import React, { useState, useEffect } from 'react'; -import { - View, - TouchableOpacity, - InteractionManager, - Platform, -} from 'react-native'; -import ElevatedView from 'react-native-elevated-view'; -import { strings } from '../../../../locales/i18n'; -import { baseStyles } from '../../../styles/common'; -import { useDispatch, useSelector } from 'react-redux'; -import { backUpSeedphraseAlertNotVisible } from '../../../actions/user'; -import { findRouteNameFromNavigatorState } from '../../../util/general'; -import { MetaMetricsEvents } from '../../../core/Analytics'; -import AnalyticsV2 from '../../../util/analyticsV2'; -import generateTestId from '../../../../wdio/utils/generateTestId'; -import { - NOTIFICATION_REMIND_ME_LATER_BUTTON_ID, - SECURE_WALLET_BACKUP_ALERT_MODAL, -} from '../../../../wdio/screen-objects/testIDs/Screens/WalletView.testIds'; -import styleSheet from './BackupAlert.styles'; -import { useStyles } from '../../../component-library/hooks'; -import { BackupAlertI } from './BackupAlert.types'; -import { PROTECT_WALLET_BUTTON } from './BackupAlert.constants'; -import Icon, { - IconColor, - IconName, - IconSize, -} from '../../../component-library/components/Icons/Icon'; -import Text, { - TextVariant, -} from '../../../component-library/components/Texts/Text'; - -const BROWSER_ROUTE = 'BrowserView'; - -const BLOCKED_LIST = [ - 'ImportPrivateKey', - 'Send', - 'SendTo', - 'Amount', - 'Confirm', - 'Approval', - 'Approve', - 'AddBookmark', - 'RevealPrivateCredentialView', - 'AccountBackupStep', - 'ManualBackupStep', -]; - -const BackupAlert = ({ navigation, onDismiss }: BackupAlertI) => { - const { styles } = useStyles(styleSheet, {}); - - const [inBrowserView, setInBrowserView] = useState(false); - const [inBlockedView, setInBlockedView] = useState(false); - const [isVisible, setIsVisible] = useState(true); - - const { seedphraseBackedUp, backUpSeedphraseVisible } = useSelector( - (state: any) => state.user, - ); - - const onboardingWizardStep = useSelector((state: any) => state.wizard.step); - const dispatch = useDispatch(); - - const currentRouteName = findRouteNameFromNavigatorState( - navigation.dangerouslyGetState().routes, - ); - - useEffect(() => { - const isInBrowserView = currentRouteName === BROWSER_ROUTE; - const blockedView = - BLOCKED_LIST.find((path) => currentRouteName.includes(path)) || - currentRouteName === 'SetPasswordFlow'; - - setInBrowserView(isInBrowserView); - setInBlockedView(!!blockedView); - }, [currentRouteName]); - - const goToBackupFlow = () => { - setIsVisible(false); - navigation.navigate('SetPasswordFlow', { - screen: 'AccountBackupStep1', - }); - InteractionManager.runAfterInteractions(() => { - AnalyticsV2.trackEvent( - MetaMetricsEvents.WALLET_SECURITY_PROTECT_ENGAGED, - { - wallet_protection_required: false, - source: 'Backup Alert', - }, - ); - }); - }; - - const onDismissAlert = () => { - dispatch(backUpSeedphraseAlertNotVisible()); - InteractionManager.runAfterInteractions(() => { - AnalyticsV2.trackEvent( - MetaMetricsEvents.WALLET_SECURITY_PROTECT_DISMISSED, - { - wallet_protection_required: false, - source: 'Backup Alert', - }, - ); - }); - if (onDismiss) onDismiss(); - }; - - const shouldNotRenderAlert = - seedphraseBackedUp || - inBlockedView || - !backUpSeedphraseVisible || - onboardingWizardStep !== 0 || - !isVisible; - - return shouldNotRenderAlert ? null : ( - - - - - - - - - {strings('backup_alert.title')} - - - - - {strings('backup_alert.right_button')} - - - - - {strings('backup_alert.left_button')} - - - - - - - - ); -}; - -export default BackupAlert; diff --git a/app/components/UI/BackupAlert/BackupAlert.types.ts b/app/components/UI/BackupAlert/BackupAlert.types.ts deleted file mode 100644 index 2bb40e1c788..00000000000 --- a/app/components/UI/BackupAlert/BackupAlert.types.ts +++ /dev/null @@ -1,4 +0,0 @@ -export interface BackupAlertI { - navigation: any; - onDismiss: () => void; -} diff --git a/app/components/UI/BackupAlert/__snapshots__/BackupAlert.test.tsx.snap b/app/components/UI/BackupAlert/__snapshots__/BackupAlert.test.tsx.snap deleted file mode 100644 index 8e500d44ceb..00000000000 --- a/app/components/UI/BackupAlert/__snapshots__/BackupAlert.test.tsx.snap +++ /dev/null @@ -1,156 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`BackupAlert should render correctly 1`] = ` - - - - - - - - - Protect your wallet - - - - - Protect wallet - - - - - Remind me later - - - - - - - -`; diff --git a/app/components/UI/BackupAlert/__snapshots__/index.test.tsx.snap b/app/components/UI/BackupAlert/__snapshots__/index.test.tsx.snap new file mode 100644 index 00000000000..c7fd0d7c159 --- /dev/null +++ b/app/components/UI/BackupAlert/__snapshots__/index.test.tsx.snap @@ -0,0 +1,37 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`BackupAlert should render correctly 1`] = ` + + + +`; diff --git a/app/components/UI/BackupAlert/index.js b/app/components/UI/BackupAlert/index.js new file mode 100644 index 00000000000..a173b803c8e --- /dev/null +++ b/app/components/UI/BackupAlert/index.js @@ -0,0 +1,268 @@ +import React, { PureComponent } from 'react'; +import { + Text, + StyleSheet, + View, + TouchableOpacity, + InteractionManager, + Platform, +} from 'react-native'; +import PropTypes from 'prop-types'; +import EvilIcons from 'react-native-vector-icons/EvilIcons'; +import ElevatedView from 'react-native-elevated-view'; +import { strings } from '../../../../locales/i18n'; +import { fontStyles, baseStyles } from '../../../styles/common'; +import Device from '../../../util/device'; +import { connect } from 'react-redux'; +import { backUpSeedphraseAlertNotVisible } from '../../../actions/user'; +import { findRouteNameFromNavigatorState } from '../../../util/general'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import generateTestId from '../../../../wdio/utils/generateTestId'; +import { + NOTIFICATION_REMIND_ME_LATER_BUTTON_ID, + SECURE_WALLET_BACKUP_ALERT_MODAL, +} from '../../../../wdio/screen-objects/testIDs/Screens/WalletView.testIds'; + +import { ThemeContext, mockTheme } from '../../../util/theme'; + +const BROWSER_ROUTE = 'BrowserView'; + +const createStyles = (colors) => + StyleSheet.create({ + container: { + backgroundColor: colors.background.default, + position: 'absolute', + left: 16, + right: 16, + borderRadius: 8, + borderColor: colors.warning.default, + borderWidth: 1, + }, + backupAlertWrapper: { + flex: 1, + backgroundColor: colors.warning.muted, + padding: 14, + }, + backupAlertIconWrapper: { + marginRight: 10, + }, + backupAlertIcon: { + fontSize: 22, + ...fontStyles.bold, + color: colors.text.default, + }, + backupAlertTitle: { + fontSize: 14, + marginBottom: 14, + color: colors.text.default, + ...fontStyles.bold, + }, + backupAlertMessage: { + fontSize: 12, + color: colors.primary.default, + marginLeft: 14, + flex: 1, + textAlign: 'right', + ...fontStyles.normal, + }, + touchableView: { + flexDirection: 'row', + }, + modalViewInBrowserView: { + bottom: Device.isIphoneX() ? 180 : 170, + }, + modalViewNotInBrowserView: { + bottom: Device.isIphoneX() ? 120 : 110, + }, + buttonsWrapper: { + flexDirection: 'row-reverse', + alignContent: 'flex-end', + flex: 1, + }, + dismissButton: { + flex: 1, + }, + }); + +const BLOCKED_LIST = [ + 'ImportPrivateKey', + 'Send', + 'SendTo', + 'Amount', + 'Confirm', + 'Approval', + 'Approve', + 'AddBookmark', + 'RevealPrivateCredentialView', + 'AccountBackupStep', + 'ManualBackupStep', +]; + +/** + * PureComponent that renders an alert shown when the + * seed phrase hasn't been backed up + */ +class BackupAlert extends PureComponent { + static propTypes = { + navigation: PropTypes.object, + /** + * redux flag that indicates if the user + * completed the seed phrase backup flow + */ + seedphraseBackedUp: PropTypes.bool, + /** + * redux flag that indicates if the alert should be shown + */ + backUpSeedphraseVisible: PropTypes.bool, + /** + * Dismisses the alert + */ + backUpSeedphraseAlertNotVisible: PropTypes.func.isRequired, + /** + * A second prop to be used in conjunction with the above + * currently used to toggle the backup reminder modal (a second time) + */ + onDismiss: PropTypes.func, + /** + * Used to determine if onboarding has been completed + * we only want to render the backup alert after onboarding + */ + onboardingWizardStep: PropTypes.number, + }; + + state = { + inBrowserView: false, + inAccountBackupStep: false, + }; + + componentDidUpdate = async (prevProps) => { + if ( + prevProps.navigation.dangerouslyGetState() !== + this.props.navigation.dangerouslyGetState() + ) { + const currentRouteName = findRouteNameFromNavigatorState( + this.props.navigation.dangerouslyGetState().routes, + ); + + const inBrowserView = currentRouteName === BROWSER_ROUTE; + const blockedView = + BLOCKED_LIST.find((path) => currentRouteName.includes(path)) || + currentRouteName === 'SetPasswordFlow'; + // eslint-disable-next-line react/no-did-update-set-state + this.setState({ inBrowserView, blockedView }); + } + }; + + goToBackupFlow = () => { + this.props.navigation.navigate('SetPasswordFlow', { + screen: 'AccountBackupStep1', + }); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent( + MetaMetricsEvents.WALLET_SECURITY_PROTECT_ENGAGED, + { + wallet_protection_required: false, + source: 'Backup Alert', + }, + ); + }); + }; + + onDismiss = () => { + const { onDismiss, backUpSeedphraseAlertNotVisible } = this.props; + backUpSeedphraseAlertNotVisible(); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent( + MetaMetricsEvents.WALLET_SECURITY_PROTECT_DISMISSED, + { + wallet_protection_required: false, + source: 'Backup Alert', + }, + ); + }); + if (onDismiss) onDismiss(); + }; + + render() { + const { + seedphraseBackedUp, + backUpSeedphraseVisible, + onboardingWizardStep, + } = this.props; + const { inBrowserView, blockedView } = this.state; + const colors = this.context.colors || mockTheme.colors; + const styles = createStyles(colors); + + const shouldNotRenderAlert = + seedphraseBackedUp || + blockedView || + !backUpSeedphraseVisible || + onboardingWizardStep !== 0; + + if (shouldNotRenderAlert) return null; + return ( + + + + + + + + + {strings('backup_alert.title')} + + + + + {strings('backup_alert.right_button')} + + + + + {strings('backup_alert.left_button')} + + + + + + + + ); + } +} + +const mapStateToProps = (state) => ({ + seedphraseBackedUp: state.user.seedphraseBackedUp, + backUpSeedphraseVisible: state.user.backUpSeedphraseVisible, + onboardingWizardStep: state.wizard.step, +}); + +const mapDispatchToProps = (dispatch) => ({ + backUpSeedphraseAlertNotVisible: () => + dispatch(backUpSeedphraseAlertNotVisible()), +}); + +BackupAlert.contextType = ThemeContext; + +export default connect(mapStateToProps, mapDispatchToProps)(BackupAlert); diff --git a/app/components/UI/BackupAlert/index.test.tsx b/app/components/UI/BackupAlert/index.test.tsx new file mode 100644 index 00000000000..612f12cc815 --- /dev/null +++ b/app/components/UI/BackupAlert/index.test.tsx @@ -0,0 +1,29 @@ +/* eslint-disable react/jsx-no-bind */ +import React from 'react'; +import configureMockStore from 'redux-mock-store'; +import { shallow } from 'enzyme'; +import BackupAlert from './'; +import { Provider } from 'react-redux'; + +const mockStore = configureMockStore(); +const initialState = { + user: { + seedphraseBackedUp: false, + passwordSet: false, + }, + wizard: { + step: 0, + }, +}; +const store = mockStore(initialState); + +describe('BackupAlert', () => { + it('should render correctly', () => { + const wrapper = shallow( + + + , + ); + expect(wrapper).toMatchSnapshot(); + }); +}); diff --git a/app/components/UI/BackupAlert/index.ts b/app/components/UI/BackupAlert/index.ts deleted file mode 100644 index b2fa1af18fc..00000000000 --- a/app/components/UI/BackupAlert/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from './BackupAlert'; diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.constants.ts b/app/components/UI/BlockaidBanner/BlockaidBanner.constants.ts similarity index 100% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.constants.ts rename to app/components/UI/BlockaidBanner/BlockaidBanner.constants.ts diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.stories.tsx b/app/components/UI/BlockaidBanner/BlockaidBanner.stories.tsx similarity index 86% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.stories.tsx rename to app/components/UI/BlockaidBanner/BlockaidBanner.stories.tsx index cec55db579c..68ecdafe6ed 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.stories.tsx +++ b/app/components/UI/BlockaidBanner/BlockaidBanner.stories.tsx @@ -7,8 +7,8 @@ import { storiesOf } from '@storybook/react-native'; import { SAMPLE_BANNERALERT_DESCRIPTION, SAMPLE_BANNERALERT_TITLE, -} from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.constants'; -import { storybookPropsGroupID } from '../../../../../component-library/constants/storybook.constants'; +} from '../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.constants'; +import { storybookPropsGroupID } from '../../../component-library/constants/storybook.constants'; import BlockaidBanner from './BlockaidBanner'; import { BlockaidBannerProps, FlagType, Reason } from './BlockaidBanner.types'; diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.styles.ts b/app/components/UI/BlockaidBanner/BlockaidBanner.styles.ts similarity index 55% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.styles.ts rename to app/components/UI/BlockaidBanner/BlockaidBanner.styles.ts index 063e47da7b3..0091222db09 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.styles.ts +++ b/app/components/UI/BlockaidBanner/BlockaidBanner.styles.ts @@ -1,5 +1,5 @@ // Third party dependencies. -import { Theme } from '../../../../../util/theme/models'; +import { Theme } from '../../../util/theme/models'; import { StyleSheet, ViewStyle } from 'react-native'; import { BlockaidBannerStyleSheetVars } from './BlockaidBanner.types'; /** @@ -36,38 +36,6 @@ const styleSheet = (_params: { marginRight: 10, marginBottom: 20, }, - bannerSectionSmall: { - flexDirection: 'row', - alignItems: 'center', - borderWidth: 1, - borderRadius: 4, - borderColor: _params.theme.colors.border.default, - marginTop: 20, - marginLeft: 10, - marginRight: 10, - marginBottom: 20, - padding: 10, - }, - bannerSectionSmallSpaced: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', - borderWidth: 1, - borderRadius: 4, - borderColor: _params.theme.colors.border.default, - marginTop: 20, - marginLeft: 10, - marginRight: 10, - marginBottom: 20, - padding: 10, - }, - infoText: { - marginLeft: 8, - }, - flexRowSection: { - flexDirection: 'row', - alignItems: 'center', - }, }); export default styleSheet; diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.test.tsx b/app/components/UI/BlockaidBanner/BlockaidBanner.test.tsx similarity index 91% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.test.tsx rename to app/components/UI/BlockaidBanner/BlockaidBanner.test.tsx index 7951d918320..da07dc8291b 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.test.tsx +++ b/app/components/UI/BlockaidBanner/BlockaidBanner.test.tsx @@ -2,18 +2,18 @@ import React from 'react'; import { fireEvent } from '@testing-library/react-native'; -import { TESTID_ACCORDION_CONTENT } from '../../../../../component-library/components/Accordions/Accordion/Accordion.constants'; -import { TESTID_ACCORDIONHEADER } from '../../../../../component-library/components/Accordions/Accordion/foundation/AccordionHeader/AccordionHeader.constants'; -import { BANNERALERT_TEST_ID } from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.constants'; +import { TESTID_ACCORDION_CONTENT } from '../../../component-library/components/Accordions/Accordion/Accordion.constants'; +import { TESTID_ACCORDIONHEADER } from '../../../component-library/components/Accordions/Accordion/foundation/AccordionHeader/AccordionHeader.constants'; +import { BANNERALERT_TEST_ID } from '../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.constants'; import BlockaidBanner from './BlockaidBanner'; import { ATTRIBUTION_LINE_TEST_ID, FALSE_POSITIVE_REPOST_LINE_TEST_ID, } from './BlockaidBanner.constants'; import { ResultType, Reason } from './BlockaidBanner.types'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; +import renderWithProvider from '../../../util/test/renderWithProvider'; -jest.mock('../../../../../util/blockaid', () => ({ +jest.mock('../../../util/blockaid', () => ({ isBlockaidFeatureEnabled: jest.fn().mockReturnValue(true), isBlockaidSupportedOnCurrentChain: jest.fn().mockReturnValue(true), })); @@ -25,7 +25,7 @@ jest.mock('react-native-gzip', () => ({ const mockState = { engine: { backgroundState: { - NetworkController: { providerConfig: { chainId: '0x1' } }, + NetworkController: { providerConfig: { chainId: '1' } }, PreferencesController: { securityAlertsEnabled: true }, }, }, @@ -184,7 +184,7 @@ describe('BlockaidBanner', () => { const mockStateNetwork = { engine: { backgroundState: { - NetworkController: { providerConfig: { chainId: '0xfa' } }, + NetworkController: { providerConfig: { chainId: '250' } }, PreferencesController: { securityAlertsEnabled: true }, }, }, @@ -203,7 +203,7 @@ describe('BlockaidBanner', () => { const mockStateNetwork = { engine: { backgroundState: { - NetworkController: { providerConfig: { chainId: '0x1' } }, + NetworkController: { providerConfig: { chainId: '1' } }, PreferencesController: { securityAlertsEnabled: false }, }, }, diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.tsx b/app/components/UI/BlockaidBanner/BlockaidBanner.tsx similarity index 74% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.tsx rename to app/components/UI/BlockaidBanner/BlockaidBanner.tsx index 67335fc2422..6df2cea596a 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.tsx +++ b/app/components/UI/BlockaidBanner/BlockaidBanner.tsx @@ -5,24 +5,24 @@ import { View } from 'react-native-animatable'; import { captureException } from '@sentry/react-native'; import { deflate } from 'react-native-gzip'; -import { strings } from '../../../../../../locales/i18n'; -import { AccordionHeaderHorizontalAlignment } from '../../../../../component-library/components/Accordions/Accordion'; -import Accordion from '../../../../../component-library/components/Accordions/Accordion/Accordion'; -import { BannerAlertSeverity } from '../../../../../component-library/components/Banners/Banner'; -import { DEFAULT_BANNERBASE_DESCRIPTION_TEXTVARIANT } from '../../../../../component-library/components/Banners/Banner/foundation/BannerBase/BannerBase.constants'; -import BannerAlert from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert'; +import { strings } from '../../../../locales/i18n'; +import { AccordionHeaderHorizontalAlignment } from '../../../component-library/components/Accordions/Accordion'; +import Accordion from '../../../component-library/components/Accordions/Accordion/Accordion'; +import { BannerAlertSeverity } from '../../../component-library/components/Banners/Banner'; +import { DEFAULT_BANNERBASE_DESCRIPTION_TEXTVARIANT } from '../../../component-library/components/Banners/Banner/foundation/BannerBase/BannerBase.constants'; +import BannerAlert from '../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert'; import { IconColor, IconName, IconSize, -} from '../../../../../component-library/components/Icons/Icon'; -import Icon from '../../../../../component-library/components/Icons/Icon/Icon'; -import Text from '../../../../../component-library/components/Texts/Text/Text'; -import { useStyles } from '../../../../../component-library/hooks/useStyles'; +} from '../../../component-library/components/Icons/Icon'; +import Icon from '../../../component-library/components/Icons/Icon/Icon'; +import Text from '../../../component-library/components/Texts/Text/Text'; +import { useStyles } from '../../../component-library/hooks/useStyles'; import { isBlockaidFeatureEnabled, isBlockaidSupportedOnCurrentChain, -} from '../../../../../util/blockaid'; +} from '../../../util/blockaid'; import { ATTRIBUTION_LINE_TEST_ID, FALSE_POSITIVE_REPOST_LINE_TEST_ID, @@ -40,13 +40,10 @@ import { BLOCKAID_ATTRIBUTION_LINK, FALSE_POSITIVE_REPORT_BASE_URL, UTM_SOURCE, -} from '../../../../../constants/urls'; -import { BLOCKAID_SUPPORTED_NETWORK_NAMES } from '../../../../../util/networks'; -import { selectIsSecurityAlertsEnabled } from '../../../../../selectors/preferencesController'; -import BlockaidVersionInfo from '../../../../../lib/ppom/blockaid-version'; -import ButtonIcon, { - ButtonIconSizes, -} from '../../../../../component-library/components/Buttons/ButtonIcon'; +} from '../../../constants/urls'; +import { BLOCKAID_SUPPORTED_NETWORK_NAMES } from '../../../util/networks'; +import { selectIsSecurityAlertsEnabled } from '../../../selectors/preferencesController'; +import BlockaidVersionInfo from '../../../lib/ppom/blockaid-version'; const getReportUrl = (encodedData: string) => `${FALSE_POSITIVE_REPORT_BASE_URL}?data=${encodeURIComponent( @@ -152,11 +149,19 @@ const BlockaidBanner = (bannerProps: BlockaidBannerProps) => { if (securityAlertResponse.reason === Reason.requestInProgress) { return ( - - - - {strings('blockaid_banner.loading_title')} - + + + } + > + + ); } @@ -164,18 +169,16 @@ const BlockaidBanner = (bannerProps: BlockaidBannerProps) => { if (result_type === ResultType.Benign) { if (displayPositiveResponse) { return ( - - - - - {strings('blockaid_banner.loading_complete_title')} - - - setDisplayPositiveResponse(false)} - iconName={IconName.Close} - /> + + { + setDisplayPositiveResponse(false); + }} + > + + ); } diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.types.ts b/app/components/UI/BlockaidBanner/BlockaidBanner.types.ts similarity index 91% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.types.ts rename to app/components/UI/BlockaidBanner/BlockaidBanner.types.ts index 048aa1a9fa6..e6e9943b068 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBanner.types.ts +++ b/app/components/UI/BlockaidBanner/BlockaidBanner.types.ts @@ -1,4 +1,4 @@ -import { BannerAlertProps } from '../../../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.types'; +import { BannerAlertProps } from '../../../component-library/components/Banners/Banner/variants/BannerAlert/BannerAlert.types'; export enum Reason { approvalFarming = 'approval_farming', diff --git a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBannerLink.tsx b/app/components/UI/BlockaidBanner/BlockaidBannerLink.tsx similarity index 77% rename from app/components/Views/confirmations/components/BlockaidBanner/BlockaidBannerLink.tsx rename to app/components/UI/BlockaidBanner/BlockaidBannerLink.tsx index 8707caa4ce5..d530be1ba3a 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/BlockaidBannerLink.tsx +++ b/app/components/UI/BlockaidBanner/BlockaidBannerLink.tsx @@ -1,8 +1,8 @@ import React from 'react'; import { Linking, StyleSheet } from 'react-native'; -import { DEFAULT_BANNERBASE_DESCRIPTION_TEXTVARIANT } from '../../../../../component-library/components/Banners/Banner/foundation/BannerBase/BannerBase.constants'; -import Text from '../../../../../component-library/components/Texts/Text/Text'; -import { useTheme } from '../../../../../util/theme'; +import { DEFAULT_BANNERBASE_DESCRIPTION_TEXTVARIANT } from '../../../component-library/components/Banners/Banner/foundation/BannerBase/BannerBase.constants'; +import Text from '../../../component-library/components/Texts/Text/Text'; +import { useTheme } from '../../../util/theme'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap b/app/components/UI/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/components/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap rename to app/components/UI/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap index 8a1a39fd2e8..d93f2c22b3d 100644 --- a/app/components/Views/confirmations/components/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap +++ b/app/components/UI/BlockaidBanner/__snapshots__/BlockaidBanner.test.tsx.snap @@ -28,8 +28,8 @@ exports[`BlockaidBanner should render correctly 1`] = ` } style={ Object { - "backgroundColor": "#BF520819", - "borderColor": "#BF5208", + "backgroundColor": "#FFD33D19", + "borderColor": "#F66A0A", "borderLeftWidth": 4, "borderRadius": 4, "flexDirection": "row", @@ -47,7 +47,7 @@ exports[`BlockaidBanner should render correctly 1`] = ` } > { if (index === 1) { - // set toggle to true - toggleRemovingProgress(); removeNft(); - // set toggle to false to indicate that removing the NFT has finished - toggleRemovingProgress(); } else if (index === 0) { refreshMetadata(); } @@ -306,7 +301,6 @@ CollectibleContractElement.propTypes = { * Dispatch remove collectible from favorites action */ removeFavoriteCollectible: PropTypes.func, - toggleRemovingProgress: PropTypes.func, }; const mapStateToProps = (state) => ({ diff --git a/app/components/UI/CollectibleContracts/index.js b/app/components/UI/CollectibleContracts/index.js index 5939091cc02..73fe8e8b052 100644 --- a/app/components/UI/CollectibleContracts/index.js +++ b/app/components/UI/CollectibleContracts/index.js @@ -114,11 +114,6 @@ const CollectibleContracts = ({ const [isAddNFTEnabled, setIsAddNFTEnabled] = useState(true); const [refreshing, setRefreshing] = useState(false); - const [isRemovingNftInProgress, setIsRemovingNftInProgress] = useState(false); - - const toggleRemovingProgress = () => - setIsRemovingNftInProgress((value) => !value); - const displayNftMedia = useSelector(selectDisplayNftMedia); const isCollectionDetectionBannerVisible = @@ -131,25 +126,6 @@ const CollectibleContracts = ({ [navigation], ); - /** - * Method that checks if the collectible is inside the collectibles array. If it is not it means the - * collectible has been ignored, hence we should not call the updateMetadata which executes the addNft fct - * - * @returns Boolean indicating if the collectible is ignored or not. - */ - const isCollectibleIgnored = useCallback( - (collectible) => { - const found = collectibles.find( - (elm) => - elm.address === collectible.address && - elm.tokenId === collectible.tokenId, - ); - if (found) return false; - return true; - }, - [collectibles], - ); - /** * Method to check the token id data type of the current collectibles. * @@ -157,8 +133,7 @@ const CollectibleContracts = ({ * @returns Boolean indicating if the collectible should be updated. */ const shouldUpdateCollectibleMetadata = (collectible) => - typeof collectible.tokenId === 'number' || - (typeof collectible.tokenId === 'string' && !isNaN(collectible.tokenId)); + typeof collectible.tokenId === 'number'; /** * Method to updated collectible and avoid backwards compatibility issues. @@ -169,24 +144,14 @@ const CollectibleContracts = ({ async (collectible) => { const { NftController } = Engine.context; const { address, tokenId } = collectible; - - const isIgnored = isCollectibleIgnored(collectible); - - if (!isRemovingNftInProgress && !isIgnored) { - if (String(tokenId).includes('e+')) { - removeFavoriteCollectible(selectedAddress, chainId, collectible); - } else { - await NftController.addNft(address, String(tokenId)); - } + NftController.removeNft(address, tokenId); + if (String(tokenId).includes('e+')) { + removeFavoriteCollectible(selectedAddress, chainId, collectible); + } else { + await NftController.addNft(address, String(tokenId)); } }, - [ - chainId, - removeFavoriteCollectible, - selectedAddress, - isCollectibleIgnored, - isRemovingNftInProgress, - ], + [chainId, removeFavoriteCollectible, selectedAddress], ); useEffect(() => { @@ -312,7 +277,6 @@ const CollectibleContracts = ({ key={item.address} contractCollectibles={contractCollectibles} collectiblesVisible={index === 0} - toggleRemovingProgress={toggleRemovingProgress} /> ); }, @@ -335,7 +299,6 @@ const CollectibleContracts = ({ key={'Favorites'} contractCollectibles={filteredCollectibles} collectiblesVisible - toggleRemovingProgress={toggleRemovingProgress} /> ) ); @@ -457,7 +420,6 @@ CollectibleContracts.propTypes = { * Array of collectibles objects */ collectibles: PropTypes.array, - /** * Navigation object required to push * the Asset detail view diff --git a/app/components/UI/CollectibleContracts/index.test.tsx b/app/components/UI/CollectibleContracts/index.test.tsx index aedf262024e..72bf4463ba2 100644 --- a/app/components/UI/CollectibleContracts/index.test.tsx +++ b/app/components/UI/CollectibleContracts/index.test.tsx @@ -6,11 +6,6 @@ import { Provider } from 'react-redux'; import initialBackgroundState from '../../../util/test/initial-background-state.json'; import renderWithProvider from '../../../util/test/renderWithProvider'; -// eslint-disable-next-line import/no-namespace -import * as allSelectors from '../../../../app/reducers/collectibles/index.js'; -import { cleanup, waitFor } from '@testing-library/react-native'; -import Engine from '../../../core/Engine'; - jest.mock('@react-navigation/native', () => { const actualReactNavigation = jest.requireActual('@react-navigation/native'); return { @@ -27,18 +22,6 @@ jest.mock('@react-navigation/native', () => { }; }); -jest.mock('../../../core/Engine', () => ({ - context: { - NftController: { - addNft: jest.fn(), - checkAndUpdateAllNftsOwnershipStatus: jest.fn(), - }, - NftDetectionController: { - detectNfts: jest.fn(), - }, - }, -})); - const mockStore = configureMockStore(); const initialState = { collectibles: { @@ -51,7 +34,6 @@ const initialState = { const store = mockStore(initialState); describe('CollectibleContracts', () => { - afterEach(cleanup); it('should render correctly', () => { const wrapper = shallow( @@ -75,7 +57,7 @@ describe('CollectibleContracts', () => { providerConfig: { ticker: 'ETH', type: 'mainnet', - chainId: '0x1', + chainId: '1', }, }, AccountTrackerController: { @@ -93,7 +75,7 @@ describe('CollectibleContracts', () => { NftController: { allNfts: { [CURRENT_ACCOUNT]: { - '0x1': [ + '1': [ { address: '0x72b1FDb6443338A158DeC2FbF411B71aeB157A42', description: @@ -125,7 +107,7 @@ describe('CollectibleContracts', () => { }, allNftContracts: { [CURRENT_ACCOUNT]: { - '0x1': [ + '1': [ { address: '0x72b1FDb6443338A158DeC2FbF411B71aeB157A42', name: 'MyToken', @@ -148,123 +130,4 @@ describe('CollectibleContracts', () => { expect(ownedNft).toBeTruthy(); expect(nonOwnedNft).toBeNull(); }); - - it('UI refresh changes NFT image when metadata image changes', async () => { - const CURRENT_ACCOUNT = '0x1a'; - const collectibleData = [ - { - address: '0x72b1FDb6443338A158DeC2FbF411B71aeB157A42', - name: 'MyToken', - symbol: 'MTK', - }, - ]; - const nftItemData = [ - { - address: '0x72b1FDb6443338A158DeC2FbF411B71aeB157A42', - description: - 'Lil Pudgys are a collection of 22,222 randomly generated NFTs minted on Ethereum.', - error: 'Opensea import error', - favorite: false, - image: 'https://api.pudgypenguins.io/lil/image/11222', - isCurrentlyOwned: true, - name: 'Lil Pudgy #113', - standard: 'ERC721', - tokenId: '113', - tokenURI: 'https://api.pudgypenguins.io/lil/113', - }, - ]; - - const nftItemDataUpdated = [ - { - address: '0x72b1FDb6443338A158DeC2FbF411B71aeB157A42', - description: - 'Lil Pudgys are a collection of 22,222 randomly generated NFTs minted on Ethereum.', - error: 'Opensea import error', - favorite: false, - image: 'https://api.pudgypenguins.io/lil/image/updated.png', - isCurrentlyOwned: true, - name: 'Lil Pudgy #113', - standard: 'ERC721', - tokenId: '113', - tokenURI: 'https://api.pudgypenguins.io/lil/113', - }, - ]; - const mockState = { - collectibles: { - favorites: {}, - }, - engine: { - backgroundState: { - ...initialBackgroundState, - NetworkController: { - network: '1', - providerConfig: { - ticker: 'ETH', - type: 'mainnet', - chainId: '1', - }, - }, - AccountTrackerController: { - accounts: { [CURRENT_ACCOUNT]: { balance: '0' } }, - }, - PreferencesController: { - displayNftMedia: true, - selectedAddress: CURRENT_ACCOUNT, - identities: { - [CURRENT_ACCOUNT]: { - address: CURRENT_ACCOUNT, - name: 'Account 1', - }, - }, - }, - NftController: { - addNft: jest.fn(), - allNfts: { - [CURRENT_ACCOUNT]: { - '1': [], - }, - }, - allNftContracts: { - [CURRENT_ACCOUNT]: { - '1': [], - }, - }, - }, - }, - }, - }; - - const spyOnCollectibles = jest - .spyOn(allSelectors, 'collectiblesSelector') - .mockReturnValueOnce(nftItemData) - .mockReturnValueOnce(nftItemDataUpdated); - const spyOnContracts = jest - .spyOn(allSelectors, 'collectibleContractsSelector') - .mockReturnValue(collectibleData); - const spyOnAddNft = jest - .spyOn(Engine.context.NftController, 'addNft') - .mockImplementation(async () => undefined); - - const { getByTestId } = renderWithProvider(, { - state: mockState, - }); - const nftImageBefore = getByTestId('nft-image'); - expect(nftImageBefore.props.source.uri).toEqual(nftItemData[0].image); - - const { queryByTestId } = renderWithProvider(, { - state: mockState, - }); - - await waitFor(() => { - expect(spyOnAddNft).toHaveBeenCalled(); - const nftImageAfter = queryByTestId('nft-image'); - expect(nftImageAfter.props.source.uri).toEqual( - nftItemDataUpdated[0].image, - ); - }); - - spyOnCollectibles.mockRestore(); - spyOnContracts.mockRestore(); - spyOnAddNft.mockRestore(); - }); }); diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.styles.ts b/app/components/UI/CustomGasModal/CustomGasModal.styles.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.styles.ts rename to app/components/UI/CustomGasModal/CustomGasModal.styles.ts diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.test.tsx b/app/components/UI/CustomGasModal/CustomGasModal.test.tsx similarity index 92% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.test.tsx rename to app/components/UI/CustomGasModal/CustomGasModal.test.tsx index cb13fd8e721..9a751fd47d3 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.test.tsx +++ b/app/components/UI/CustomGasModal/CustomGasModal.test.tsx @@ -2,10 +2,10 @@ import React from 'react'; import { fireEvent } from '@testing-library/react-native'; -import Engine from '../../../../../../../core/Engine'; -import initialBackgroundState from '../../../../../../../util/test/initial-background-state.json'; -import renderWithProvider from '../../../../../../../util/test/renderWithProvider'; -import CustomGasModal from '.'; +import Engine from '../../../core/Engine'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; +import renderWithProvider from '../../../util/test/renderWithProvider'; +import CustomGasModal from './'; Engine.init({}); jest.mock('@react-navigation/native', () => ({ diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.tsx b/app/components/UI/CustomGasModal/CustomGasModal.tsx similarity index 94% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.tsx rename to app/components/UI/CustomGasModal/CustomGasModal.tsx index 225683325c2..3e9f24cab55 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.tsx +++ b/app/components/UI/CustomGasModal/CustomGasModal.tsx @@ -3,10 +3,10 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view import Modal from 'react-native-modal'; import { useSelector } from 'react-redux'; -import { selectChainId } from '../../../../../../../selectors/networkController'; -import { useAppThemeFromContext } from '../../../../../../../util/theme'; -import EditGasFee1559 from '../../../../components/EditGasFee1559Update'; -import EditGasFeeLegacy from '../../../../components/EditGasFeeLegacyUpdate'; +import { selectChainId } from '../../../selectors/networkController'; +import { useAppThemeFromContext } from '../../../util/theme'; +import EditGasFee1559 from '../../UI/EditGasFee1559Update'; +import EditGasFeeLegacy from '../../UI/EditGasFeeLegacyUpdate'; import createStyles from './CustomGasModal.styles'; import { CustomGasModalProps } from './CustomGasModal.types'; diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.types.ts b/app/components/UI/CustomGasModal/CustomGasModal.types.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/CustomGasModal.types.ts rename to app/components/UI/CustomGasModal/CustomGasModal.types.ts diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap b/app/components/UI/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap rename to app/components/UI/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap index 3727d291edf..b758d8221f0 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap +++ b/app/components/UI/CustomGasModal/__snapshots__/CustomGasModal.test.tsx.snap @@ -1002,7 +1002,7 @@ exports[`CustomGasModal should render correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/index.ts b/app/components/UI/CustomGasModal/index.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/Confirm/components/CustomGasModal/index.ts rename to app/components/UI/CustomGasModal/index.ts diff --git a/app/components/Views/confirmations/components/CustomNonce/__snapshots__/index.test.tsx.snap b/app/components/UI/CustomNonce/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/CustomNonce/__snapshots__/index.test.tsx.snap rename to app/components/UI/CustomNonce/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/CustomNonce/index.js b/app/components/UI/CustomNonce/index.js similarity index 88% rename from app/components/Views/confirmations/components/CustomNonce/index.js rename to app/components/UI/CustomNonce/index.js index 2ed5defa81a..6b48c07c280 100644 --- a/app/components/Views/confirmations/components/CustomNonce/index.js +++ b/app/components/UI/CustomNonce/index.js @@ -1,9 +1,9 @@ import React from 'react'; import { StyleSheet, TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types'; -import { strings } from '../../../../../../locales/i18n'; -import Text from '../../../../Base/Text'; -import { useTheme } from '../../../../../util/theme'; +import { strings } from '../../../../locales/i18n'; +import Text from '../../Base/Text'; +import { useTheme } from '../../../util/theme'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/CustomNonce/index.test.tsx b/app/components/UI/CustomNonce/index.test.tsx similarity index 88% rename from app/components/Views/confirmations/components/CustomNonce/index.test.tsx rename to app/components/UI/CustomNonce/index.test.tsx index da9314de094..1a9cd4ca55f 100644 --- a/app/components/Views/confirmations/components/CustomNonce/index.test.tsx +++ b/app/components/UI/CustomNonce/index.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { shallow } from 'enzyme'; -import CustomNonce from '.'; +import CustomNonce from './'; describe('CustomNonce', () => { it('should render correctly', () => { diff --git a/app/components/Views/confirmations/SendFlow/components/CustomNonceModal/__snapshots__/index.test.tsx.snap b/app/components/UI/CustomNonceModal/__snapshots__/index.test.tsx.snap similarity index 98% rename from app/components/Views/confirmations/SendFlow/components/CustomNonceModal/__snapshots__/index.test.tsx.snap rename to app/components/UI/CustomNonceModal/__snapshots__/index.test.tsx.snap index 40ed5b2c54d..38de52540e7 100644 --- a/app/components/Views/confirmations/SendFlow/components/CustomNonceModal/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/CustomNonceModal/__snapshots__/index.test.tsx.snap @@ -208,8 +208,8 @@ exports[`CustomNonceModal should render correctly 1`] = ` StyleSheet.create({ @@ -128,8 +127,7 @@ const CustomModalNonce = ({ proposedNonce, nonceValue, close, save }) => { }; const saveAndClose = () => { - const numberNonce = Number(nonce); - save(numberNonce); + save(nonce); close(); }; @@ -168,11 +166,7 @@ const CustomModalNonce = ({ proposedNonce, nonceValue, close, save }) => { // autoFocus autoCapitalize="none" autoCorrect={false} - onChangeText={(text) => { - if (isNumber(text)) { - onChangeText(text); - } - }} + onChangeText={onChangeText} placeholder={String(proposedNonce)} placeholderTextColor={colors.text.muted} spellCheck={false} diff --git a/app/components/UI/CustomNonceModal/index.test.tsx b/app/components/UI/CustomNonceModal/index.test.tsx new file mode 100644 index 00000000000..84cc225cb5b --- /dev/null +++ b/app/components/UI/CustomNonceModal/index.test.tsx @@ -0,0 +1,20 @@ +import React from 'react'; +import { shallow } from 'enzyme'; +import CustomNonceModal from './'; + +describe('CustomNonceModal', () => { + it('should render correctly', () => { + const proposedNonce = 26; + const customNonce = 28; + const noop = () => ({}); + const wrapper = shallow( + , + ); + expect(wrapper).toMatchSnapshot(); + }); +}); diff --git a/app/components/UI/DrawerView/index.js b/app/components/UI/DrawerView/index.js index a63f0ae3cbe..39f8c0ba6f5 100644 --- a/app/components/UI/DrawerView/index.js +++ b/app/components/UI/DrawerView/index.js @@ -20,7 +20,6 @@ import { hasBlockExplorer, findBlockExplorerForRpc, getBlockExplorerName, - getDecimalChainId, } from '../../../util/networks'; import Identicon from '../Identicon'; import StyledButton from '../StyledButton'; @@ -634,7 +633,7 @@ class DrawerView extends PureComponent { const { providerConfig } = this.props; AnalyticsV2.trackEvent(MetaMetricsEvents.BROWSER_OPENED, { source: 'In-app Navigation', - chain_id: getDecimalChainId(providerConfig.chainId), + chain_id: providerConfig.chainId, }); }; @@ -703,7 +702,7 @@ class DrawerView extends PureComponent { this.props; if (providerConfig.type === RPC) { const blockExplorer = findBlockExplorerForRpc( - providerConfig.rpcUrl, + providerConfig.rpcTarget, networkConfigurations, ); const url = `${blockExplorer}/address/${selectedAddress}`; @@ -759,10 +758,10 @@ class DrawerView extends PureComponent { const { networkConfigurations } = this.props; if (providerType === RPC) { const { - providerConfig: { rpcUrl }, + providerConfig: { rpcTarget }, } = this.props; const blockExplorer = findBlockExplorerForRpc( - rpcUrl, + rpcTarget, networkConfigurations, ); if (blockExplorer) { @@ -847,12 +846,12 @@ class DrawerView extends PureComponent { getSections = () => { const { - providerConfig: { type, rpcUrl }, + providerConfig: { type, rpcTarget }, networkConfigurations, } = this.props; let blockExplorer, blockExplorerName; if (type === RPC) { - blockExplorer = findBlockExplorerForRpc(rpcUrl, networkConfigurations); + blockExplorer = findBlockExplorerForRpc(rpcTarget, networkConfigurations); blockExplorerName = getBlockExplorerName(blockExplorer); } return [ diff --git a/app/components/UI/EditGasFee1559/index.js b/app/components/UI/EditGasFee1559/index.js index 430f213e352..dd73b169c7a 100644 --- a/app/components/UI/EditGasFee1559/index.js +++ b/app/components/UI/EditGasFee1559/index.js @@ -18,7 +18,7 @@ import { strings } from '../../../../locales/i18n'; import Alert, { AlertType } from '../../Base/Alert'; import HorizontalSelector from '../../Base/HorizontalSelector'; import Device from '../../../util/device'; -import { getDecimalChainId, isMainnetByChainId } from '../../../util/networks'; +import { isMainnetByChainId } from '../../../util/networks'; import PropTypes from 'prop-types'; import BigNumber from 'bignumber.js'; import FadeAnimationView from '../FadeAnimationView'; @@ -29,12 +29,11 @@ import TimeEstimateInfoModal from '../TimeEstimateInfoModal'; import useModalHandler from '../../Base/hooks/useModalHandler'; import AppConstants from '../../../core/AppConstants'; import { useTheme } from '../../../util/theme'; -import { - GAS_LIMIT_INCREMENT, - GAS_PRICE_INCREMENT as GAS_INCREMENT, - GAS_LIMIT_MIN, - GAS_PRICE_MIN as GAS_MIN, -} from '../../../util/gasUtils'; + +const GAS_LIMIT_INCREMENT = new BigNumber(1000); +const GAS_INCREMENT = new BigNumber(1); +const GAS_LIMIT_MIN = new BigNumber(21000); +const GAS_MIN = new BigNumber(0); const createStyles = (colors) => StyleSheet.create({ @@ -205,7 +204,7 @@ const EditGasFee1559 = ({ try { return { ...analyticsParams, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, function_type: view, gas_mode: selectedOption ? 'Basic' : 'Advanced', speed_set: selectedOption || undefined, diff --git a/app/components/Views/confirmations/components/EditGasFee1559Update/index.tsx b/app/components/UI/EditGasFee1559Update/index.tsx similarity index 94% rename from app/components/Views/confirmations/components/EditGasFee1559Update/index.tsx rename to app/components/UI/EditGasFee1559Update/index.tsx index ef4ee040a38..6aa2f59dab7 100644 --- a/app/components/Views/confirmations/components/EditGasFee1559Update/index.tsx +++ b/app/components/UI/EditGasFee1559Update/index.tsx @@ -6,42 +6,38 @@ import { TouchableWithoutFeedback, Platform, } from 'react-native'; -import Text from '../../../../Base/Text'; -import StyledButton from '../../../../UI/StyledButton'; -import RangeInput from '../../../../Base/RangeInput'; +import Text from '../../Base/Text'; +import StyledButton from '../StyledButton'; +import RangeInput from '../../Base/RangeInput'; import MaterialCommunityIcon from 'react-native-vector-icons/MaterialCommunityIcons'; -import InfoModal from '../../../../UI/Swaps/components/InfoModal'; +import InfoModal from '../Swaps/components/InfoModal'; import Icon from 'react-native-vector-icons/Ionicons'; -import { strings } from '../../../../../../locales/i18n'; -import Alert, { AlertType } from '../../../../Base/Alert'; -import HorizontalSelector from '../../../../Base/HorizontalSelector'; -import { - getDecimalChainId, - isMainnetByChainId, -} from '../../../../../util/networks'; +import { strings } from '../../../../locales/i18n'; +import Alert, { AlertType } from '../../Base/Alert'; +import HorizontalSelector from '../../Base/HorizontalSelector'; +import { isMainnetByChainId } from '../../../util/networks'; import BigNumber from 'bignumber.js'; -import FadeAnimationView from '../../../../UI/FadeAnimationView'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; - -import TimeEstimateInfoModal from '../../../../UI/TimeEstimateInfoModal'; -import useModalHandler from '../../../../Base/hooks/useModalHandler'; -import AppConstants from '../../../../../core/AppConstants'; -import { useGasTransaction } from '../../../../../core/GasPolling/GasPolling'; -import { useAppThemeFromContext, mockTheme } from '../../../../../util/theme'; +import FadeAnimationView from '../FadeAnimationView'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; + +import TimeEstimateInfoModal from '../TimeEstimateInfoModal'; +import useModalHandler from '../../Base/hooks/useModalHandler'; +import AppConstants from '../../../core/AppConstants'; +import { useGasTransaction } from '../../../core/GasPolling/GasPolling'; +import { useAppThemeFromContext, mockTheme } from '../../../util/theme'; import createStyles from './styles'; import { EditGasFee1559UpdateProps, RenderInputProps } from './types'; -import generateTestId from '../../../../../../wdio/utils/generateTestId'; +import generateTestId from '../../../../wdio/utils/generateTestId'; import { EDIT_PRIORITY_SCREEN_TEST_ID, MAX_PRIORITY_FEE_INPUT_TEST_ID, -} from '../../../../../../wdio/screen-objects/testIDs/Screens/EditGasFeeScreen.testids.js'; -import { - GAS_LIMIT_INCREMENT, - GAS_PRICE_INCREMENT as GAS_INCREMENT, - GAS_LIMIT_MIN, - GAS_PRICE_MIN as GAS_MIN, -} from '../../../../../util/gasUtils'; +} from '../../../../wdio/screen-objects/testIDs/Screens/EditGasFeeScreen.testids.js'; + +const GAS_LIMIT_INCREMENT = new BigNumber(1000); +const GAS_INCREMENT = new BigNumber(1); +const GAS_LIMIT_MIN = new BigNumber(21000); +const GAS_MIN = new BigNumber(0); const EditGasFee1559Update = ({ selectedGasValue, @@ -121,7 +117,7 @@ const EditGasFee1559Update = ({ try { return { ...analyticsParams, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, function_type: analyticsParams.view, gas_mode: selectedOption ? 'Basic' : 'Advanced', speed_set: selectedOption || undefined, diff --git a/app/components/Views/confirmations/components/EditGasFee1559Update/styles.ts b/app/components/UI/EditGasFee1559Update/styles.ts similarity index 97% rename from app/components/Views/confirmations/components/EditGasFee1559Update/styles.ts rename to app/components/UI/EditGasFee1559Update/styles.ts index 07bb45aebd8..4f013cda7bf 100644 --- a/app/components/Views/confirmations/components/EditGasFee1559Update/styles.ts +++ b/app/components/UI/EditGasFee1559Update/styles.ts @@ -1,5 +1,5 @@ import { StyleSheet } from 'react-native'; -import Device from '../../../../../util/device'; +import Device from '../../../util/device'; const createStyles = (colors: any) => StyleSheet.create({ root: { diff --git a/app/components/Views/confirmations/components/EditGasFee1559Update/types.ts b/app/components/UI/EditGasFee1559Update/types.ts similarity index 97% rename from app/components/Views/confirmations/components/EditGasFee1559Update/types.ts rename to app/components/UI/EditGasFee1559Update/types.ts index 75e5374f0d3..b5173db8510 100644 --- a/app/components/Views/confirmations/components/EditGasFee1559Update/types.ts +++ b/app/components/UI/EditGasFee1559Update/types.ts @@ -1,4 +1,4 @@ -import { GasFeeOptions } from '../../../../../core/GasPolling/types'; +import { GasFeeOptions } from '../../../core/GasPolling/types'; export interface RenderInputProps { updateOption: diff --git a/app/components/UI/EditGasFeeLegacy/index.js b/app/components/UI/EditGasFeeLegacy/index.js index d1529909f31..206415def01 100644 --- a/app/components/UI/EditGasFeeLegacy/index.js +++ b/app/components/UI/EditGasFeeLegacy/index.js @@ -20,19 +20,18 @@ import { strings } from '../../../../locales/i18n'; import Alert, { AlertType } from '../../Base/Alert'; import HorizontalSelector from '../../Base/HorizontalSelector'; import Device from '../../../util/device'; -import { getDecimalChainId, isMainnetByChainId } from '../../../util/networks'; +import { isMainnetByChainId } from '../../../util/networks'; import FadeAnimationView from '../FadeAnimationView'; import { MetaMetricsEvents } from '../../../core/Analytics'; import AnalyticsV2 from '../../../util/analyticsV2'; import AppConstants from '../../../core/AppConstants'; import { useTheme } from '../../../util/theme'; -import { - GAS_LIMIT_INCREMENT, - GAS_PRICE_INCREMENT, - GAS_LIMIT_MIN, - GAS_PRICE_MIN, -} from '../../../util/gasUtils'; + +const GAS_LIMIT_INCREMENT = new BigNumber(1000); +const GAS_PRICE_INCREMENT = new BigNumber(1); +const GAS_LIMIT_MIN = new BigNumber(21000); +const GAS_PRICE_MIN = new BigNumber(0); const createStyles = (colors) => StyleSheet.create({ @@ -154,7 +153,7 @@ const EditGasFeeLegacy = ({ try { return { ...analyticsParams, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, function_type: view, gas_mode: selectedOption ? 'Basic' : 'Advanced', speed_set: selectedOption || undefined, diff --git a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx b/app/components/UI/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx similarity index 90% rename from app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx rename to app/components/UI/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx index ffa6406d083..240c1c9e080 100644 --- a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx +++ b/app/components/UI/EditGasFeeLegacyUpdate/EditGasFeeLegacyUpdate.test.tsx @@ -1,8 +1,8 @@ import React from 'react'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; -import EditGasFeeLegacyUpdate from '.'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; +import renderWithProvider from '../../../util/test/renderWithProvider'; +import EditGasFeeLegacyUpdate from './'; const mockInitialState = (txnType = 'none') => ({ engine: { diff --git a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap b/app/components/UI/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap rename to app/components/UI/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap index 2762671d6d4..1cb3273a1a3 100644 --- a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap +++ b/app/components/UI/EditGasFeeLegacyUpdate/__snapshots__/EditGasFeeLegacyUpdate.test.tsx.snap @@ -129,8 +129,8 @@ exports[`EditGasFeeLegacyUpdate should match snapshot 1`] = ` "paddingVertical": 8, }, Object { - "backgroundColor": "#BF520819", - "borderColor": "#BF5208", + "backgroundColor": "#FFD33D19", + "borderColor": "#F66A0A", }, undefined, ] @@ -148,7 +148,7 @@ exports[`EditGasFeeLegacyUpdate should match snapshot 1`] = ` style={ Array [ Object { - "color": "#BF5208", + "color": "#F66A0A", "fontSize": 20, }, undefined, @@ -169,7 +169,7 @@ exports[`EditGasFeeLegacyUpdate should match snapshot 1`] = ` accessibilityRole="text" style={ Object { - "color": "#BF5208", + "color": "#F66A0A", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -947,7 +947,7 @@ exports[`EditGasFeeLegacyUpdate should match snapshot 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/index.tsx b/app/components/UI/EditGasFeeLegacyUpdate/index.tsx similarity index 92% rename from app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/index.tsx rename to app/components/UI/EditGasFeeLegacyUpdate/index.tsx index c4a3757c57b..330a7be379f 100644 --- a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/index.tsx +++ b/app/components/UI/EditGasFeeLegacyUpdate/index.tsx @@ -13,33 +13,29 @@ import { useSelector } from 'react-redux'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; -import { strings } from '../../../../../../locales/i18n'; +import { strings } from '../../../../locales/i18n'; import Text, { TextColor, TextVariant, -} from '../../../../../component-library/components/Texts/Text'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import { useGasTransaction } from '../../../../../core/GasPolling/GasPolling'; -import { selectChainId } from '../../../../../selectors/networkController'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { - getDecimalChainId, - isMainnetByChainId, -} from '../../../../../util/networks'; -import { useTheme } from '../../../../../util/theme'; -import Alert, { AlertType } from '../../../../Base/Alert'; -import RangeInput from '../../../../Base/RangeInput'; -import FadeAnimationView from '../../../../UI/FadeAnimationView'; -import StyledButton from '../../../../UI/StyledButton'; -import InfoModal from '../../../../UI/Swaps/components/InfoModal'; +} from '../../../component-library/components/Texts/Text'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import { useGasTransaction } from '../../../core/GasPolling/GasPolling'; +import { selectChainId } from '../../../selectors/networkController'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import { isMainnetByChainId } from '../../../util/networks'; +import { useTheme } from '../../../util/theme'; +import Alert, { AlertType } from '../../Base/Alert'; +import RangeInput from '../../Base/RangeInput'; +import FadeAnimationView from '../FadeAnimationView'; +import StyledButton from '../StyledButton'; +import InfoModal from '../Swaps/components/InfoModal'; import createStyles from './styles'; import { EditGasFeeLegacyUpdateProps, EditLegacyGasTransaction } from './types'; -import { - GAS_LIMIT_INCREMENT, - GAS_PRICE_INCREMENT, - GAS_LIMIT_MIN, - GAS_PRICE_MIN, -} from '../../../../../util/gasUtils'; + +const GAS_LIMIT_INCREMENT = new BigNumber(1000); +const GAS_PRICE_INCREMENT = new BigNumber(1); +const GAS_LIMIT_MIN = new BigNumber(21000); +const GAS_PRICE_MIN = new BigNumber(0); const EditGasFeeLegacy = ({ onCancel, @@ -99,7 +95,7 @@ const EditGasFeeLegacy = ({ const save = useCallback(() => { AnalyticsV2.trackEvent(MetaMetricsEvents.GAS_FEE_CHANGED, { ...analyticsParams, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, function_type: view, gas_mode: 'Basic', }); diff --git a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/styles.ts b/app/components/UI/EditGasFeeLegacyUpdate/styles.ts similarity index 97% rename from app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/styles.ts rename to app/components/UI/EditGasFeeLegacyUpdate/styles.ts index 66c245b9a7b..89484195a0e 100644 --- a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/styles.ts +++ b/app/components/UI/EditGasFeeLegacyUpdate/styles.ts @@ -1,6 +1,6 @@ import { StyleSheet } from 'react-native'; -import Device from '../../../../../util/device'; +import Device from '../../../util/device'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/types.ts b/app/components/UI/EditGasFeeLegacyUpdate/types.ts similarity index 100% rename from app/components/Views/confirmations/components/EditGasFeeLegacyUpdate/types.ts rename to app/components/UI/EditGasFeeLegacyUpdate/types.ts diff --git a/app/components/UI/LedgerModals/LedgerConfirmationModal.tsx b/app/components/UI/LedgerModals/LedgerConfirmationModal.tsx index 7fa40e3b5df..94bc7892a23 100644 --- a/app/components/UI/LedgerModals/LedgerConfirmationModal.tsx +++ b/app/components/UI/LedgerModals/LedgerConfirmationModal.tsx @@ -70,7 +70,7 @@ const LedgerConfirmationModal = ({ const connectLedger = () => { try { ledgerLogicToRun(async () => { - await unlockLedgerDefaultAccount(false); + await unlockLedgerDefaultAccount(); await onConfirmation(); }); } catch (_e) { diff --git a/app/components/UI/LedgerModals/LedgerTransactionModal.tsx b/app/components/UI/LedgerModals/LedgerTransactionModal.tsx index 6094e4a8c0f..f47998092bd 100644 --- a/app/components/UI/LedgerModals/LedgerTransactionModal.tsx +++ b/app/components/UI/LedgerModals/LedgerTransactionModal.tsx @@ -10,7 +10,6 @@ import { } from '../../../util/navigation/navUtils'; import Routes from '../../../constants/navigation/Routes'; import { useAppThemeFromContext, mockTheme } from '../../../util/theme'; -import { speedUpTransaction } from '../../../util/transaction-controller'; export const createLedgerTransactionModalNavDetails = createNavigationDetails( @@ -50,7 +49,10 @@ const LedgerTransactionModal = () => { const executeOnLedger = useCallback(async () => { if (replacementParams?.type === LedgerReplacementTxTypes.SPEED_UP) { - await speedUpTransaction(transactionId, replacementParams.eip1559GasFee); + await TransactionController.speedUpTransaction( + transactionId, + replacementParams.eip1559GasFee, + ); } else if (replacementParams?.type === LedgerReplacementTxTypes.CANCEL) { await TransactionController.stopTransaction( transactionId, diff --git a/app/components/UI/LedgerModals/styles.ts b/app/components/UI/LedgerModals/styles.ts index 6de560c41a7..81f27f596da 100644 --- a/app/components/UI/LedgerModals/styles.ts +++ b/app/components/UI/LedgerModals/styles.ts @@ -6,14 +6,12 @@ export const createStyles = (colors: Colors) => StyleSheet.create({ modal: { justifyContent: 'flex-end', - height: 600, margin: 0, + height: 600, zIndex: 1000, }, contentWrapper: { zIndex: 1000, - paddingHorizontal: 8, - marginHorizontal: 8, paddingBottom: 32, borderRadius: 20, backgroundColor: colors.background.default, diff --git a/app/components/Views/confirmations/components/MessageSign/MessageSign.tsx b/app/components/UI/MessageSign/MessageSign.tsx similarity index 86% rename from app/components/Views/confirmations/components/MessageSign/MessageSign.tsx rename to app/components/UI/MessageSign/MessageSign.tsx index 2a3ac444079..24a5b965075 100644 --- a/app/components/Views/confirmations/components/MessageSign/MessageSign.tsx +++ b/app/components/UI/MessageSign/MessageSign.tsx @@ -1,24 +1,24 @@ import React, { useEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { StyleSheet, View, Text } from 'react-native'; -import { fontStyles } from '../../../../../styles/common'; +import { fontStyles } from '../../../styles/common'; import SignatureRequest from '../SignatureRequest'; import ExpandedMessage from '../SignatureRequest/ExpandedMessage'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { useTheme } from '../../../../../util/theme'; +import { KEYSTONE_TX_CANCELED } from '../../../constants/error'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import { useTheme } from '../../../util/theme'; import { getAnalyticsParams, handleSignatureAction, -} from '../../../../../util/confirmation/signatureUtils'; +} from '../../../util/confirmation/signatureUtils'; import { MessageParams, PageMeta } from '../SignatureRequest/types'; -import { Colors } from '../../../../../util/theme/models'; -import { isExternalHardwareAccount } from '../../../../../util/address'; -import createExternalSignModelNav from '../../../../../util/hardwareWallet/signatureUtils'; -import { SigningModalSelectorsIDs } from '../../../../../../e2e/selectors/Modals/SigningModal.selectors'; +import { Colors } from '../../../util/theme/models'; +import { isExternalHardwareAccount } from '../../../util/address'; +import createExternalSignModelNav from '../../../util/hardwareWallet/signatureUtils'; +import { SigningModalSelectorsIDs } from '../../../../e2e/selectors/Modals/SigningModal.selectors'; import { useNavigation } from '@react-navigation/native'; -import Engine from '../../../../../core/Engine'; +import Engine from '../../../core/Engine'; interface MessageSignProps { /** diff --git a/app/components/Views/confirmations/components/MessageSign/__snapshots__/index.test.tsx.snap b/app/components/UI/MessageSign/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/MessageSign/__snapshots__/index.test.tsx.snap rename to app/components/UI/MessageSign/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/MessageSign/index.test.tsx b/app/components/UI/MessageSign/index.test.tsx similarity index 90% rename from app/components/Views/confirmations/components/MessageSign/index.test.tsx rename to app/components/UI/MessageSign/index.test.tsx index 208ba1ece0a..25e1fd2f8f8 100644 --- a/app/components/Views/confirmations/components/MessageSign/index.test.tsx +++ b/app/components/UI/MessageSign/index.test.tsx @@ -1,24 +1,24 @@ import React from 'react'; import MessageSign from './index'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import Engine from '../../../../../core/Engine'; -import NotificationManager from '../../../../../core/NotificationManager'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; +import Engine from '../../../core/Engine'; +import NotificationManager from '../../../core/NotificationManager'; import { InteractionManager } from 'react-native'; -import AppConstants from '../../../../../core/AppConstants'; -import { strings } from '../../../../../../locales/i18n'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import analyticsV2 from '../../../../../util/analyticsV2'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; +import AppConstants from '../../../core/AppConstants'; +import { strings } from '../../../../locales/i18n'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; +import analyticsV2 from '../../../util/analyticsV2'; +import renderWithProvider from '../../../util/test/renderWithProvider'; import { act, waitFor } from '@testing-library/react-native'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; +import { KEYSTONE_TX_CANCELED } from '../../../constants/error'; +import { MetaMetricsEvents } from '../../../core/Analytics'; // eslint-disable-next-line import/no-namespace -import * as addressUtils from '../../../../../util/address'; -import createExternalSignModelNav from '../../../../../util/hardwareWallet/signatureUtils'; +import * as addressUtils from '../../../util/address'; +import createExternalSignModelNav from '../../../util/hardwareWallet/signatureUtils'; const fakeAddress = '0xE413f7dB07f9B93936189867588B1440D823e651'; -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../core/Engine', () => ({ acceptPendingApproval: jest.fn(), rejectPendingApproval: jest.fn(), context: { @@ -38,20 +38,20 @@ jest.mock('../../../../../core/Engine', () => ({ const EngineMock = Engine as jest.Mocked; -jest.mock('../../../../../core/NotificationManager', () => ({ +jest.mock('../../../core/NotificationManager', () => ({ showSimpleNotification: jest.fn(), })); -jest.mock('../../../../../util/analyticsV2'); +jest.mock('../../../util/analyticsV2'); -jest.mock('../../../../../util/address', () => ({ - ...jest.requireActual('../../../../../util/address'), +jest.mock('../../../util/address', () => ({ + ...jest.requireActual('../../../util/address'), isExternalHardwareAccount: jest.fn(), })); const addressUtilsMock = addressUtils as jest.Mocked; -jest.mock('../../../../../util/hardwareWallet/signatureUtils', () => ({ +jest.mock('../../../util/hardwareWallet/signatureUtils', () => ({ __esModule: true, default: jest.fn().mockImplementation((...args) => [args]), })); diff --git a/app/components/Views/confirmations/components/MessageSign/index.ts b/app/components/UI/MessageSign/index.ts similarity index 100% rename from app/components/Views/confirmations/components/MessageSign/index.ts rename to app/components/UI/MessageSign/index.ts diff --git a/app/components/UI/Navbar/index.js b/app/components/UI/Navbar/index.js index 347e341906d..1de294e0118 100644 --- a/app/components/UI/Navbar/index.js +++ b/app/components/UI/Navbar/index.js @@ -29,7 +29,11 @@ import PickerNetwork from '../../../component-library/components/Pickers/PickerN import BrowserUrlBar from '../BrowserUrlBar'; import generateTestId from '../../../../wdio/utils/generateTestId'; import { NAVBAR_NETWORK_BUTTON } from '../../../../wdio/screen-objects/testIDs/Screens/WalletView.testIds'; -import { NAV_ANDROID_BACK_BUTTON } from '../../../../wdio/screen-objects/testIDs/Screens/NetworksScreen.testids'; +import { + NAV_ANDROID_BACK_BUTTON, + NETWORK_BACK_ARROW_BUTTON_ID, + NETWORK_SCREEN_CLOSE_ICON, +} from '../../../../wdio/screen-objects/testIDs/Screens/NetworksScreen.testids'; import { SEND_CANCEL_BUTTON } from '../../../../wdio/screen-objects/testIDs/Screens/SendScreen.testIds'; import { ASSET_BACK_BUTTON } from '../../../../wdio/screen-objects/testIDs/Screens/TokenOverviewScreen.testIds'; import { REQUEST_SEARCH_RESULTS_BACK_BUTTON } from '../../../../wdio/screen-objects/testIDs/Screens/RequestToken.testIds'; @@ -50,7 +54,6 @@ import { } from '../../../component-library/components/Texts/Text'; import { CommonSelectorsIDs } from '../../../../e2e/selectors/Common.selectors'; import { WalletViewSelectorsIDs } from '../../../../e2e/selectors/WalletView.selectors'; -import { NetworksViewSelectorsIDs } from '../../../../e2e/selectors/Settings/NetworksView.selectors'; const trackEvent = (event) => { InteractionManager.runAfterInteractions(() => { @@ -213,7 +216,7 @@ export function getNavigationOptionsTitle( iconName={IconName.Close} onPress={navigationPop} style={innerStyles.accessories} - testID={NetworksViewSelectorsIDs.CLOSE_ICON} + {...generateTestId(Platform, NETWORK_SCREEN_CLOSE_ICON)} /> ) : null, headerLeft: () => @@ -223,7 +226,7 @@ export function getNavigationOptionsTitle( iconName={IconName.ArrowLeft} onPress={navigationPop} style={innerStyles.accessories} - testID={NetworksViewSelectorsIDs.BACK_ARROW_BUTTON} + {...generateTestId(Platform, NETWORK_BACK_ARROW_BUTTON_ID)} /> ), headerTintColor: themeColors.primary.default, diff --git a/app/components/UI/NavbarTitle/index.js b/app/components/UI/NavbarTitle/index.js index 0999c9b2e91..8dfc5a9d44a 100644 --- a/app/components/UI/NavbarTitle/index.js +++ b/app/components/UI/NavbarTitle/index.js @@ -4,7 +4,7 @@ import { connect } from 'react-redux'; import { scale } from 'react-native-size-matters'; import { TouchableOpacity, View, StyleSheet, Text } from 'react-native'; import { fontStyles, colors as importedColors } from '../../../styles/common'; -import Networks, { getDecimalChainId } from '../../../util/networks'; +import Networks from '../../../util/networks'; import { strings } from '../../../../locales/i18n'; import Device from '../../../util/device'; import { ThemeContext, mockTheme } from '../../../util/theme'; @@ -94,7 +94,7 @@ class NavbarTitle extends PureComponent { Analytics.trackEventWithParameters( MetaMetricsEvents.NETWORK_SELECTOR_PRESSED, { - chain_id: getDecimalChainId(this.props.providerConfig.chainId), + chain_id: this.props.providerConfig.chainId, }, ); setTimeout(() => { diff --git a/app/components/UI/NetworkInfo/index.tsx b/app/components/UI/NetworkInfo/index.tsx index d6617cef5fc..e6cabc8cb13 100644 --- a/app/components/UI/NetworkInfo/index.tsx +++ b/app/components/UI/NetworkInfo/index.tsx @@ -117,7 +117,7 @@ interface NetworkInfoProps { const NetworkInfo = (props: NetworkInfoProps) => { const { onClose, ticker, isTokenDetectionEnabled } = props; const providerConfig = useSelector(selectProviderConfig); - const { type, ticker: networkTicker, rpcUrl, chainId } = providerConfig; + const { type, ticker: networkTicker, rpcTarget, chainId } = providerConfig; const { colors } = useTheme(); const styles = createStyles(colors); const isTokenDetectionSupported = @@ -170,7 +170,9 @@ const NetworkInfo = (props: NetworkInfoProps) => { {networkName} - {ticker === undefined && {rpcUrl}} + {ticker === undefined && ( + {rpcTarget} + )} {strings('network_information.things_to_keep_in_mind')}: diff --git a/app/components/UI/NetworkMainAssetLogo/index.js b/app/components/UI/NetworkMainAssetLogo/index.js index b85e38b64d1..53e265ee244 100644 --- a/app/components/UI/NetworkMainAssetLogo/index.js +++ b/app/components/UI/NetworkMainAssetLogo/index.js @@ -1,6 +1,6 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { ChainId } from '@metamask/controller-utils'; +import { NetworksChainId } from '@metamask/controller-utils'; import { connect } from 'react-redux'; import TokenIcon from '../Swaps/components/TokenIcon'; import { @@ -9,7 +9,7 @@ import { } from '../../../selectors/networkController'; function NetworkMainAssetLogo({ chainId, ticker, style, big, biggest }) { - if (chainId === ChainId.mainnet) { + if (chainId === NetworksChainId.mainnet) { return ( ); diff --git a/app/components/UI/NetworkModal/NetworkAdded/index.tsx b/app/components/UI/NetworkModal/NetworkAdded/index.tsx index 139ae4cbe03..2b4039a8f6b 100644 --- a/app/components/UI/NetworkModal/NetworkAdded/index.tsx +++ b/app/components/UI/NetworkModal/NetworkAdded/index.tsx @@ -4,8 +4,10 @@ import StyledButton from '../../StyledButton'; import { strings } from '../../../../../locales/i18n'; import Text from '../../../Base/Text'; import { useTheme } from '../../../../util/theme'; -import { NetworkAddedModalSelectorsIDs } from '../../../../../e2e/selectors/Modals/NetworkAddedModal.selectors'; - +import { + NEW_NETWORK_ADDED_SWITCH_TO_NETWORK_BUTTON, + NEW_NETWORK_ADDED_CLOSE_BUTTON, +} from '../../../../../wdio/screen-objects/testIDs/Screens/NetworksScreen.testids'; const createStyles = (colors: any) => StyleSheet.create({ buttonView: { @@ -45,14 +47,14 @@ const NetworkAdded = (props: NetworkAddedProps) => { {`"${strings('networks.network_name', { - networkName: nickname ?? '', + networkName: nickname, })}"`} {strings('networks.network_added')} @@ -61,7 +63,7 @@ const NetworkAdded = (props: NetworkAddedProps) => { {strings('networks.switch_network')} diff --git a/app/components/UI/NetworkModal/NetworkDetails/index.tsx b/app/components/UI/NetworkModal/NetworkDetails/index.tsx index 1e7d2ed3fa3..f9d6a32fe21 100644 --- a/app/components/UI/NetworkModal/NetworkDetails/index.tsx +++ b/app/components/UI/NetworkModal/NetworkDetails/index.tsx @@ -4,7 +4,6 @@ import ConnectHeader from '../../../UI/ConnectHeader'; import { strings } from '../../../../../locales/i18n'; import Text from '../../../Base/Text'; import { useTheme } from '../../../../util/theme'; -import { getDecimalChainId } from '../../../../util/networks'; const createStyles = (colors: any) => StyleSheet.create({ @@ -46,7 +45,7 @@ const NetworkDetails = (props: NetworkDetailsProps) => { }, { title: strings('networks.network_chain_id'), - value: getDecimalChainId(chainId), + value: chainId, }, { title: strings('networks.network_currency_symbol'), diff --git a/app/components/UI/NetworkModal/__snapshots__/index.test.tsx.snap b/app/components/UI/NetworkModal/__snapshots__/index.test.tsx.snap deleted file mode 100644 index 84e5c22fe23..00000000000 --- a/app/components/UI/NetworkModal/__snapshots__/index.test.tsx.snap +++ /dev/null @@ -1,586 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`NetworkDetails renders correctly 1`] = ` - - - - - - - - - - - - - - - - - Add custom network - - - - - - - - - - - - - - Test Network - - - - MetaMask doesn’t verify custom networks, so only approve networks you trust. - - - Learn more about network security risks and scams. - - - - - - Display name - - - Test Network - - - Chain ID - - - 1 - - - Network URL - - - https://localhost:8545 - - - - View details - - - - - - - - - - - - - Cancel - - - - - Confirm - - - - - - - - - -`; diff --git a/app/components/UI/NetworkModal/index.styles.ts b/app/components/UI/NetworkModal/index.styles.ts deleted file mode 100644 index fd2be5dc160..00000000000 --- a/app/components/UI/NetworkModal/index.styles.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { StyleSheet } from 'react-native'; -import { fontStyles } from '../../../styles/common'; -import scaling from '../../../util/scaling'; -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; - -const createNetworkModalStyles = (colors: ThemeColors) => - StyleSheet.create({ - root: { - backgroundColor: colors.background.default, - paddingHorizontal: 0, - maxHeight: '85%', - paddingBottom: 20, - }, - bottomModal: { - justifyContent: 'flex-end', - margin: 0, - }, - alertBar: { - width: '100%', - marginBottom: 15, - }, - modalContainer: { - borderRadius: 10, - backgroundColor: colors.background.default, - padding: 4, - paddingTop: 4, - maxHeight: '80%', - }, - title: { - ...fontStyles.bold, - fontSize: scaling.scale(18), - textAlign: 'center', - color: colors.text.default, - lineHeight: 34, - marginVertical: 10, - paddingHorizontal: 16, - }, - bottomSpace: { - marginBottom: 10, - }, - actionContainer: { - flex: 0, - paddingVertical: 16, - justifyContent: 'center', - }, - notch: { - width: 40, - height: 4, - borderRadius: 2, - backgroundColor: colors.border.muted, - }, - notchWrapper: { - alignSelf: 'stretch', - padding: 4, - alignItems: 'center', - }, - textSection: { - marginBottom: 8, - }, - accountCardWrapper: { - borderWidth: 1, - borderColor: colors.border.default, - borderRadius: 10, - padding: 16, - marginVertical: 16, - maxHeight: '70%', - }, - nestedScrollContent: { paddingBottom: 24 }, - networkSection: { marginBottom: 16 }, - textCentred: { - textAlign: 'center', - }, - }); - -export default createNetworkModalStyles; diff --git a/app/components/UI/NetworkModal/index.test.tsx b/app/components/UI/NetworkModal/index.test.tsx deleted file mode 100644 index d1ae7342112..00000000000 --- a/app/components/UI/NetworkModal/index.test.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import React from 'react'; -import NetworkModal from './index'; -import { render } from '@testing-library/react-native'; -import { useSelector } from 'react-redux'; - -interface NetworkProps { - isVisible: boolean; - onClose: () => void; - networkConfiguration: any; - navigation: any; - shouldNetworkSwitchPopToWallet: boolean; - onNetworkSwitch?: () => void; -} - -jest.mock('react-redux', () => ({ - ...jest.requireActual('react-redux'), - useDispatch: jest.fn(), - useSelector: jest.fn(), -})); -describe('NetworkDetails', () => { - const props: NetworkProps = { - isVisible: true, - onClose: () => ({}), - networkConfiguration: { - chainId: '1', - nickname: 'Test Network', - ticker: 'Test', - rpcUrl: 'https://localhost:8545', - formattedRpcUrl: 'https://localhost:8545', - rpcPrefs: { blockExplorerUrl: 'https://test.com', imageUrl: 'image' }, - }, - navigation: 'navigation', - shouldNetworkSwitchPopToWallet: true, - }; - it('renders correctly', () => { - (useSelector as jest.Mock).mockReturnValue(true); - const { toJSON } = render(); - - expect(toJSON()).toMatchSnapshot(); - }); -}); diff --git a/app/components/UI/NetworkModal/index.tsx b/app/components/UI/NetworkModal/index.tsx index 3594d1faf4b..18f72928e0f 100644 --- a/app/components/UI/NetworkModal/index.tsx +++ b/app/components/UI/NetworkModal/index.tsx @@ -1,38 +1,102 @@ import Modal from 'react-native-modal'; -import React, { useCallback, useEffect } from 'react'; -import { View } from 'react-native'; +import React from 'react'; +import { View, StyleSheet, Linking, Platform } from 'react-native'; +import StyledButton from '../StyledButton'; +import { fontStyles } from '../../../styles/common'; import { strings } from '../../../../locales/i18n'; import Text from '../../Base/Text'; import NetworkDetails from './NetworkDetails'; import NetworkAdded from './NetworkAdded'; import Engine from '../../../core/Engine'; -import { - isprivateConnection, - toggleUseSafeChainsListValidation, -} from '../../../util/networks'; +import { isprivateConnection } from '../../../util/networks'; import getDecimalChainId from '../../../util/networks/getDecimalChainId'; import URLPARSE from 'url-parse'; +import scaling from '../../../util/scaling'; import { isWebUri } from 'valid-url'; -import { useDispatch, useSelector } from 'react-redux'; +import FAIcon from 'react-native-vector-icons/FontAwesome'; +import InfoModal from '../Swaps/components/InfoModal'; +import ImageIcons from '../../UI/ImageIcon'; +import { useDispatch } from 'react-redux'; import { MetaMetricsEvents } from '../../../core/Analytics'; -import { BannerAlertSeverity } from '../../../component-library/components/Banners/Banner'; -import { - ButtonSize, - ButtonVariants, -} from '../../../component-library/components/Buttons/Button'; import AnalyticsV2 from '../../../util/analyticsV2'; import { useTheme } from '../../../util/theme'; import { networkSwitched } from '../../../actions/onboardNetwork'; +import generateTestId from '../../../../wdio/utils/generateTestId'; import { NetworkApprovalModalSelectorsIDs } from '../../../../e2e/selectors/Modals/NetworkApprovalModal.selectors'; -import { selectUseSafeChainsListValidation } from '../../../selectors/preferencesController'; -import BottomSheetFooter, { - ButtonsAlignment, -} from '../../../component-library/components/BottomSheets/BottomSheetFooter'; -import { ButtonProps } from '../../../component-library/components/Buttons/Button/Button.types'; -import checkSafeNetwork from '../../../core/RPCMethods/networkChecker.util'; -import NetworkVerificationInfo from '../NetworkVerificationInfo'; -import createNetworkModalStyles from './index.styles'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; + +const createStyles = (colors: ThemeColors) => + StyleSheet.create({ + bottomModal: { + justifyContent: 'flex-end', + margin: 0, + }, + modalContainer: { + borderRadius: 10, + backgroundColor: colors.background.default, + padding: 20, + }, + buttonView: { + flexDirection: 'row', + paddingVertical: 16, + }, + button: { + flex: 1, + }, + cancel: { + marginRight: 8, + borderColor: colors.text.muted, + borderWidth: 1, + }, + confirm: { + marginLeft: 8, + }, + networkInformation: { + flexDirection: 'row', + justifyContent: 'flex-start', + borderWidth: 1, + borderColor: colors.text.muted, + borderRadius: 10, + padding: 16, + marginBottom: 10, + }, + title: { + ...fontStyles.bold, + fontSize: scaling.scale(18), + textAlign: 'center', + color: colors.text.default, + lineHeight: 34, + marginVertical: 10, + paddingHorizontal: 16, + }, + bottomSpace: { + marginBottom: 10, + }, + nameWrapper: { + backgroundColor: colors.background.alternative, + marginRight: '15%', + marginLeft: '15%', + paddingVertical: 5, + borderRadius: 40, + justifyContent: 'center', + alignItems: 'center', + flexDirection: 'row', + }, + infoIconContainer: { + paddingHorizontal: 3, + }, + infoIcon: { + fontSize: 12, + color: colors.icon.default, + }, + popularNetworkImage: { + width: 20, + height: 20, + marginRight: 10, + borderRadius: 10, + }, + }); interface NetworkProps { isVisible: boolean; @@ -61,22 +125,13 @@ const NetworkModals = (props: NetworkProps) => { } = props; const [showDetails, setShowDetails] = React.useState(false); + const [showInfo, setShowInfo] = React.useState(false); const [networkAdded, setNetworkAdded] = React.useState(false); - const [showCheckNetwork, setShowCheckNetwork] = React.useState(false); - const [alerts, setAlerts] = React.useState< - { - alertError: string; - alertSeverity: BannerAlertSeverity; - alertOrigin: string; - }[] - >([]); - const isCustomNetwork = true; const showDetailsModal = () => setShowDetails(!showDetails); - const showCheckNetworkModal = () => setShowCheckNetwork(!showCheckNetwork); const { colors } = useTheme(); - const styles = createNetworkModalStyles(colors); + const styles = createStyles(colors); const dispatch = useDispatch(); @@ -91,64 +146,19 @@ const NetworkModals = (props: NetworkProps) => { setNetworkAdded(validUrl); }; - const cancelButtonProps: ButtonProps = { - variant: ButtonVariants.Secondary, - label: strings('accountApproval.cancel'), - size: ButtonSize.Lg, - onPress: showCheckNetworkModal, - testID: NetworkApprovalModalSelectorsIDs.CANCEL_BUTTON, - }; + const showToolTip = () => setShowInfo(!showInfo); - const confirmButtonProps: ButtonProps = { - variant: ButtonVariants.Primary, - label: strings('enter_password.confirm_button'), - size: ButtonSize.Lg, - onPress: () => { - toggleUseSafeChainsListValidation(true); - showCheckNetworkModal(); - }, - testID: NetworkApprovalModalSelectorsIDs.CONFIRM_NETWORK_CHECK, - }; - - const useSafeChainsListValidation = useSelector( - selectUseSafeChainsListValidation, - ); - - const customNetworkInformation = { - chainId, - blockExplorerUrl, - chainName: nickname, - rpcUrl, - icon: imageUrl, - ticker, - alerts, - }; - - const checkNetwork = useCallback(async () => { - if (useSafeChainsListValidation) { - const alertsNetwork = await checkSafeNetwork( - getDecimalChainId(chainId), - rpcUrl, - nickname, - ticker, - ); - - setAlerts(alertsNetwork); - } - }, [chainId, rpcUrl, nickname, ticker, useSafeChainsListValidation]); - - useEffect(() => { - checkNetwork(); - }, [checkNetwork]); + const goToLink = () => Linking.openURL(strings('networks.security_link')); const closeModal = () => { const { NetworkController } = Engine.context; const url = new URLPARSE(rpcUrl); + const decimalChainId = getDecimalChainId(chainId); !isprivateConnection(url.hostname) && url.set('protocol', 'https:'); NetworkController.upsertNetworkConfiguration( { rpcUrl: url.href, - chainId, + chainId: decimalChainId, ticker, nickname, rpcPrefs: { blockExplorerUrl }, @@ -166,12 +176,13 @@ const NetworkModals = (props: NetworkProps) => { const switchNetwork = () => { const { NetworkController, CurrencyRateController } = Engine.context; const url = new URLPARSE(rpcUrl); + const decimalChainId = getDecimalChainId(chainId); CurrencyRateController.setNativeCurrency(ticker); !isprivateConnection(url.hostname) && url.set('protocol', 'https:'); NetworkController.upsertNetworkConfiguration( { rpcUrl: url.href, - chainId, + chainId: decimalChainId, ticker, nickname, rpcPrefs: { blockExplorerUrl }, @@ -186,7 +197,7 @@ const NetworkModals = (props: NetworkProps) => { ); const analyticsParamsAdd = { - chain_id: getDecimalChainId(chainId), + chain_id: decimalChainId, source: 'Popular network list', symbol: ticker, }; @@ -213,35 +224,11 @@ const NetworkModals = (props: NetworkProps) => { backdropOpacity={0.7} animationInTiming={600} animationOutTiming={600} + swipeDirection={'down'} propagateSwipe > - {showCheckNetwork ? ( - - - - {strings('wallet.network_details_check')} - - - {strings('app_settings.use_safe_chains_list_validation_desc')} - - - - {strings('networks.network_select_confirm_use_safe_check')} - - {strings('networks.network_settings_security_privacy')} - {' '} - - - - - - - - ) : showDetails ? ( + {showDetails ? ( { /> ) : ( - - - - - - + )} + + + {nickname} + + + {strings('networks.want_to_add_network')} + + + {strings('networks.network_infomation')} + + + {strings('networks.network_endorsement')} + + + + + + {strings('networks.learn_about')} + + {strings('networks.network_risk')} + + + + + {strings('networks.network_display_name')} + + {nickname} + + {strings('networks.network_chain_id')} + + {chainId} + + {strings('networks.network_rpc_url')} + + {formattedRpcUrl || rpcUrl} + + + + + {strings('networks.view_details')} + + + + {strings('networks.cancel')} + + + {strings('networks.approve')} + )} diff --git a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.styles.ts b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.styles.ts index da1fa609867..0873292ea38 100644 --- a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.styles.ts +++ b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.styles.ts @@ -1,10 +1,10 @@ -import { StyleSheet, TextStyle } from 'react-native'; +import { StyleSheet } from 'react-native'; // External dependencies. import { Theme } from '../../../util/theme/models'; const styleSheet = (params: { theme: Theme }) => { const { theme } = params; - const { colors, typography } = theme; + const { colors } = theme; return StyleSheet.create({ root: { @@ -22,36 +22,7 @@ const styleSheet = (params: { theme: Theme }) => { textSection: { marginBottom: 8, }, - alertBar: { - width: '100%', - marginBottom: 15, - }, - title: { - textAlign: 'center', - marginVertical: 10, - paddingHorizontal: 16, - ...typography.lBodyMDBold, - } as TextStyle, - bottomSpace: { - marginBottom: 10, - }, - textContainer: { - paddingHorizontal: 16, - marginVertical: 10, - }, - warningContainer: { - marginTop: 20, - marginHorizontal: 4, - }, - errorContinue: { - marginVertical: 16, - }, - textCentred: { - textAlign: 'center', - }, - boldText: { - ...typography.sBodyMDBold, - } as TextStyle, + networkSection: { marginBottom: 16 }, nestedScrollContent: { paddingBottom: 24 }, }); diff --git a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.test.tsx b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.test.tsx index 45b0b9f28dc..effb2c89e6d 100644 --- a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.test.tsx +++ b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.test.tsx @@ -3,7 +3,6 @@ import NetworkVerificationInfo from './NetworkVerificationInfo'; import { render } from '@testing-library/react-native'; import { BannerAlertSeverity } from '../../../component-library/components/Banners/Banner'; import { strings } from '../../../../locales/i18n'; -import { useSelector } from 'react-redux'; const mockNetworkInfo = { chainName: 'Test Chain', @@ -21,17 +20,8 @@ const mockNetworkInfo = { icon: 'test-icon', }; -jest.mock('react-redux', () => ({ - ...jest.requireActual('react-redux'), - useSelector: jest.fn(), -})); - describe('NetworkVerificationInfo', () => { - beforeEach(() => { - (useSelector as jest.Mock).mockClear(); - }); it('renders correctly', () => { - (useSelector as jest.Mock).mockReturnValue(true); const { toJSON } = render( , ); @@ -39,7 +29,6 @@ describe('NetworkVerificationInfo', () => { expect(toJSON()).toMatchSnapshot(); }); it('renders one alert', () => { - (useSelector as jest.Mock).mockReturnValue(true); const { getByText } = render( , ); @@ -47,25 +36,4 @@ describe('NetworkVerificationInfo', () => { getByText(strings('add_custom_network.unrecognized_chain_name')), ).toBeDefined(); }); - - it('should render the banner', () => { - (useSelector as jest.Mock).mockReturnValue(false); - const { getByText } = render( - , - ); - expect( - getByText(strings('wallet.turn_on_network_check_cta')), - ).toBeDefined(); - }); - - it('should not render alert', () => { - (useSelector as jest.Mock).mockReturnValue(false); - const { getByText } = render( - , - ); - - expect(() => - getByText(strings('add_custom_network.unrecognized_chain_name')), - ).toThrow('Unable to find an element with text'); - }); }); diff --git a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.tsx b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.tsx index 0e5ff5b6bdd..4d8b4bd2f7c 100644 --- a/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.tsx +++ b/app/components/UI/NetworkVerificationInfo/NetworkVerificationInfo.tsx @@ -1,6 +1,6 @@ /* eslint-disable react/prop-types */ -import React, { useCallback, useEffect, useState } from 'react'; -import { View, Linking } from 'react-native'; +import React, { useCallback, useState } from 'react'; +import { Linking } from 'react-native'; import { strings } from '../../../../locales/i18n'; import { CommonSelectorsIDs } from '../../../../e2e/selectors/Common.selectors'; import Text, { @@ -13,59 +13,26 @@ import Banner, { BannerAlertSeverity, BannerVariant, } from '../../../component-library/components/Banners/Banner'; +import { DEFAULT_BUTTONLINK_LABEL_COLOR } from '../../../component-library/components/Buttons/Button/variants/ButtonLink/ButtonLink.constants'; import { useStyles } from '../../../component-library/hooks'; import styleSheet from './NetworkVerificationInfo.styles'; import { CustomNetworkInformation } from './NetworkVerificationInfo.types'; import { ScrollView } from 'react-native-gesture-handler'; import { ADD_CUSTOM_NETWORK_ARTCILE } from '../../../constants/urls'; -import { useSelector } from 'react-redux'; -import { selectUseSafeChainsListValidation } from '../../../selectors/preferencesController'; -import { - ButtonSize, - ButtonVariants, -} from '../../../component-library/components/Buttons/Button'; -import BottomSheetFooter, { - ButtonsAlignment, -} from '../../../component-library/components/BottomSheets/BottomSheetFooter'; -import BottomSheetHeader from '../../../component-library/components/BottomSheets/BottomSheetHeader'; -import { toggleUseSafeChainsListValidation } from '../../../util/networks'; -import { NetworkApprovalModalSelectorsIDs } from '../../../../e2e/selectors/Modals/NetworkApprovalModal.selectors'; - -interface Alert { - alertError: string; - alertSeverity: BannerAlertSeverity; - alertOrigin: string; -} /** * NetworkVerificationInfo component */ const NetworkVerificationInfo = ({ customNetworkInformation, - onReject, - onConfirm, - isCustomNetwork = false, }: { customNetworkInformation: CustomNetworkInformation; - onReject: () => void; - onConfirm: () => void; - isCustomNetwork?: boolean; }) => { const [networkInfoMaxHeight, setNetworkInfoMaxHeight] = useState< number | null >(null); const [networkDetailsExpanded, setNetworkDetailsExpanded] = useState(false); const { styles } = useStyles(styleSheet, {}); - const safeChainsListValidationEnabled = useSelector( - selectUseSafeChainsListValidation, - ); - const [showCheckNetwork, setShowCheckNetwork] = React.useState(false); - const { alerts: alertsFromProps } = customNetworkInformation; - const [alerts, setAlerts] = React.useState([]); - - const showCheckNetworkModal = () => setShowCheckNetwork(!showCheckNetwork); - - useEffect(() => setAlerts(alertsFromProps), [alertsFromProps]); const renderNetworkInfo = () => ( { - if (!safeChainsListValidationEnabled) { - return ( - - - - ); - } - return null; - }; - const renderAlerts = useCallback(() => { - if (!safeChainsListValidationEnabled) return null; - if (!alerts.length) return null; - return alerts.map( - ( - networkAlert: { - alertError: string; - alertSeverity: BannerAlertSeverity; - alertOrigin: string; - }, - index, - ) => ( + if (!customNetworkInformation.alerts.length) return null; + return customNetworkInformation.alerts.map( + (networkAlert: { + alertError: string; + alertSeverity: BannerAlertSeverity; + alertOrigin: string; + }) => ( { - const newAlerts = [...alerts]; - newAlerts.splice(index, 1); - setAlerts(newAlerts); - }} /> ), ); - }, [alerts, styles.textSection, safeChainsListValidationEnabled]); - - return showCheckNetwork ? ( - - - - {strings('wallet.network_details_check')} - - - {strings('app_settings.use_safe_chains_list_validation_desc_1')}{' '} - chainid.network{' '} - {strings('app_settings.use_safe_chains_list_validation_desc_2')} - - - - {strings('networks.network_select_confirm_use_safe_check')}{' '} - - {strings('networks.network_settings_security_privacy')} - - - - - { - toggleUseSafeChainsListValidation(true); - showCheckNetworkModal(); - }, - label: strings('confirmation_modal.confirm_cta'), - variant: ButtonVariants.Primary, - size: ButtonSize.Lg, - testID: CommonSelectorsIDs.CONNECT_BUTTON, - }, - ]} - buttonsAlignment={ButtonsAlignment.Horizontal} + }, [customNetworkInformation.alerts, styles.textSection]); + + return ( + + - - ) : ( - - - - {isCustomNetwork - ? strings('networks.add_custom_network') - : strings('app_settings.network_add_network')} - - - - - {renderAlerts()} - {renderBanner()} - - {strings('add_custom_network.warning_subtext_new.1')}{' '} - - {strings('add_custom_network.warning_subtext_new.2')} - + {renderAlerts()} + + {strings('add_custom_network.warning_subtext_new.1')}{' '} + + {strings('add_custom_network.warning_subtext_new.2')} - {renderNetworkInfo()} - - - + + {renderNetworkInfo()} + ); }; diff --git a/app/components/UI/NetworkVerificationInfo/__snapshots__/NetworkVerificationInfo.test.tsx.snap b/app/components/UI/NetworkVerificationInfo/__snapshots__/NetworkVerificationInfo.test.tsx.snap index a9f05c62c14..02f7903ddb4 100644 --- a/app/components/UI/NetworkVerificationInfo/__snapshots__/NetworkVerificationInfo.test.tsx.snap +++ b/app/components/UI/NetworkVerificationInfo/__snapshots__/NetworkVerificationInfo.test.tsx.snap @@ -1,259 +1,269 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`NetworkVerificationInfo renders correctly 1`] = ` - - - + + - - + > + + - Add Network + Test Chain - + - - - - - - - - + width={24} + /> + + - Test Chain + It looks like this network's display name doesn't match its chain ID. - - + + + MetaMask doesn’t verify custom networks, so only approve networks you trust. + + - + + + + - - - + - + - It looks like this network's display name doesn't match its chain ID. - - - + Chain ID + + - + - - - - - - MetaMask doesn’t verify custom networks, so only approve networks you trust. - + > + Network URL + - Learn more about network security risks and scams. + http://test.com - - - - - Display name - - - Test Chain - - - Chain ID - - - 1 - - - Network URL - + } + testID="accordionheader" + > - http://test.com + View details - - - View details - - - - - - - - - - - - - Cancel - - - - - Confirm - - + testID="accordionheader-arrow-icon" + width={16} + /> + + + + - + `; diff --git a/app/components/UI/Notification/TransactionNotification/index.js b/app/components/UI/Notification/TransactionNotification/index.js index 6543347eea5..4c583b8d82b 100644 --- a/app/components/UI/Notification/TransactionNotification/index.js +++ b/app/components/UI/Notification/TransactionNotification/index.js @@ -35,7 +35,6 @@ import { selectTokensByAddress } from '../../../../selectors/tokensController'; import { selectContractExchangeRates } from '../../../../selectors/tokenRatesController'; import { selectAccounts } from '../../../../selectors/accountTrackerController'; import { selectSelectedAddress } from '../../../../selectors/preferencesController'; -import { speedUpTransaction } from '../../../../util/transaction-controller'; const WINDOW_WIDTH = Dimensions.get('window').width; const ACTION_CANCEL = 'cancel'; @@ -203,8 +202,10 @@ function TransactionNotification(props) { [onActionFinish], ); - const speedUpTx = useCallback(() => { - safelyExecute(() => speedUpTransaction(tx?.id)); + const speedUpTransaction = useCallback(() => { + safelyExecute(() => + Engine.context.TransactionController.speedUpTransaction(tx?.id), + ); }, [safelyExecute, tx]); const stopTransaction = useCallback(() => { @@ -329,7 +330,7 @@ function TransactionNotification(props) { onConfirmPress={ transactionAction === ACTION_CANCEL ? stopTransaction - : speedUpTx + : speedUpTransaction } confirmText={strings('transaction.lets_try')} confirmButtonMode={'confirm'} diff --git a/app/components/UI/OnboardingWizard/Coachmark/__snapshots__/index.test.tsx.snap b/app/components/UI/OnboardingWizard/Coachmark/__snapshots__/index.test.tsx.snap index e3f79c2b8c7..e8a4b95e504 100644 --- a/app/components/UI/OnboardingWizard/Coachmark/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/OnboardingWizard/Coachmark/__snapshots__/index.test.tsx.snap @@ -61,7 +61,7 @@ exports[`Coachmark should render correctly 1`] = ` } > @@ -106,7 +106,7 @@ exports[`Coachmark should render correctly 1`] = ` diff --git a/app/components/UI/OptinMetrics/index.js b/app/components/UI/OptinMetrics/index.js index 666f50c094a..f3cc890338e 100644 --- a/app/components/UI/OptinMetrics/index.js +++ b/app/components/UI/OptinMetrics/index.js @@ -17,11 +17,17 @@ import { getOptinMetricsNavbarOptions } from '../Navbar'; import { strings } from '../../../../locales/i18n'; import setOnboardingWizardStep from '../../../actions/wizard'; import { connect } from 'react-redux'; +import Analytics from '../../../core/Analytics/Analytics'; import { clearOnboardingEvents } from '../../../actions/onboarding'; -import { ONBOARDING_WIZARD } from '../../../constants/storage'; +import { + ONBOARDING_WIZARD, + METRICS_OPT_IN, + DENIED, + AGREED, +} from '../../../constants/storage'; import AppConstants from '../../../core/AppConstants'; -import { Analytics, MetaMetricsEvents } from '../../../core/Analytics'; -import { withMetricsAwareness } from '../../hooks/useMetrics'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import DefaultPreference from 'react-native-default-preference'; import { ThemeContext } from '../../../util/theme'; @@ -39,9 +45,6 @@ import Button, { } from '../../../component-library/components/Buttons/Button'; import { MAINNET } from '../../../constants/network'; import Routes from '../../../constants/navigation/Routes'; -import generateDeviceAnalyticsMetaData, { - UserSettingsAnalyticsMetaData as generateUserSettingsAnalyticsMetaData, -} from '../../../util/metrics'; const createStyles = ({ colors }) => StyleSheet.create({ @@ -141,10 +144,6 @@ class OptinMetrics extends PureComponent { * Object that represents the current route info like params passed to it */ route: PropTypes.object, - /** - * Metrics injected by withMetricsAwareness HOC - */ - metrics: PropTypes.object, }; state = { @@ -261,17 +260,32 @@ class OptinMetrics extends PureComponent { ); }; + /** + * Track the event of opt in or opt out. + * @param AnalyticsOptionSelected - User selected option regarding the tracking of events + */ + trackOptInEvent = (AnalyticsOptionSelected) => { + InteractionManager.runAfterInteractions(async () => { + AnalyticsV2.trackEvent(MetaMetricsEvents.ANALYTICS_PREFERENCE_SELECTED, { + analytics_option_selected: AnalyticsOptionSelected, + updated_after_onboarding: false, + }); + }); + }; + /** * Callback on press cancel */ onCancel = async () => { + const { events } = this.props; + const metricsOptionSelected = 'Metrics Opt Out'; setTimeout(async () => { - const { clearOnboardingEvents, metrics } = this.props; - // if users refuses tracking, get rid of the stored events - // and never send them to Segment - // and disable analytics - clearOnboardingEvents(); - await metrics.enable(false); + if (events && events.length) { + events.forEach((eventArgs) => AnalyticsV2.trackEvent(...eventArgs)); + } + this.trackOptInEvent(metricsOptionSelected); + this.props.clearOnboardingEvents(); + await DefaultPreference.set(METRICS_OPT_IN, DENIED); Analytics.disableInstance(); }, 200); this.continue(); @@ -281,44 +295,17 @@ class OptinMetrics extends PureComponent { * Callback on press confirm */ onConfirm = async () => { - const { events, metrics } = this.props; - await metrics.enable(); - InteractionManager.runAfterInteractions(async () => { - // add traits to user for identification - // consolidate device and user settings traits - const consolidatedTraits = { - ...generateDeviceAnalyticsMetaData(), - ...generateUserSettingsAnalyticsMetaData(), - }; - await metrics.addTraitsToUser(consolidatedTraits); - - // track onboarding events that were stored before user opted in - // only if the user eventually opts in. + const { events } = this.props; + const metricsOptionSelected = 'Metrics Opt In'; + Analytics.enable(); + setTimeout(async () => { if (events && events.length) { - let delay = 0; // Initialize delay - const eventTrackingDelay = 200; // ms delay between each event - events.forEach((eventArgs) => { - // delay each event to prevent them from - // being tracked with the same timestamp - // which would cause them to be grouped together - // by sentAt time in the Segment dashboard - // as precision is only to the milisecond - // and loop seems to runs faster than that - setTimeout(() => { - metrics.trackEvent(...eventArgs); - }, delay); - delay += eventTrackingDelay; - }); + events.forEach((eventArgs) => AnalyticsV2.trackEvent(...eventArgs)); } - + this.trackOptInEvent(metricsOptionSelected); this.props.clearOnboardingEvents(); - - // track event for user opting in - metrics.trackEvent(MetaMetricsEvents.ANALYTICS_PREFERENCE_SELECTED, { - analytics_option_selected: 'Metrics Opt In', - updated_after_onboarding: false, - }); - }); + await DefaultPreference.set(METRICS_OPT_IN, AGREED); + }, 200); this.continue(); }; @@ -536,7 +523,4 @@ const mapDispatchToProps = (dispatch) => ({ clearOnboardingEvents: () => dispatch(clearOnboardingEvents()), }); -export default connect( - mapStateToProps, - mapDispatchToProps, -)(withMetricsAwareness(OptinMetrics)); +export default connect(mapStateToProps, mapDispatchToProps)(OptinMetrics); diff --git a/app/components/UI/PaymentRequest/index.js b/app/components/UI/PaymentRequest/index.js index 7eeecdeece4..267aa2b0e0a 100644 --- a/app/components/UI/PaymentRequest/index.js +++ b/app/components/UI/PaymentRequest/index.js @@ -40,7 +40,7 @@ import { } from '../../../util/payment-link-generator'; import Device from '../../../util/device'; import currencySymbols from '../../../util/currency-symbols.json'; -import { ChainId } from '@metamask/controller-utils'; +import { NetworksChainId } from '@metamask/controller-utils'; import { getTicker } from '../../../util/transactions'; import { toLowerCaseEquals } from '../../../util/general'; import { utils as ethersUtils } from 'ethers'; @@ -433,13 +433,13 @@ class PaymentRequest extends PureComponent { if (isTDSupportedForNetwork) { const defaults = - chainId === ChainId.mainnet + chainId === NetworksChainId.mainnet ? defaultAssets : [{ ...defaultEth, symbol: getTicker(ticker), name: '' }]; results = this.state.searchInputValue ? this.state.results : defaults; } else if ( //Check to see if it is not a test net ticker symbol - Object.values(ChainId).find((value) => value === chainId) && + Object.values(NetworksChainId).find((value) => value === chainId) && !(parseInt(chainId, 10) > 1 && parseInt(chainId, 10) < 6) ) { results = [defaultEth]; diff --git a/app/components/Views/confirmations/components/PersonalSign/PersonalSign.tsx b/app/components/UI/PersonalSign/PersonalSign.tsx similarity index 84% rename from app/components/Views/confirmations/components/PersonalSign/PersonalSign.tsx rename to app/components/UI/PersonalSign/PersonalSign.tsx index c0986c88f71..0ba3d6e9083 100644 --- a/app/components/Views/confirmations/components/PersonalSign/PersonalSign.tsx +++ b/app/components/UI/PersonalSign/PersonalSign.tsx @@ -1,35 +1,34 @@ import React, { useState, useEffect, useCallback } from 'react'; import { useSelector } from 'react-redux'; import { View, Text, InteractionManager } from 'react-native'; -import Engine from '../../../../../core/Engine'; +import Engine from '../../../core/Engine'; import SignatureRequest from '../SignatureRequest'; import ExpandedMessage from '../SignatureRequest/ExpandedMessage'; -import NotificationManager from '../../../../../core/NotificationManager'; -import { strings } from '../../../../../../locales/i18n'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; +import NotificationManager from '../../../core/NotificationManager'; +import { strings } from '../../../../locales/i18n'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { getAddressAccountType, isExternalHardwareAccount, stripHexPrefix, -} from '../../../../../util/address'; -import sanitizeString from '../../../../../util/string'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import { useTheme } from '../../../../../util/theme'; +} from '../../../util/address'; +import sanitizeString from '../../../util/string'; +import { KEYSTONE_TX_CANCELED } from '../../../constants/error'; +import { useTheme } from '../../../util/theme'; import { PersonalSignProps } from './types'; import { useNavigation } from '@react-navigation/native'; import createStyles from './styles'; -import AppConstants from '../../../../../core/AppConstants'; -import createExternalSignModelNav from '../../../../../util/hardwareWallet/signatureUtils'; -import { selectChainId } from '../../../../../selectors/networkController'; -import { store } from '../../../../../store'; -import { getBlockaidMetricsParams } from '../../../../../util/blockaid'; +import AppConstants from '../../../core/AppConstants'; +import createExternalSignModelNav from '../../../util/hardwareWallet/signatureUtils'; +import { selectChainId } from '../../../selectors/networkController'; +import { store } from '../../../store'; +import { getBlockaidMetricsParams } from '../../../util/blockaid'; import { SecurityAlertResponse } from '../BlockaidBanner/BlockaidBanner.types'; -import { SigningModalSelectorsIDs } from '../../../../../../e2e/selectors/Modals/SigningModal.selectors'; -import { getDecimalChainId } from '../../../../../util/networks'; -import Logger from '../../../../../util/Logger'; +import { SigningModalSelectorsIDs } from '../../../../e2e/selectors/Modals/SigningModal.selectors'; +import Logger from '../../../util/Logger'; /** * Converts a hexadecimal string to a utf8 string. @@ -94,7 +93,7 @@ const PersonalSign = ({ return { account_type: getAddressAccountType(messageParams.from), dapp_host_name: url?.host, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, signature_type: 'personal_sign', ...pageInfo?.analytics, ...blockaidParams, diff --git a/app/components/Views/confirmations/components/PersonalSign/__snapshots__/index.test.tsx.snap b/app/components/UI/PersonalSign/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/PersonalSign/__snapshots__/index.test.tsx.snap rename to app/components/UI/PersonalSign/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/PersonalSign/index.test.tsx b/app/components/UI/PersonalSign/index.test.tsx similarity index 89% rename from app/components/Views/confirmations/components/PersonalSign/index.test.tsx rename to app/components/UI/PersonalSign/index.test.tsx index b2793039d9f..e5897a1336f 100644 --- a/app/components/Views/confirmations/components/PersonalSign/index.test.tsx +++ b/app/components/UI/PersonalSign/index.test.tsx @@ -1,19 +1,19 @@ import React from 'react'; import { shallow } from 'enzyme'; -import PersonalSign from '.'; +import PersonalSign from './'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; import SignatureRequest from '../SignatureRequest'; -import Engine from '../../../../../core/Engine'; -import NotificationManager from '../../../../../core/NotificationManager'; +import Engine from '../../../core/Engine'; +import NotificationManager from '../../../core/NotificationManager'; import { InteractionManager } from 'react-native'; -import AppConstants from '../../../../../core/AppConstants'; -import { strings } from '../../../../../../locales/i18n'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import analyticsV2 from '../../../../../util/analyticsV2'; +import AppConstants from '../../../core/AppConstants'; +import { strings } from '../../../../locales/i18n'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; +import analyticsV2 from '../../../util/analyticsV2'; -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../core/Engine', () => ({ acceptPendingApproval: jest.fn(), rejectPendingApproval: jest.fn(), context: { @@ -30,7 +30,7 @@ jest.mock('../../../../../core/Engine', () => ({ }, })); -jest.mock('../../../../../core/NotificationManager', () => ({ +jest.mock('../../../core/NotificationManager', () => ({ showSimpleNotification: jest.fn(), })); @@ -69,9 +69,9 @@ jest.mock('react-redux', () => ({ }), })); -jest.mock('../../../../../util/analyticsV2'); +jest.mock('../../../util/analyticsV2'); -jest.mock('../../../../../util/address', () => ({ +jest.mock('../../../util/address', () => ({ getAddressAccountType: jest.fn().mockReturnValue('Metamask'), isExternalHardwareAccount: jest.fn().mockReturnValue(false), })); diff --git a/app/components/Views/confirmations/components/PersonalSign/index.ts b/app/components/UI/PersonalSign/index.ts similarity index 100% rename from app/components/Views/confirmations/components/PersonalSign/index.ts rename to app/components/UI/PersonalSign/index.ts diff --git a/app/components/Views/confirmations/components/PersonalSign/styles.ts b/app/components/UI/PersonalSign/styles.ts similarity index 87% rename from app/components/Views/confirmations/components/PersonalSign/styles.ts rename to app/components/UI/PersonalSign/styles.ts index 307e88ca81a..de28c14f735 100644 --- a/app/components/Views/confirmations/components/PersonalSign/styles.ts +++ b/app/components/UI/PersonalSign/styles.ts @@ -1,5 +1,5 @@ import { StyleSheet } from 'react-native'; -import { fontStyles } from '../../../../../styles/common'; +import { fontStyles } from '../../../styles/common'; export default (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/PersonalSign/types.ts b/app/components/UI/PersonalSign/types.ts similarity index 100% rename from app/components/Views/confirmations/components/PersonalSign/types.ts rename to app/components/UI/PersonalSign/types.ts diff --git a/app/components/UI/Ramp/Views/BuildQuote/__snapshots__/BuildQuote.test.tsx.snap b/app/components/UI/Ramp/Views/BuildQuote/__snapshots__/BuildQuote.test.tsx.snap index fd694600bd4..beda4b1db08 100644 --- a/app/components/UI/Ramp/Views/BuildQuote/__snapshots__/BuildQuote.test.tsx.snap +++ b/app/components/UI/Ramp/Views/BuildQuote/__snapshots__/BuildQuote.test.tsx.snap @@ -674,7 +674,7 @@ exports[`BuildQuote View Crypto Currency Data renders a special error page if cr "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -1406,7 +1406,7 @@ exports[`BuildQuote View Crypto Currency Data renders a special error page if cr "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -2138,7 +2138,7 @@ exports[`BuildQuote View Crypto Currency Data renders an error page when there i "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -3736,7 +3736,7 @@ exports[`BuildQuote View Fiat Currency Data renders an error page when there is "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -5334,7 +5334,7 @@ exports[`BuildQuote View Payment Method Data renders an error page when there is "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -6932,7 +6932,7 @@ exports[`BuildQuote View Regions data renders an error page when there is a regi "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -9659,7 +9659,7 @@ exports[`BuildQuote View renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -10944,7 +10944,7 @@ exports[`BuildQuote View renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -12837,7 +12837,7 @@ exports[`BuildQuote View renders correctly 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -14187,7 +14187,7 @@ exports[`BuildQuote View renders correctly 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -15004,7 +15004,7 @@ exports[`BuildQuote View renders correctly when sdkError is present 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -15707,7 +15707,7 @@ exports[`BuildQuote View renders correctly when sdkError is present 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/GetStarted/__snapshots__/GetStarted.test.tsx.snap b/app/components/UI/Ramp/Views/GetStarted/__snapshots__/GetStarted.test.tsx.snap index f08c774fbc4..bd7f860e121 100644 --- a/app/components/UI/Ramp/Views/GetStarted/__snapshots__/GetStarted.test.tsx.snap +++ b/app/components/UI/Ramp/Views/GetStarted/__snapshots__/GetStarted.test.tsx.snap @@ -642,7 +642,7 @@ exports[`GetStarted renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -1311,7 +1311,7 @@ exports[`GetStarted renders correctly 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -2428,7 +2428,7 @@ exports[`GetStarted renders correctly when sdkError is present 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.test.tsx b/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.test.tsx index 169c962fca7..473285b4fc4 100644 --- a/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.test.tsx +++ b/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.test.tsx @@ -80,13 +80,13 @@ function render(Component: React.ComponentType, chainId?: string) { NetworkController: { ...initialBackgroundState.NetworkController, providerConfig: { - chainId: chainId ?? '0x38', + chainId: chainId ?? '56', ticker: 'BNB', nickname: 'BNB Smart Chain', }, networkConfigurations: { networkId1: { - chainId: '0x89', + chainId: '137', nickname: 'Polygon Mainnet', rpcPrefs: { blockExplorerUrl: 'https://polygonscan.com' }, rpcUrl: diff --git a/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.tsx b/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.tsx index 3441401a1d2..df410f24eb2 100644 --- a/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.tsx +++ b/app/components/UI/Ramp/Views/NetworkSwitcher/NetworkSwitcher.tsx @@ -2,7 +2,7 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useNavigation } from '@react-navigation/native'; import { RefreshControl, TouchableOpacity, View } from 'react-native'; import { ScrollView } from 'react-native-gesture-handler'; -import { ChainId, NetworkType, toHex } from '@metamask/controller-utils'; +import { NetworksChainId, NetworkType } from '@metamask/controller-utils'; import { useSelector } from 'react-redux'; import LoadingNetworksSkeleton from './LoadingNetworksSkeleton'; @@ -63,10 +63,10 @@ function NetworkSwitcher() { const rampNetworks = useMemo(() => { const activeNetworkDetails: Network[] = []; supportedNetworks.forEach(({ chainId: supportedChainId, active }) => { - const currentChainId = toHex(supportedChainId); + const currentChainId = `${supportedChainId}`; if ( - currentChainId === ChainId['linea-mainnet'] || - currentChainId === ChainId.mainnet || + currentChainId === NetworksChainId['linea-mainnet'] || + currentChainId === NetworksChainId.mainnet || !active ) { return; @@ -82,7 +82,7 @@ function NetworkSwitcher() { } const networkDetail = networksDetails.find( - ({ chainId }) => toHex(chainId) === currentChainId, + ({ chainId }) => chainId === currentChainId, ); if (networkDetail) { activeNetworkDetails.push(networkDetail); @@ -227,7 +227,10 @@ function NetworkSwitcher() { ) : ( <> - {isNetworkRampSupported(ChainId.mainnet, supportedNetworks) ? ( + {isNetworkRampSupported( + NetworksChainId.mainnet, + supportedNetworks, + ) ? ( switchToMainnet('mainnet')} @@ -250,7 +253,7 @@ function NetworkSwitcher() { ) : null} {isNetworkRampSupported( - ChainId['linea-mainnet'], + NetworksChainId['linea-mainnet'], supportedNetworks, ) ? ( @@ -944,468 +958,828 @@ exports[`NetworkSwitcher View renders and dismisses network modal when pressing style={ Object { "alignItems": "center", - "alignSelf": "stretch", - "padding": 4, + "backgroundColor": "#F2F4F6", + "borderRadius": 40, + "flexDirection": "row", + "justifyContent": "center", + "marginLeft": "15%", + "marginRight": "15%", + "paddingVertical": 5, } } + testID="approve-network-modal" + > + + Cronos Mainnet + + + + Want to add this network? + + + This allows this network to be used within MetaMask + + + MetaMask does not endorse custom networks or their security. - + > + +  + + + + + + Learn about + + + + scams and network security risks + + - - + - + - - - - - Add custom network - - - - - - - + Cronos Mainnet + + + Chain ID + + + 25 + + + Network URL + + - - + + + + View details + + + - - - - - Cronos Mainnet - - - - MetaMask doesn’t verify custom networks, so only approve networks you trust. - - - Learn more about network security risks and scams. - - - - - - Display name - - - Cronos Mainnet - - - Chain ID - - - 25 - - - Network URL - - - https://evm.cronos.org - - - - View details - - - - - - - - - - + - + + - - Cancel - - - - + - Confirm - - - - + "fontWeight": "600", + "textAlign": "center", + }, + Object { + "color": "#FCFCFC", + }, + undefined, + ], + null, + ] + } + > + Approve + + @@ -8369,7 +8743,7 @@ exports[`NetworkSwitcher View renders correctly with errors 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -9051,7 +9425,7 @@ exports[`NetworkSwitcher View renders correctly with errors 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -9733,7 +10107,7 @@ exports[`NetworkSwitcher View renders correctly with no data 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/OrderDetails/__snapshots__/OrderDetails.test.tsx.snap b/app/components/UI/Ramp/Views/OrderDetails/__snapshots__/OrderDetails.test.tsx.snap index b7553163a74..5cbf28e682a 100644 --- a/app/components/UI/Ramp/Views/OrderDetails/__snapshots__/OrderDetails.test.tsx.snap +++ b/app/components/UI/Ramp/Views/OrderDetails/__snapshots__/OrderDetails.test.tsx.snap @@ -1910,7 +1910,7 @@ exports[`OrderDetails renders a cancelled order 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -2425,7 +2425,7 @@ exports[`OrderDetails renders a completed order 1`] = ` style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 32, }, undefined, @@ -3864,7 +3864,7 @@ exports[`OrderDetails renders a completed order 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -7685,7 +7685,7 @@ exports[`OrderDetails renders a failed order 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -10686,7 +10686,7 @@ exports[`OrderDetails renders an error screen if a CREATED order cannot be polle "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -12678,7 +12678,7 @@ exports[`OrderDetails renders non-transacted orders 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -13194,7 +13194,7 @@ exports[`OrderDetails renders the support links if the provider has them 1`] = ` style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 32, }, undefined, @@ -14741,7 +14741,7 @@ exports[`OrderDetails renders the support links if the provider has them 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/OrdersList/OrdersList.test.tsx b/app/components/UI/Ramp/Views/OrdersList/OrdersList.test.tsx index 1cf05fc4096..59b72f8c486 100644 --- a/app/components/UI/Ramp/Views/OrdersList/OrdersList.test.tsx +++ b/app/components/UI/Ramp/Views/OrdersList/OrdersList.test.tsx @@ -125,7 +125,7 @@ function render(Component: React.ReactElement, orders = testOrders) { providerConfig: { ticker: 'ETH', type: 'mainnet', - chainId: '0x1', + chainId: '1', }, }, }, diff --git a/app/components/UI/Ramp/Views/OrdersList/__snapshots__/OrdersList.test.tsx.snap b/app/components/UI/Ramp/Views/OrdersList/__snapshots__/OrdersList.test.tsx.snap index eb15ac6f751..185b239f73a 100644 --- a/app/components/UI/Ramp/Views/OrdersList/__snapshots__/OrdersList.test.tsx.snap +++ b/app/components/UI/Ramp/Views/OrdersList/__snapshots__/OrdersList.test.tsx.snap @@ -231,7 +231,7 @@ exports[`OrdersList renders buy only correctly when pressing buy filter 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -464,7 +464,7 @@ exports[`OrdersList renders buy only correctly when pressing buy filter 1`] = ` accessibilityRole="text" style={ Object { - "color": "#1C8234", + "color": "#28A745", "fontFamily": "Euclid Circular B", "fontSize": 12, "fontWeight": "700", @@ -1352,7 +1352,7 @@ exports[`OrdersList renders correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -1624,7 +1624,7 @@ exports[`OrdersList renders correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#1C8234", + "color": "#28A745", "fontFamily": "Euclid Circular B", "fontSize": 12, "fontWeight": "700", @@ -2760,7 +2760,7 @@ exports[`OrdersList renders empty buy message 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -3050,7 +3050,7 @@ exports[`OrdersList renders empty sell message 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -3327,7 +3327,7 @@ exports[`OrdersList renders sell only correctly when pressing sell filter 1`] = accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -3873,7 +3873,7 @@ exports[`OrdersList resets filter to all after other filter was set 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -4405,7 +4405,7 @@ exports[`OrdersList resets filter to all after other filter was set 2`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", @@ -4677,7 +4677,7 @@ exports[`OrdersList resets filter to all after other filter was set 2`] = ` accessibilityRole="text" style={ Object { - "color": "#1C8234", + "color": "#28A745", "fontFamily": "Euclid Circular B", "fontSize": 12, "fontWeight": "700", diff --git a/app/components/UI/Ramp/Views/PaymentMethods/__snapshots__/PaymentMethods.test.tsx.snap b/app/components/UI/Ramp/Views/PaymentMethods/__snapshots__/PaymentMethods.test.tsx.snap index f281af080d5..dd2d5a92c0d 100644 --- a/app/components/UI/Ramp/Views/PaymentMethods/__snapshots__/PaymentMethods.test.tsx.snap +++ b/app/components/UI/Ramp/Views/PaymentMethods/__snapshots__/PaymentMethods.test.tsx.snap @@ -2030,7 +2030,7 @@ exports[`PaymentMethods View renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -4088,7 +4088,7 @@ exports[`PaymentMethods View renders correctly for sell 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -6221,7 +6221,7 @@ If you selected Chile by mistake, click the button below to reset your region. "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -6926,7 +6926,7 @@ If you selected Chile by mistake, click the button below to reset your region. "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -7629,7 +7629,7 @@ exports[`PaymentMethods View renders correctly with error 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -11175,7 +11175,7 @@ exports[`PaymentMethods View renders correctly with payment method with disclaim "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -11877,7 +11877,7 @@ exports[`PaymentMethods View renders correctly with sdkError 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -13913,7 +13913,7 @@ exports[`PaymentMethods View renders correctly with show back button false 1`] = "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/Quotes/Quotes.tsx b/app/components/UI/Ramp/Views/Quotes/Quotes.tsx index 6cbf49eb632..ed7e51d25a8 100644 --- a/app/components/UI/Ramp/Views/Quotes/Quotes.tsx +++ b/app/components/UI/Ramp/Views/Quotes/Quotes.tsx @@ -593,11 +593,6 @@ function Quotes() { (link) => link.name === PROVIDER_LINKS.PRIVACY_POLICY, )?.url } - providerTermsOfService={ - selectedProviderInfo?.links?.find( - (link) => link.name === PROVIDER_LINKS.TOS, - )?.url - } providerSupport={ selectedProviderInfo?.links?.find( (link) => link.name === PROVIDER_LINKS.SUPPORT, diff --git a/app/components/UI/Ramp/Views/Quotes/__snapshots__/Quotes.test.tsx.snap b/app/components/UI/Ramp/Views/Quotes/__snapshots__/Quotes.test.tsx.snap index 73f38913267..19b7f536e33 100644 --- a/app/components/UI/Ramp/Views/Quotes/__snapshots__/Quotes.test.tsx.snap +++ b/app/components/UI/Ramp/Views/Quotes/__snapshots__/Quotes.test.tsx.snap @@ -2275,7 +2275,7 @@ exports[`Quotes renders correctly after animation with quotes 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -2615,7 +2615,7 @@ exports[`Quotes renders correctly after animation with quotes 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -3296,7 +3296,7 @@ exports[`Quotes renders correctly after animation without quotes 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -3968,7 +3968,7 @@ exports[`Quotes renders correctly when fetching quotes errors 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -4668,7 +4668,7 @@ exports[`Quotes renders correctly with sdkError 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -5343,7 +5343,7 @@ exports[`Quotes renders quotes expired screen 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/Regions/__snapshots__/Regions.test.tsx.snap b/app/components/UI/Ramp/Views/Regions/__snapshots__/Regions.test.tsx.snap index 8dad06619da..247be1fc570 100644 --- a/app/components/UI/Ramp/Views/Regions/__snapshots__/Regions.test.tsx.snap +++ b/app/components/UI/Ramp/Views/Regions/__snapshots__/Regions.test.tsx.snap @@ -737,7 +737,7 @@ exports[`Regions View renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -2081,7 +2081,7 @@ exports[`Regions View renders correctly with error 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -3367,7 +3367,7 @@ exports[`Regions View renders correctly with sdkError 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -4133,7 +4133,7 @@ exports[`Regions View renders correctly with selectedRegion 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -4955,7 +4955,7 @@ exports[`Regions View renders correctly with unsupportedRegion 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -6153,7 +6153,7 @@ exports[`Regions View renders correctly with unsupportedRegion 2`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -7351,7 +7351,7 @@ exports[`Regions View renders regions modal when pressing select button 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.test.tsx b/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.test.tsx index 7f8d13ca8cf..2ffd1b51011 100644 --- a/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.test.tsx +++ b/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.test.tsx @@ -6,9 +6,8 @@ import Routes from '../../../../../constants/navigation/Routes'; import { renderScreen } from '../../../../../util/test/renderWithProvider'; import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import { addTransaction } from '../../../../../util/transaction-controller'; - import SendTransaction from './SendTransaction'; +import Engine from '../../../../../core/Engine'; type DeepPartial = { [key in keyof BaseType]?: DeepPartial; @@ -291,7 +290,6 @@ const mockGoBack = jest.fn(); const mockReset = jest.fn(); const mockPop = jest.fn(); const mockTrackEvent = jest.fn(); -const mockAddTransaction = addTransaction as jest.Mock; jest.mock('@react-navigation/native', () => { const actualReactNavigation = jest.requireActual('@react-navigation/native'); @@ -322,10 +320,12 @@ jest.mock('../../../../../util/navigation/navUtils', () => ({ useParams: jest.fn(() => mockUseParamsValues), })); -jest.mock('../../../../../util/transaction-controller', () => ({ - __esModule: true, - ...jest.requireActual('../../../../../util/transaction-controller'), - addTransaction: jest.fn(), +jest.mock('../../../../../core/Engine', () => ({ + context: { + TransactionController: { + addTransaction: jest.fn(), + }, + }, })); const mockDispatch = jest.fn(); @@ -346,7 +346,7 @@ describe('SendTransaction View', () => { mockPop.mockClear(); mockDispatch.mockClear(); mockTrackEvent.mockClear(); - mockAddTransaction.mockClear(); + Engine.context.TransactionController.addTransaction.mockClear(); }); beforeEach(() => { @@ -395,16 +395,19 @@ describe('SendTransaction View', () => { expect(screen.toJSON()).toMatchSnapshot(); }); - it('calls addTransaction for native coin when clicking on send button', async () => { + it('calls TransactionController.addTransaction for native coin when clicking on send button', async () => { render(SendTransaction); const nextButton = screen.getByRole('button', { name: 'Next' }); fireEvent.press(nextButton); - expect(mockAddTransaction).toBeCalledTimes(1); - expect(mockAddTransaction.mock.calls).toMatchInlineSnapshot(` + expect(Engine.context.TransactionController.addTransaction).toBeCalledTimes( + 1, + ); + expect(Engine.context.TransactionController.addTransaction.mock.calls) + .toMatchInlineSnapshot(` Array [ Array [ Object { - "chainId": "0x1", + "chainId": 1, "from": "0x1234", "to": "0x34256", "value": "0x2bea80d2171600", @@ -437,13 +440,16 @@ describe('SendTransaction View', () => { `); }); - it('calls addTransaction for erc20 when clicking on send button', async () => { + it('calls TransactionController.addTransaction for erc20 when clicking on send button', async () => { mockUseParamsValues = { orderId: 'test-id-2' }; render(SendTransaction); const nextButton = screen.getByRole('button', { name: 'Next' }); fireEvent.press(nextButton); - expect(mockAddTransaction).toBeCalledTimes(1); - expect(mockAddTransaction.mock.calls).toMatchInlineSnapshot(` + expect(Engine.context.TransactionController.addTransaction).toBeCalledTimes( + 1, + ); + expect(Engine.context.TransactionController.addTransaction.mock.calls) + .toMatchInlineSnapshot(` Array [ Array [ Object { @@ -463,7 +469,9 @@ describe('SendTransaction View', () => { it('calls analytics and redirects when the transaction is confirmed ', async () => { render(SendTransaction); const nextButton = screen.getByRole('button', { name: 'Next' }); - mockAddTransaction.mockImplementationOnce(() => ({ + ( + Engine.context.TransactionController.addTransaction as jest.Mock + ).mockImplementationOnce(() => ({ result: Promise.resolve('0x987654321'), })); @@ -486,10 +494,12 @@ describe('SendTransaction View', () => { expect(mockGoBack).toHaveBeenCalled(); }); - it('dispatches setFiatSellTxHash after getting hash from addTransaction', async () => { + it('dispatches setFiatSellTxHash after getting hash from TransactionController.addTransaction', async () => { render(SendTransaction); const nextButton = screen.getByRole('button', { name: 'Next' }); - mockAddTransaction.mockImplementationOnce(() => ({ + ( + Engine.context.TransactionController.addTransaction as jest.Mock + ).mockImplementationOnce(() => ({ result: Promise.resolve('0x987654321'), })); @@ -513,7 +523,9 @@ describe('SendTransaction View', () => { it('calls analytics when the transaction is rejected', async () => { render(SendTransaction); const nextButton = screen.getByRole('button', { name: 'Next' }); - mockAddTransaction.mockImplementationOnce(() => ({ + ( + Engine.context.TransactionController.addTransaction as jest.Mock + ).mockImplementationOnce(() => ({ result: Promise.reject(new Error('Transaction rejected')), })); diff --git a/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.tsx b/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.tsx index 7db84663a0e..75a0be4451d 100644 --- a/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.tsx +++ b/app/components/UI/Ramp/Views/SendTransaction/SendTransaction.tsx @@ -5,6 +5,7 @@ import { useNavigation } from '@react-navigation/native'; import { BN } from 'ethereumjs-util'; import { SellOrder } from '@consensys/on-ramp-sdk/dist/API'; import { Transaction, WalletDevice } from '@metamask/transaction-controller'; +import Engine from '../../../../../core/Engine'; import Row from '../../components/Row'; import ScreenLayout from '../../components/ScreenLayout'; @@ -47,13 +48,11 @@ import { } from '../../../../../util/number'; import { strings } from '../../../../../../locales/i18n'; import { useStyles } from '../../../../../component-library/hooks'; -import { addTransaction } from '../../../../../util/transaction-controller'; import { NATIVE_ADDRESS } from '../../../../../constants/on-ramp'; import { safeToChecksumAddress } from '../../../../../util/address'; import { generateTransferData } from '../../../../../util/transactions'; import useAnalytics from '../../hooks/useAnalytics'; -import { toHex } from '@metamask/controller-utils'; interface SendTransactionParams { orderId?: string; @@ -111,6 +110,8 @@ function SendTransaction() { }, [trackEvent, transactionAnalyticsPayload]); const handleSend = useCallback(async () => { + const { TransactionController: TxController } = Engine.context; + let transactionParams: Transaction; const amount = addHexPrefix( new BN( @@ -125,7 +126,7 @@ function SendTransaction() { from: safeToChecksumAddress(orderData.walletAddress) as string, to: safeToChecksumAddress(orderData.depositWallet), value: amount, - chainId: toHex(orderData.cryptoCurrency.network.chainId), + chainId: orderData.cryptoCurrency.network.chainId, }; } else { transactionParams = { @@ -144,7 +145,7 @@ function SendTransaction() { 'OFFRAMP_SEND_TRANSACTION_INVOKED', transactionAnalyticsPayload, ); - const response = await addTransaction(transactionParams, { + const response = await TxController.addTransaction(transactionParams, { deviceConfirmedOn: WalletDevice.MM_MOBILE, }); const hash = await response.result; diff --git a/app/components/UI/Ramp/Views/SendTransaction/__snapshots__/SendTransaction.test.tsx.snap b/app/components/UI/Ramp/Views/SendTransaction/__snapshots__/SendTransaction.test.tsx.snap index 0b439fe7ec4..3ac07384d87 100644 --- a/app/components/UI/Ramp/Views/SendTransaction/__snapshots__/SendTransaction.test.tsx.snap +++ b/app/components/UI/Ramp/Views/SendTransaction/__snapshots__/SendTransaction.test.tsx.snap @@ -782,7 +782,7 @@ exports[`SendTransaction View renders correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 16, "fontWeight": "500", @@ -1509,7 +1509,7 @@ exports[`SendTransaction View renders correctly for custom action payment method accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 16, "fontWeight": "500", @@ -2320,7 +2320,7 @@ exports[`SendTransaction View renders correctly for token 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 16, "fontWeight": "500", diff --git a/app/components/UI/Ramp/Views/Settings/__snapshots__/AddActivationKey.test.tsx.snap b/app/components/UI/Ramp/Views/Settings/__snapshots__/AddActivationKey.test.tsx.snap index 709604fac45..195d08469bc 100644 --- a/app/components/UI/Ramp/Views/Settings/__snapshots__/AddActivationKey.test.tsx.snap +++ b/app/components/UI/Ramp/Views/Settings/__snapshots__/AddActivationKey.test.tsx.snap @@ -548,7 +548,7 @@ exports[`AddActivationKey renders correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/UI/Ramp/components/InfoAlert.tsx b/app/components/UI/Ramp/components/InfoAlert.tsx index fa3a7626f6b..22e6e139758 100644 --- a/app/components/UI/Ramp/components/InfoAlert.tsx +++ b/app/components/UI/Ramp/components/InfoAlert.tsx @@ -51,7 +51,6 @@ interface Props { dismissButtonText?: string; providerWebsite?: string; providerPrivacyPolicy?: string; - providerTermsOfService?: string; providerSupport?: string; dismiss?: () => any; } @@ -65,7 +64,6 @@ const InfoAlert: React.FC = ({ dismiss, providerWebsite, providerPrivacyPolicy, - providerTermsOfService, providerSupport, }: Props) => { const { colors, themeAppearance } = useTheme(); @@ -96,18 +94,6 @@ const InfoAlert: React.FC = ({ [trackEvent], ); - const handleTermsOfServiceLinkPress = useCallback( - (url: string) => { - Linking.openURL(url); - trackEvent('ONRAMP_EXTERNAL_LINK_CLICKED', { - location: 'Quotes Screen', - text: 'Provider Terms of Service', - url_domain: url, - }); - }, - [trackEvent], - ); - const handleProviderSupportLinkPress = useCallback( (url: string) => { Linking.openURL(url); @@ -183,17 +169,6 @@ const InfoAlert: React.FC = ({ )} - {Boolean(providerTermsOfService) && ( - - handleTermsOfServiceLinkPress(providerTermsOfService as string) - } - > - - {strings('fiat_on_ramp_aggregator.terms_of_service')} - - - )} {Boolean(providerSupport) && ( diff --git a/app/components/UI/Ramp/components/OrderListItem/__snapshots__/OrderListItem.test.tsx.snap b/app/components/UI/Ramp/components/OrderListItem/__snapshots__/OrderListItem.test.tsx.snap index 4bb3eafbe12..23213dca0f2 100644 --- a/app/components/UI/Ramp/components/OrderListItem/__snapshots__/OrderListItem.test.tsx.snap +++ b/app/components/UI/Ramp/components/OrderListItem/__snapshots__/OrderListItem.test.tsx.snap @@ -161,7 +161,7 @@ exports[`OrderListItem should render correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#1C8234", + "color": "#28A745", "fontFamily": "Euclid Circular B", "fontSize": 12, "fontWeight": "700", diff --git a/app/components/UI/Ramp/hooks/useBalance.ts b/app/components/UI/Ramp/hooks/useBalance.ts index 66a341c9f08..e06c2f6d8cc 100644 --- a/app/components/UI/Ramp/hooks/useBalance.ts +++ b/app/components/UI/Ramp/hooks/useBalance.ts @@ -1,7 +1,7 @@ import { hexToBN } from '@metamask/controller-utils'; import { useSelector } from 'react-redux'; import { NATIVE_ADDRESS } from '../../../../constants/on-ramp'; -import { selectAccountsByChainId } from '../../../../selectors/accountTrackerController'; +import { selectAccounts } from '../../../../selectors/accountTrackerController'; import { selectConversionRate, selectCurrentCurrency, @@ -9,13 +9,11 @@ import { import { selectSelectedAddress } from '../../../../selectors/preferencesController'; import { selectContractBalances } from '../../../../selectors/tokenBalancesController'; import { selectContractExchangeRates } from '../../../../selectors/tokenRatesController'; -import { selectChainId } from '../../../../selectors/networkController'; import { safeToChecksumAddress } from '../../../../util/address'; import { balanceToFiat, renderFromTokenMinimalUnit, renderFromWei, - toHexadecimal, weiToFiat, } from '../../../../util/number'; @@ -26,8 +24,7 @@ interface Asset { export default function useBalance(asset?: Asset) { const assetAddress = safeToChecksumAddress(asset?.address); - const accountsByChainId = useSelector(selectAccountsByChainId); - const chainId = useSelector(selectChainId); + const accounts = useSelector(selectAccounts); const selectedAddress = useSelector(selectSelectedAddress); const conversionRate = useSelector(selectConversionRate); const currentCurrency = useSelector(selectCurrentCurrency); @@ -40,13 +37,8 @@ export default function useBalance(asset?: Asset) { let balance, balanceFiat, balanceBN; if (assetAddress === NATIVE_ADDRESS) { - balance = renderFromWei( - accountsByChainId[toHexadecimal(chainId)][selectedAddress]?.balance, - ); - - balanceBN = hexToBN( - accountsByChainId[toHexadecimal(chainId)][selectedAddress]?.balance, - ); + balance = renderFromWei(accounts[selectedAddress]?.balance); + balanceBN = hexToBN(accounts[selectedAddress].balance); balanceFiat = weiToFiat(balanceBN, conversionRate, currentCurrency); } else { const exchangeRate = diff --git a/app/components/UI/Ramp/hooks/useHandleSuccessfulOrder.ts b/app/components/UI/Ramp/hooks/useHandleSuccessfulOrder.ts index 07fe2fa35da..9bc36ef7222 100644 --- a/app/components/UI/Ramp/hooks/useHandleSuccessfulOrder.ts +++ b/app/components/UI/Ramp/hooks/useHandleSuccessfulOrder.ts @@ -14,10 +14,9 @@ import useThunkDispatch from '../../../hooks/useThunkDispatch'; import { useRampSDK } from '../sdk'; import { getNotificationDetails, stateHasOrder } from '../utils'; import useAnalytics from './useAnalytics'; -import { hexToBN, toHexadecimal } from '../../../../util/number'; -import { selectAccountsByChainId } from '../../../../selectors/accountTrackerController'; +import { hexToBN } from '../../../../util/number'; +import { selectAccounts } from '../../../../selectors/accountTrackerController'; import Routes from '../../../../constants/navigation/Routes'; -import { selectChainId } from '../../../../selectors/networkController'; function useHandleSuccessfulOrder() { const { selectedChainId, selectedAddress } = useRampSDK(); @@ -25,8 +24,7 @@ function useHandleSuccessfulOrder() { const dispatch = useDispatch(); const dispatchThunk = useThunkDispatch(); const trackEvent = useAnalytics(); - const accountsByChainId = useSelector(selectAccountsByChainId); - const chainIdFromProvider = useSelector(selectChainId); + const accounts = useSelector(selectAccounts); const addTokenToTokensController = useCallback( async (token: CryptoCurrency) => { @@ -110,16 +108,8 @@ function useHandleSuccessfulOrder() { provider_onramp: (order?.data as Order)?.provider?.name, chain_id_destination: selectedChainId, has_zero_currency_destination_balance: false, - has_zero_native_balance: accountsByChainId[ - toHexadecimal(chainIdFromProvider) - ][selectedAddress]?.balance - ? ( - hexToBN( - accountsByChainId[toHexadecimal(chainIdFromProvider)][ - selectedAddress - ].balance, - ) as any - )?.isZero?.() + has_zero_native_balance: accounts[selectedAddress]?.balance + ? (hexToBN(accounts[selectedAddress].balance) as any)?.isZero?.() : undefined, currency_source: (order?.data as Order)?.fiatCurrency.symbol, currency_destination: (order?.data as Order)?.cryptoCurrency.symbol, @@ -128,8 +118,7 @@ function useHandleSuccessfulOrder() { }); }, [ - chainIdFromProvider, - accountsByChainId, + accounts, addTokenToTokensController, dispatchThunk, handleDispatchUserWalletProtection, diff --git a/app/components/UI/Ramp/routes/index.tsx b/app/components/UI/Ramp/routes/index.tsx deleted file mode 100644 index 911a0d44164..00000000000 --- a/app/components/UI/Ramp/routes/index.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import React from 'react'; -import { createStackNavigator } from '@react-navigation/stack'; -import Regions from '../Views/Regions'; -import Quotes from '../Views/Quotes'; -import PaymentMethods from '../Views/PaymentMethods'; -import NetworkSwitcher from '../Views/NetworkSwitcher'; -import GetStarted from '../Views/GetStarted'; -import CheckoutWebView from '../Views/Checkout'; -import BuildQuote from '../Views/BuildQuote'; -import { RampType } from '../types'; -import { RampSDKProvider } from '../sdk'; -import Routes from '../../../../constants/navigation/Routes'; - -const Stack = createStackNavigator(); - -const RampRoutes = ({ rampType }: { rampType: RampType }) => ( - - - - - - - - - - - - - - -); - -export default RampRoutes; diff --git a/app/components/UI/Ramp/types/index.ts b/app/components/UI/Ramp/types/index.ts index d98a7a6d817..45c0c4902f0 100644 --- a/app/components/UI/Ramp/types/index.ts +++ b/app/components/UI/Ramp/types/index.ts @@ -7,7 +7,6 @@ export enum PROVIDER_LINKS { HOMEPAGE = 'Homepage', PRIVACY_POLICY = 'Privacy Policy', SUPPORT = 'Support', - TOS = 'Terms of Service', } export interface QuickAmount { diff --git a/app/components/UI/Ramp/utils/index.test.ts b/app/components/UI/Ramp/utils/index.test.ts index 6fac8ed177e..a77268f1eec 100644 --- a/app/components/UI/Ramp/utils/index.test.ts +++ b/app/components/UI/Ramp/utils/index.test.ts @@ -137,48 +137,6 @@ describe('isNetworkBuySupported', () => { ]), ).toBe(false); }); - - it('should return true if network is supported when chainId is on hexadecimal format', () => { - expect( - isNetworkRampSupported('0x1', [ - { - active: true, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(true); - }); - - it('should return false if network is not supported when chainId is on hexadecimal format', () => { - expect( - isNetworkRampSupported('0x1', [ - { - active: false, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(false); - }); - - it('should return false if network is not found when chainId is on hexadecimal format', () => { - expect( - isNetworkRampSupported('0x22', [ - { - active: true, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(false); - }); }); describe('isNetworkBuyNativeTokenSupported', () => { @@ -237,62 +195,6 @@ describe('isNetworkBuyNativeTokenSupported', () => { ]), ).toBe(false); }); - - it('should return true if network is supported and native token is supported when chainId is on hexadecimal format', () => { - expect( - isNetworkRampNativeTokenSupported('0x1', [ - { - active: true, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(true); - }); - - it('should return false if network is not supported when chainId is on hexadecimal format', () => { - expect( - isNetworkRampNativeTokenSupported('0x1', [ - { - active: false, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(false); - }); - - it('should return false if network is not found when chainId is on hexadecimal format', () => { - expect( - isNetworkRampNativeTokenSupported('0x22', [ - { - active: true, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: true, - shortName: 'Ethereum', - }, - ]), - ).toBe(false); - }); - - it('should return false if network is supported but native token is not supported when chainId is on hexadecimal format', () => { - expect( - isNetworkRampNativeTokenSupported('0x1', [ - { - active: true, - chainId: 1, - chainName: 'Ethereum Mainnet', - nativeTokenSupported: false, - shortName: 'Ethereum', - }, - ]), - ).toBe(false); - }); }); describe('getOrderAmount', () => { diff --git a/app/components/UI/Ramp/utils/index.ts b/app/components/UI/Ramp/utils/index.ts index 59faa946016..ec45cd7730e 100644 --- a/app/components/UI/Ramp/utils/index.ts +++ b/app/components/UI/Ramp/utils/index.ts @@ -19,7 +19,6 @@ import { getOrders, FiatOrder } from '../../../../reducers/fiatOrders'; import { RootState } from '../../../../reducers'; import { FIAT_ORDER_STATES } from '../../../../constants/on-ramp'; import { strings } from '../../../../../locales/i18n'; -import { getDecimalChainId } from '../../../../util/networks'; const isOverAnHour = (minutes: number) => minutes > 59; @@ -129,9 +128,8 @@ export function isNetworkRampSupported( networks: AggregatorNetwork[], ) { return ( - networks.find( - (network) => String(network.chainId) === getDecimalChainId(chainId), - )?.active ?? false + networks.find((network) => String(network.chainId) === chainId)?.active ?? + false ); } @@ -140,7 +138,7 @@ export function isNetworkRampNativeTokenSupported( networks: AggregatorNetwork[], ) { const network = networks.find( - (_network) => String(_network.chainId) === getDecimalChainId(chainId), + (_network) => String(_network.chainId) === chainId, ); return (network?.active && network.nativeTokenSupported) ?? false; } diff --git a/app/components/UI/ReceiveRequest/index.js b/app/components/UI/ReceiveRequest/index.js index f77bdc75ac3..50174adf03f 100644 --- a/app/components/UI/ReceiveRequest/index.js +++ b/app/components/UI/ReceiveRequest/index.js @@ -45,7 +45,6 @@ import { isNetworkRampSupported } from '../Ramp/utils'; import { selectSelectedAddress } from '../../../selectors/preferencesController'; import { getRampNetworks } from '../../../reducers/fiatOrders'; import { RequestPaymentModalSelectorsIDs } from '../../../../e2e/selectors/Modals/RequestPaymentModal.selectors'; -import { getDecimalChainId } from '../../../util/networks'; const createStyles = (theme) => StyleSheet.create({ @@ -200,7 +199,7 @@ class ReceiveRequest extends PureComponent { { text: 'Buy Native Token', location: 'Receive Modal', - chain_id_destination: getDecimalChainId(this.props.chainId), + chain_id_destination: this.props.chainId, }, ); }); diff --git a/app/components/UI/SDKFeedback/index.tsx b/app/components/UI/SDKFeedback/index.tsx index eec9e5c2118..12b2f1ae862 100644 --- a/app/components/UI/SDKFeedback/index.tsx +++ b/app/components/UI/SDKFeedback/index.tsx @@ -1,5 +1,5 @@ -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; -import type { ThemeTypography } from '@metamask/design-tokens/dist/types/js/typography'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; +import { ThemeTypography } from '@metamask/design-tokens/dist/js/typography'; import Icon, { IconName, IconSize, diff --git a/app/components/UI/SDKLoading/index.tsx b/app/components/UI/SDKLoading/index.tsx index 0d8f92019c1..cb965e460a2 100644 --- a/app/components/UI/SDKLoading/index.tsx +++ b/app/components/UI/SDKLoading/index.tsx @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports, import/no-commonjs */ -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; import LottieView from 'lottie-react-native'; import React from 'react'; import { StyleSheet, View } from 'react-native'; diff --git a/app/components/UI/SearchTokenAutocomplete/index.tsx b/app/components/UI/SearchTokenAutocomplete/index.tsx index d502e9a454b..782f63b0f2b 100644 --- a/app/components/UI/SearchTokenAutocomplete/index.tsx +++ b/app/components/UI/SearchTokenAutocomplete/index.tsx @@ -22,7 +22,6 @@ import NotificationManager from '../../../core/NotificationManager'; import { useTheme } from '../../../util/theme'; import { selectChainId } from '../../../selectors/networkController'; import { selectUseTokenDetection } from '../../../selectors/preferencesController'; -import { getDecimalChainId } from '../../../util/networks'; const createStyles = (colors: any) => StyleSheet.create({ @@ -78,7 +77,7 @@ const SearchTokenAutocomplete = ({ navigation }: Props) => { return { token_address: address, token_symbol: symbol, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, source: 'Add token dropdown', }; } catch (error) { diff --git a/app/components/UI/SettingsDrawer/index.js b/app/components/UI/SettingsDrawer/index.js index d1d2c241ebe..ccd5d1c45fc 100644 --- a/app/components/UI/SettingsDrawer/index.js +++ b/app/components/UI/SettingsDrawer/index.js @@ -76,7 +76,7 @@ const propTypes = { /** * Title color */ - titleColor: PropTypes.string, + titleColor: TextColor, }; const defaultProps = { diff --git a/app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/__snapshots__/index.test.tsx.snap b/app/components/UI/SignatureRequest/ExpandedMessage/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/__snapshots__/index.test.tsx.snap rename to app/components/UI/SignatureRequest/ExpandedMessage/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.js b/app/components/UI/SignatureRequest/ExpandedMessage/index.js similarity index 90% rename from app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.js rename to app/components/UI/SignatureRequest/ExpandedMessage/index.js index 89a56a07561..cce7cc87582 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.js +++ b/app/components/UI/SignatureRequest/ExpandedMessage/index.js @@ -8,13 +8,13 @@ import { ScrollView, TouchableWithoutFeedback, } from 'react-native'; -import { fontStyles, baseStyles } from '../../../../../../styles/common'; -import WebsiteIcon from '../../../../../UI/WebsiteIcon'; +import { fontStyles, baseStyles } from '../../../../styles/common'; +import WebsiteIcon from '../../WebsiteIcon'; import Ionicons from 'react-native-vector-icons/Ionicons'; -import { strings } from '../../../../../../../locales/i18n'; -import Device from '../../../../../../util/device'; -import { getHost } from '../../../../../../util/browser'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; +import { strings } from '../../../../../locales/i18n'; +import Device from '../../../../util/device'; +import { getHost } from '../../../../util/browser'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.test.tsx b/app/components/UI/SignatureRequest/ExpandedMessage/index.test.tsx similarity index 93% rename from app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.test.tsx rename to app/components/UI/SignatureRequest/ExpandedMessage/index.test.tsx index e6b66c1e6a7..39bd162b595 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/ExpandedMessage/index.test.tsx +++ b/app/components/UI/SignatureRequest/ExpandedMessage/index.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { shallow } from 'enzyme'; -import ExpandedMessage from '.'; +import ExpandedMessage from './'; const renderMessageMock = jest.fn(); const toggleExpandedMessageMock = jest.fn(); diff --git a/app/components/Views/confirmations/components/SignatureRequest/Root/Root.test.tsx b/app/components/UI/SignatureRequest/Root/Root.test.tsx similarity index 90% rename from app/components/Views/confirmations/components/SignatureRequest/Root/Root.test.tsx rename to app/components/UI/SignatureRequest/Root/Root.test.tsx index db0d02372b8..6ce0905f6cb 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/Root/Root.test.tsx +++ b/app/components/UI/SignatureRequest/Root/Root.test.tsx @@ -2,12 +2,12 @@ import React from 'react'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; import { render } from '@testing-library/react-native'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; import Root from '.'; -import { ApprovalTypes } from '../../../../../../core/RPCMethods/RPCMethodMiddleware'; +import { ApprovalTypes } from '../../../../core/RPCMethods/RPCMethodMiddleware'; import { shallow } from 'enzyme'; jest.mock('react-native-keyboard-aware-scroll-view', () => { @@ -15,7 +15,7 @@ jest.mock('react-native-keyboard-aware-scroll-view', () => { return { KeyboardAwareScrollView }; }); -jest.mock('../../../../../../core/Engine', () => ({ +jest.mock('../../../../core/Engine', () => ({ init: () => ({}), context: { KeyringController: { @@ -90,7 +90,7 @@ const initialState = { }, NetworkController: { providerConfig: { - chainId: '0x1', + chainId: '1', }, }, }, diff --git a/app/components/Views/confirmations/components/SignatureRequest/Root/Root.tsx b/app/components/UI/SignatureRequest/Root/Root.tsx similarity index 89% rename from app/components/Views/confirmations/components/SignatureRequest/Root/Root.tsx rename to app/components/UI/SignatureRequest/Root/Root.tsx index d66e4f70d46..113370b208a 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/Root/Root.tsx +++ b/app/components/UI/SignatureRequest/Root/Root.tsx @@ -2,14 +2,14 @@ import Modal from 'react-native-modal'; import React, { useEffect, useState } from 'react'; import { StyleSheet } from 'react-native'; import { useNavigation } from '@react-navigation/native'; -import setSignatureRequestSecurityAlertResponse from '../../../../../../actions/signatureRequest'; -import { store } from '../../../../../../store'; -import { useTheme } from '../../../../../../util/theme'; -import MessageSign from '../../MessageSign'; -import PersonalSign from '../../PersonalSign'; -import TypedSign from '../../TypedSign'; +import setSignatureRequestSecurityAlertResponse from '../../../../actions/signatureRequest'; +import { store } from '../../../../store'; +import { useTheme } from '../../../../util/theme'; +import MessageSign from '../../../UI/MessageSign'; +import PersonalSign from '../../../UI/PersonalSign'; +import TypedSign from '../../../UI/TypedSign'; import { MessageParams } from '../types'; -import { ApprovalTypes } from '../../../../../../core/RPCMethods/RPCMethodMiddleware'; +import { ApprovalTypes } from '../../../../core/RPCMethods/RPCMethodMiddleware'; import { useSelector } from 'react-redux'; interface RootProps { diff --git a/app/components/Views/confirmations/components/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap b/app/components/UI/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap similarity index 94% rename from app/components/Views/confirmations/components/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap rename to app/components/UI/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap index 777e22673ee..9cbbe048078 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap +++ b/app/components/UI/SignatureRequest/Root/__snapshots__/Root.test.tsx.snap @@ -66,10 +66,8 @@ exports[`Root should render correctly 1`] = ` "error": Object { "alternative": "#B92534", "default": "#D73847", - "defaultHover": "#CD4250", - "defaultPressed": "#C63441", "disabled": "#D7384780", - "inverse": "#FFFFFF", + "inverse": "#FCFCFC", "muted": "#D7384719", "shadow": "#D7384766", }, @@ -86,7 +84,7 @@ exports[`Root should render correctly 1`] = ` "alternative": "#0260A4", "default": "#0376C9", "disabled": "#0376C980", - "inverse": "#FFFFFF", + "inverse": "#FCFCFC", "muted": "#0376C919", }, "networks": Object { @@ -111,15 +109,13 @@ exports[`Root should render correctly 1`] = ` "primary": Object { "alternative": "#0260A4", "default": "#0376C9", - "defaultHover": "#0379CE", - "defaultPressed": "#036DB9", "disabled": "#0376C980", - "inverse": "#FFFFFF", + "inverse": "#FCFCFC", "muted": "#0376C919", "shadow": "#0376C933", }, "secondary": Object { - "alternative": "#BF5208", + "alternative": "#C65507", "default": "#F66A0A", "disabled": "#F66A0A80", "inverse": "#FCFCFC", @@ -129,13 +125,11 @@ exports[`Root should render correctly 1`] = ` "default": "#0000001A", }, "success": Object { - "alternative": "#1C8234", - "default": "#1C8234", - "defaultHover": "#208838", - "defaultPressed": "#1B7431", + "alternative": "#1E7E34", + "default": "#28A745", "disabled": "#28A74580", - "inverse": "#FFFFFF", - "muted": "#1C823419", + "inverse": "#FCFCFC", + "muted": "#28A74519", }, "text": Object { "alternative": "#535A61", @@ -144,12 +138,10 @@ exports[`Root should render correctly 1`] = ` }, "warning": Object { "alternative": "#FFC70A", - "default": "#BF5208", - "defaultHover": "#C2540A", - "defaultPressed": "#A24507", + "default": "#F66A0A", "disabled": "#FFD33D80", - "inverse": "#FFFFFF", - "muted": "#BF520819", + "inverse": "#FCFCFC", + "muted": "#FFD33D19", }, }, "shadows": Object { diff --git a/app/components/Views/confirmations/components/SignatureRequest/Root/index.ts b/app/components/UI/SignatureRequest/Root/index.ts similarity index 100% rename from app/components/Views/confirmations/components/SignatureRequest/Root/index.ts rename to app/components/UI/SignatureRequest/Root/index.ts diff --git a/app/components/Views/confirmations/components/SignatureRequest/__snapshots__/index.test.tsx.snap b/app/components/UI/SignatureRequest/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/SignatureRequest/__snapshots__/index.test.tsx.snap rename to app/components/UI/SignatureRequest/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/SignatureRequest/index.js b/app/components/UI/SignatureRequest/index.js similarity index 85% rename from app/components/Views/confirmations/components/SignatureRequest/index.js rename to app/components/UI/SignatureRequest/index.js index 27accc98ff6..babd4738610 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/index.js +++ b/app/components/UI/SignatureRequest/index.js @@ -3,27 +3,26 @@ import React, { PureComponent } from 'react'; import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import { connect } from 'react-redux'; -import { SigningModalSelectorsIDs } from '../../../../../../e2e/selectors/Modals/SigningModal.selectors'; -import { strings } from '../../../../../../locales/i18n'; -import ExtendedKeyringTypes from '../../../../../constants/keyringTypes'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import Analytics from '../../../../../core/Analytics/Analytics'; -import { selectProviderType } from '../../../../../selectors/networkController'; -import { fontStyles } from '../../../../../styles/common'; -import { isHardwareAccount } from '../../../../../util/address'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { getHost } from '../../../../../util/browser'; -import { getAnalyticsParams } from '../../../../../util/confirmation/signatureUtils'; -import Device from '../../../../../util/device'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import WarningMessage from '../../SendFlow/WarningMessage'; -import AccountInfoCard from '../../../../UI/AccountInfoCard'; -import ActionView, { ConfirmButtonState } from '../../../../UI/ActionView'; +import { SigningModalSelectorsIDs } from '../../../../e2e/selectors/Modals/SigningModal.selectors'; +import { strings } from '../../../../locales/i18n'; +import ExtendedKeyringTypes from '../../../constants/keyringTypes'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import Analytics from '../../../core/Analytics/Analytics'; +import { selectProviderType } from '../../../selectors/networkController'; +import { fontStyles } from '../../../styles/common'; +import { isHardwareAccount } from '../../../util/address'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import { getHost } from '../../../util/browser'; +import { getAnalyticsParams } from '../../../util/confirmation/signatureUtils'; +import Device from '../../../util/device'; +import { ThemeContext, mockTheme } from '../../../util/theme'; +import WarningMessage from '../../Views/SendFlow/WarningMessage'; +import AccountInfoCard from '../AccountInfoCard'; +import ActionView from '../ActionView'; import BlockaidBanner from '../BlockaidBanner/BlockaidBanner'; -import QRSigningDetails from '../../../../UI/QRHardware/QRSigningDetails'; -import withQRHardwareAwareness from '../../../../UI/QRHardware/withQRHardwareAwareness'; -import WebsiteIcon from '../../../../UI/WebsiteIcon'; -import { ResultType } from '../BlockaidBanner/BlockaidBanner.types'; +import QRSigningDetails from '../QRHardware/QRSigningDetails'; +import withQRHardwareAwareness from '../QRHardware/withQRHardwareAwareness'; +import WebsiteIcon from '../WebsiteIcon'; const createStyles = (colors) => StyleSheet.create({ @@ -335,14 +334,6 @@ class SignatureRequest extends PureComponent { expandedHeight = styles.expandedHeight1; } } - - let confirmButtonState = ConfirmButtonState.Normal; - if (securityAlertResponse?.result_type === ResultType.Malicious) { - confirmButtonState = ConfirmButtonState.Error; - } else if (securityAlertResponse?.result_type === ResultType.Warning) { - confirmButtonState = ConfirmButtonState.Warning; - } - return ( diff --git a/app/components/Views/confirmations/components/SignatureRequest/index.test.tsx b/app/components/UI/SignatureRequest/index.test.tsx similarity index 83% rename from app/components/Views/confirmations/components/SignatureRequest/index.test.tsx rename to app/components/UI/SignatureRequest/index.test.tsx index 349b1df2a97..bcebf88c8ac 100644 --- a/app/components/Views/confirmations/components/SignatureRequest/index.test.tsx +++ b/app/components/UI/SignatureRequest/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { shallow } from 'enzyme'; -import SignatureRequest from '.'; +import SignatureRequest from './'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/SignatureRequest/types.ts b/app/components/UI/SignatureRequest/types.ts similarity index 100% rename from app/components/Views/confirmations/components/SignatureRequest/types.ts rename to app/components/UI/SignatureRequest/types.ts diff --git a/app/components/UI/SliderButton/__snapshots__/index.test.tsx.snap b/app/components/UI/SliderButton/__snapshots__/index.test.tsx.snap index 53a8784e594..91d696769be 100644 --- a/app/components/UI/SliderButton/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/SliderButton/__snapshots__/index.test.tsx.snap @@ -91,7 +91,7 @@ exports[`SliderButton should render correctly 1`] = ` { + async ( + TransactionController, + newSwapsTransactions, + approvalTransactionMetaId, + ) => { if (!selectedQuote) { return; } try { resetTransaction(); - const { transactionMeta } = await addTransaction( + const { transactionMeta } = await TransactionController.addTransaction( { ...selectedQuote.trade, ...getTransactionPropertiesFromGasEstimates( @@ -968,7 +970,7 @@ function SwapsQuotesView({ ) => { try { resetTransaction(); - const { transactionMeta } = await addTransaction( + const { transactionMeta } = await TransactionController.addTransaction( { ...approvalTransaction, ...getTransactionPropertiesFromGasEstimates( @@ -1125,7 +1127,7 @@ function SwapsQuotesView({ ), custom_spend_limit_set: originalAmount !== currentAmount, custom_spend_limit_amount: currentAmount, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; Analytics.trackEventWithParameters( MetaMetricsEvents.EDIT_SPEND_LIMIT_OPENED, @@ -1180,7 +1182,7 @@ function SwapsQuotesView({ ), network_fees_ETH: renderFromWei(toWei(selectedQuoteValue.ethFee)), available_quotes: allQuotes.length, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; Analytics.trackEventWithParameters(MetaMetricsEvents.QUOTES_RECEIVED, {}); Analytics.trackEventWithParameters( @@ -1230,7 +1232,7 @@ function SwapsQuotesView({ ), network_fees_ETH: renderFromWei(toWei(selectedQuoteValue.ethFee)), available_quotes: allQuotes.length, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; Analytics.trackEventWithParameters( MetaMetricsEvents.ALL_AVAILABLE_QUOTES_OPENED, @@ -1269,7 +1271,7 @@ function SwapsQuotesView({ request_type: hasEnoughTokenBalance ? 'Order' : 'Quote', slippage, custom_slippage: slippage !== AppConstants.SWAPS.DEFAULT_SLIPPAGE, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; if (error?.key === swapsUtils.SwapsError.QUOTES_EXPIRED_ERROR) { InteractionManager.runAfterInteractions(() => { @@ -1572,7 +1574,7 @@ function SwapsQuotesView({ token_to: destinationToken.symbol, request_type: hasEnoughTokenBalance ? 'Order' : 'Quote', custom_slippage: slippage !== AppConstants.SWAPS.DEFAULT_SLIPPAGE, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; navigation.setParams({ requestedTrade: data }); navigation.setParams({ selectedQuote: undefined }); diff --git a/app/components/UI/Swaps/components/ApprovalTransactionEditionModal.js b/app/components/UI/Swaps/components/ApprovalTransactionEditionModal.js index afcd29cb0f0..0fb7ffd6912 100644 --- a/app/components/UI/Swaps/components/ApprovalTransactionEditionModal.js +++ b/app/components/UI/Swaps/components/ApprovalTransactionEditionModal.js @@ -6,7 +6,7 @@ import Modal from 'react-native-modal'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { swapsUtils } from '@metamask/swaps-controller'; -import EditPermission from '../../../Views/confirmations/components/ApproveTransactionReview/EditPermission'; +import EditPermission from '../../ApproveTransactionReview/EditPermission'; import { fromTokenMinimalUnitString, hexToBN } from '../../../../util/number'; import { decodeApproveData, diff --git a/app/components/UI/Swaps/components/TokenSelectModal.js b/app/components/UI/Swaps/components/TokenSelectModal.js index dbf1e204dfd..4857b049b47 100644 --- a/app/components/UI/Swaps/components/TokenSelectModal.js +++ b/app/components/UI/Swaps/components/TokenSelectModal.js @@ -60,7 +60,6 @@ import Analytics from '../../../../core/Analytics/Analytics'; import { MetaMetricsEvents } from '../../../../core/Analytics'; import { useTheme } from '../../../../util/theme'; import { SWAP_SEARCH_TOKEN } from '../../../../../wdio/screen-objects/testIDs/Screens/QuoteView.js'; -import { getDecimalChainId } from '../../../../util/networks'; const createStyles = (colors) => StyleSheet.create({ @@ -305,7 +304,7 @@ function TokenSelectModal({ InteractionManager.runAfterInteractions(() => { Analytics.trackEventWithParameters( MetaMetricsEvents.CUSTOM_TOKEN_IMPORTED, - { address, symbol, chain_id: getDecimalChainId(chainId) }, + { address, symbol, chain_id: chainId }, true, ); }); diff --git a/app/components/UI/Swaps/index.js b/app/components/UI/Swaps/index.js index 465a0ab44ea..9aac6887de1 100644 --- a/app/components/UI/Swaps/index.js +++ b/app/components/UI/Swaps/index.js @@ -87,7 +87,6 @@ import { SWAP_DEST_TOKEN, SWAP_MAX_SLIPPAGE, } from '../../../../wdio/screen-objects/testIDs/Screens/QuoteView.js'; -import { getDecimalChainId } from '../../../util/networks'; const createStyles = (colors) => StyleSheet.create({ @@ -284,7 +283,7 @@ function SwapsAmountView({ activeCurrency: swapsTokens?.find((token) => toLowerCaseEquals(token.address, initialSource), )?.symbol, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }; Analytics.trackEventWithParameters( MetaMetricsEvents.SWAPS_OPENED, diff --git a/app/components/UI/Swaps/utils/useBlockExplorer.js b/app/components/UI/Swaps/utils/useBlockExplorer.js index 190750b7b7c..246cee18285 100644 --- a/app/components/UI/Swaps/utils/useBlockExplorer.js +++ b/app/components/UI/Swaps/utils/useBlockExplorer.js @@ -21,7 +21,7 @@ function useBlockExplorer(providerConfig, networkConfigurations) { if (providerConfig.type === RPC) { try { const blockExplorer = findBlockExplorerForRpc( - providerConfig.rpcUrl, + providerConfig.rpcTarget, networkConfigurations, ); if (!blockExplorer) { diff --git a/app/components/UI/Tabs/__snapshots__/index.test.tsx.snap b/app/components/UI/Tabs/__snapshots__/index.test.tsx.snap index 4659d03ffa0..98b2e74640b 100644 --- a/app/components/UI/Tabs/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/Tabs/__snapshots__/index.test.tsx.snap @@ -124,7 +124,7 @@ exports[`Tabs should render correctly 1`] = ` style={ Object { "alignContent": "center", - "color": "#FFFFFF", + "color": "#FCFCFC", "fontSize": 24, "justifyContent": "center", "marginTop": 3, diff --git a/app/components/UI/Tabs/index.js b/app/components/UI/Tabs/index.js index 6f002584f8a..7c337d5cc94 100644 --- a/app/components/UI/Tabs/index.js +++ b/app/components/UI/Tabs/index.js @@ -7,6 +7,7 @@ import { ScrollView, TouchableOpacity, StyleSheet, + Platform, } from 'react-native'; import MaterialCommunityIcon from 'react-native-vector-icons/MaterialCommunityIcons'; import PropTypes from 'prop-types'; @@ -18,6 +19,7 @@ import { MetaMetricsEvents } from '../../../core/Analytics'; import AnalyticsV2 from '../../../util/analyticsV2'; import { ThemeContext, mockTheme } from '../../../util/theme'; +import generateTestId from '../../../../wdio/utils/generateTestId'; import { MULTI_TAB_ADD_BUTTON, MULTI_TAB_CLOSE_ALL_BUTTON, @@ -229,7 +231,10 @@ export default class Tabs extends PureComponent { return ( - + {strings('browser.no_tabs_title')} {strings('browser.no_tabs_desc')} @@ -282,7 +287,7 @@ export default class Tabs extends PureComponent { = ({ tokens }) => { const [tokenToRemove, setTokenToRemove] = useState(); const [isAddTokenEnabled, setIsAddTokenEnabled] = useState(true); const [refreshing, setRefreshing] = useState(false); - const [isNetworkRampSupported, isNativeTokenRampSupported] = useRampNetwork(); const actionSheet = useRef(); @@ -230,8 +229,6 @@ const Tokens: React.FC = ({ tokens }) => { // render balances according to primary currency let mainBalance, secondaryBalance; - mainBalance = TOKEN_BALANCE_LOADING; - if (primaryCurrency === 'ETH') { mainBalance = balanceValueFormatted; secondaryBalance = balanceFiat; @@ -322,7 +319,7 @@ const Tokens: React.FC = ({ tokens }) => { Analytics.trackEventWithParameters(MetaMetricsEvents.BUY_BUTTON_CLICKED, { text: 'Buy Native Token', location: 'Home Screen', - chain_id_destination: getDecimalChainId(chainId), + chain_id_destination: chainId, }); }); }; diff --git a/app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx b/app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx similarity index 81% rename from app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx rename to app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx index 82693e1f332..deda858f061 100644 --- a/app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx +++ b/app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.test.tsx @@ -1,13 +1,13 @@ import React from 'react'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; -import { TESTID_ACCORDION_CONTENT } from '../../../../../component-library/components/Accordions/Accordion/Accordion.constants'; -import { TESTID_ACCORDIONHEADER } from '../../../../../component-library/components/Accordions/Accordion/foundation/AccordionHeader/AccordionHeader.constants'; +import renderWithProvider from '../../../util/test/renderWithProvider'; +import { TESTID_ACCORDION_CONTENT } from '../../../component-library/components/Accordions/Accordion/Accordion.constants'; +import { TESTID_ACCORDIONHEADER } from '../../../component-library/components/Accordions/Accordion/foundation/AccordionHeader/AccordionHeader.constants'; import { ResultType, Reason } from '../BlockaidBanner/BlockaidBanner.types'; import TransactionBlockaidBanner from './TransactionBlockaidBanner'; -jest.mock('../../../../../util/blockaid', () => ({ +jest.mock('../../../util/blockaid', () => ({ isBlockaidFeatureEnabled: jest.fn().mockReturnValue(true), isBlockaidSupportedOnCurrentChain: jest.fn().mockReturnValue(true), })); @@ -19,7 +19,7 @@ jest.mock('react-native-gzip', () => ({ const mockState = { engine: { backgroundState: { - NetworkController: { providerConfig: { chainId: '0x1' } }, + NetworkController: { providerConfig: { chainId: '1' } }, PreferencesController: { securityAlertsEnabled: true }, }, }, diff --git a/app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.tsx b/app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.tsx similarity index 100% rename from app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.tsx rename to app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.tsx diff --git a/app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.types.ts b/app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.types.ts similarity index 100% rename from app/components/Views/confirmations/components/TransactionBlockaidBanner/TransactionBlockaidBanner.types.ts rename to app/components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner.types.ts diff --git a/app/components/Views/confirmations/components/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap b/app/components/UI/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap similarity index 98% rename from app/components/Views/confirmations/components/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap rename to app/components/UI/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap index 2df5c56e1c6..594c30b2b0f 100644 --- a/app/components/Views/confirmations/components/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap +++ b/app/components/UI/TransactionBlockaidBanner/__snapshots__/TransactionBlockaidBanner.test.tsx.snap @@ -17,8 +17,8 @@ exports[`TransactionBlockaidBanner should render correctly 1`] = ` } style={ Object { - "backgroundColor": "#BF520819", - "borderColor": "#BF5208", + "backgroundColor": "#FFD33D19", + "borderColor": "#F66A0A", "borderLeftWidth": 4, "borderRadius": 4, "flexDirection": "row", @@ -36,7 +36,7 @@ exports[`TransactionBlockaidBanner should render correctly 1`] = ` } > { const { - providerConfig: { rpcUrl, type }, + providerConfig: { rpcTarget, type }, networkConfigurations, } = this.props; let blockExplorer; if (type === RPC) { blockExplorer = - findBlockExplorerForRpc(rpcUrl, networkConfigurations) || + findBlockExplorerForRpc(rpcTarget, networkConfigurations) || NO_RPC_BLOCK_EXPLORER; } this.setState({ rpcBlockExplorer: blockExplorer }); diff --git a/app/components/UI/TransactionElement/index.js b/app/components/UI/TransactionElement/index.js index 2a2e6433a8f..6d0132d548b 100644 --- a/app/components/UI/TransactionElement/index.js +++ b/app/components/UI/TransactionElement/index.js @@ -24,10 +24,9 @@ import StatusText from '../../Base/StatusText'; import DetailsModal from '../../Base/DetailsModal'; import { isMainNet } from '../../../util/networks'; import { weiHexToGweiDec } from '@metamask/controller-utils'; -import { - WalletDevice, - isEIP1559Transaction, -} from '@metamask/transaction-controller'; +import { WalletDevice } from '@metamask/transaction-controller'; +// TODO: Update after this function has been exported from the package +import { isEIP1559Transaction } from '@metamask/transaction-controller/dist/utils'; import { ThemeContext, mockTheme } from '../../../util/theme'; import { selectChainId, diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/TransactionReviewData/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/TransactionReviewData/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.js b/app/components/UI/TransactionReview/TransactionReviewData/index.js similarity index 89% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.js rename to app/components/UI/TransactionReview/TransactionReviewData/index.js index 3abf121f4c8..d31d051b595 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.js +++ b/app/components/UI/TransactionReview/TransactionReviewData/index.js @@ -3,19 +3,19 @@ import PropTypes from 'prop-types'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import IonicIcon from 'react-native-vector-icons/Ionicons'; -import { fontStyles } from '../../../../../../styles/common'; -import { strings } from '../../../../../../../locales/i18n'; +import { fontStyles } from '../../../../styles/common'; +import { strings } from '../../../../../locales/i18n'; import { connect } from 'react-redux'; -import Device from '../../../../../../util/device'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; -import ClipboardManager from '../../../../../../core/ClipboardManager'; -import { showAlert } from '../../../../../../actions/alert'; -import GlobalAlert from '../../../../../UI/GlobalAlert'; +import Device from '../../../../util/device'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import ClipboardManager from '../../../../core/ClipboardManager'; +import { showAlert } from '../../../../actions/alert'; +import GlobalAlert from '../../../../components/UI/GlobalAlert'; import { selectConversionRate, selectCurrentCurrency, -} from '../../../../../../selectors/currencyRateController'; -import { selectContractExchangeRates } from '../../../../../../selectors/tokenRatesController'; +} from '../../../../selectors/currencyRateController'; +import { selectContractExchangeRates } from '../../../../selectors/tokenRatesController'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.test.tsx b/app/components/UI/TransactionReview/TransactionReviewData/index.test.tsx similarity index 85% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.test.tsx rename to app/components/UI/TransactionReview/TransactionReviewData/index.test.tsx index f56892d81f3..bf6416c41c9 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewData/index.test.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewData/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import TransactionReviewData from '.'; +import TransactionReviewData from './'; import configureMockStore from 'redux-mock-store'; import { shallow } from 'enzyme'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/__snapshots__/index.test.js.snap b/app/components/UI/TransactionReview/TransactionReviewDetailsCard/__snapshots__/index.test.js.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/__snapshots__/index.test.js.snap rename to app/components/UI/TransactionReview/TransactionReviewDetailsCard/__snapshots__/index.test.js.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.js b/app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.js similarity index 92% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.js rename to app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.js index a6a8701a826..333a7a80ab6 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.js +++ b/app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.js @@ -1,16 +1,16 @@ import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; -import { fontStyles } from '../../../../../../styles/common'; +import { fontStyles } from '../../../../styles/common'; import PropTypes from 'prop-types'; import IonicIcon from 'react-native-vector-icons/Ionicons'; -import { strings } from '../../../../../../../locales/i18n'; +import { strings } from '../../../../../locales/i18n'; import Feather from 'react-native-vector-icons/Feather'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; -import ConnectHeader from '../../../../../UI/ConnectHeader'; -import formatNumber from '../../../../../../util/formatNumber'; -import TransactionTypes from '../../../../../../core/TransactionTypes'; -import { renderShortAddress } from '../../../../../../util/address'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import ConnectHeader from '../../ConnectHeader'; +import formatNumber from '../../../../util/formatNumber'; +import TransactionTypes from '../../../../core/TransactionTypes'; +import { renderShortAddress } from '../../../../util/address'; const { ASSET: { ERC20 }, diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.test.js b/app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.test.js similarity index 86% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.test.js rename to app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.test.js index a18a5da4918..7b31e104323 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewDetailsCard/index.test.js +++ b/app/components/UI/TransactionReview/TransactionReviewDetailsCard/index.test.js @@ -3,7 +3,7 @@ import TransactionReviewDetailsCard from '.'; import { shallow } from 'enzyme'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/TransactionReviewEIP1559/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/TransactionReviewEIP1559/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.js b/app/components/UI/TransactionReview/TransactionReviewEIP1559/index.js similarity index 95% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.js rename to app/components/UI/TransactionReview/TransactionReviewEIP1559/index.js index 5dc7fea2078..600c8a89cb2 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.js +++ b/app/components/UI/TransactionReview/TransactionReviewEIP1559/index.js @@ -1,21 +1,21 @@ import React, { useState, useCallback } from 'react'; import { TouchableOpacity, View, StyleSheet, Linking } from 'react-native'; -import Summary from '../../../../../Base/Summary'; -import Text from '../../../../../Base/Text'; +import Summary from '../../../Base/Summary'; +import Text from '../../../Base/Text'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; -import { isMainnetByChainId, isTestNet } from '../../../../../../util/networks'; +import { isMainnetByChainId, isTestNet } from '../../../../util/networks'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; -import InfoModal from '../../../../../UI/Swaps/components/InfoModal'; -import FadeAnimationView from '../../../../../UI/FadeAnimationView'; +import InfoModal from '../../Swaps/components/InfoModal'; +import FadeAnimationView from '../../FadeAnimationView'; import SkeletonPlaceholder from 'react-native-skeleton-placeholder'; -import { strings } from '../../../../../../../locales/i18n'; -import TimeEstimateInfoModal from '../../../../../UI/TimeEstimateInfoModal'; -import useModalHandler from '../../../../../Base/hooks/useModalHandler'; -import AppConstants from '../../../../../../core/AppConstants'; -import Device from '../../../../../../util/device'; -import { useTheme } from '../../../../../../util/theme'; -import { selectChainId } from '../../../../../../selectors/networkController'; +import { strings } from '../../../../../locales/i18n'; +import TimeEstimateInfoModal from '../../TimeEstimateInfoModal'; +import useModalHandler from '../../../Base/hooks/useModalHandler'; +import AppConstants from '../../../../core/AppConstants'; +import Device from '../../../../util/device'; +import { useTheme } from '../../../../util/theme'; +import { selectChainId } from '../../../../selectors/networkController'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.test.tsx b/app/components/UI/TransactionReview/TransactionReviewEIP1559/index.test.tsx similarity index 62% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.test.tsx rename to app/components/UI/TransactionReview/TransactionReviewEIP1559/index.test.tsx index c30705d191e..3fce7a9d1c0 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559/index.test.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewEIP1559/index.test.tsx @@ -1,7 +1,7 @@ import React from 'react'; -import TransactionReviewEIP1559 from '.'; -import renderWithProvider from '../../../../../../util/test/renderWithProvider'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import TransactionReviewEIP1559 from './'; +import renderWithProvider from '../../../..//util/test/renderWithProvider'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const initialState = { engine: { diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx similarity index 90% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx index c7350a79ced..8755b0a2e0f 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.test.tsx @@ -2,9 +2,9 @@ import React from 'react'; import renderWithProvider, { renderHookWithProvider, -} from '../../../../../../util/test/renderWithProvider'; -import TransactionReviewEIP1559 from '.'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +} from '../../../../util/test/renderWithProvider'; +import TransactionReviewEIP1559 from './'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const initialState = { settings: {}, @@ -63,7 +63,6 @@ const transactionReview = { suggestedMaxFeePerGas: '', suggestedMaxPriorityFeePerGas: '', }, - gasObjectLegacy: {}, updateTransactionState: undefined, onlyGas: false, }; diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.tsx b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.tsx similarity index 93% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.tsx rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.tsx index 8105f4c44c5..ee343b56897 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/index.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/index.tsx @@ -2,23 +2,20 @@ import React, { useCallback, useEffect, useState } from 'react'; import { Linking, Platform, TouchableOpacity, View } from 'react-native'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; -import { strings } from '../../../../../../../locales/i18n'; -import { ESTIMATED_FEE_TEST_ID } from '../../../../../../../wdio/screen-objects/testIDs/Screens/TransactionSummaryScreen.testIds'; -import generateTestId from '../../../../../../../wdio/utils/generateTestId'; -import AppConstants from '../../../../../../core/AppConstants'; -import { useGasTransaction } from '../../../../../../core/GasPolling/GasPolling'; -import Device from '../../../../../../util/device'; -import { isMainnetByChainId } from '../../../../../../util/networks'; -import { - mockTheme, - useAppThemeFromContext, -} from '../../../../../../util/theme'; -import useModalHandler from '../../../../../Base/hooks/useModalHandler'; -import Summary from '../../../../../Base/Summary'; -import Text from '../../../../../Base/Text'; -import FadeAnimationView from '../../../../../UI/FadeAnimationView'; -import InfoModal from '../../../../../UI/Swaps/components/InfoModal'; -import TimeEstimateInfoModal from '../../../../../UI/TimeEstimateInfoModal'; +import { strings } from '../../../../../locales/i18n'; +import { ESTIMATED_FEE_TEST_ID } from '../../../../../wdio/screen-objects/testIDs/Screens/TransactionSummaryScreen.testIds'; +import generateTestId from '../../../../../wdio/utils/generateTestId'; +import AppConstants from '../../../../core/AppConstants'; +import { useGasTransaction } from '../../../../core/GasPolling/GasPolling'; +import Device from '../../../../util/device'; +import { isMainnetByChainId } from '../../../../util/networks'; +import { mockTheme, useAppThemeFromContext } from '../../../../util/theme'; +import useModalHandler from '../../../Base/hooks/useModalHandler'; +import Summary from '../../../Base/Summary'; +import Text from '../../../Base/Text'; +import FadeAnimationView from '../../FadeAnimationView'; +import InfoModal from '../../Swaps/components/InfoModal'; +import TimeEstimateInfoModal from '../../TimeEstimateInfoModal'; import SkeletonComponent from './skeletonComponent'; import createStyles from './styles'; import { TransactionEIP1559UpdateProps } from './types'; diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx similarity index 91% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx index dcd93db47ce..034a8d23f6e 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/skeletonComponent.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { View } from 'react-native'; -import { useTheme } from '../../../../../../util/theme'; +import { useTheme } from '../../../../util/theme'; import SkeletonPlaceholder from 'react-native-skeleton-placeholder'; import createStyles from './styles'; import { SkeletonProps } from './types'; diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/styles.ts b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/styles.ts similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/styles.ts rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/styles.ts diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/types.ts b/app/components/UI/TransactionReview/TransactionReviewEIP1559Update/types.ts similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewEIP1559Update/types.ts rename to app/components/UI/TransactionReview/TransactionReviewEIP1559Update/types.ts diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/TransactionReviewInformation/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/TransactionReviewInformation/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.js b/app/components/UI/TransactionReview/TransactionReviewInformation/index.js similarity index 93% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.js rename to app/components/UI/TransactionReview/TransactionReviewInformation/index.js index 07c1ed16cb9..cd60c3c5736 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.js +++ b/app/components/UI/TransactionReview/TransactionReviewInformation/index.js @@ -8,7 +8,7 @@ import { TouchableOpacity, InteractionManager, } from 'react-native'; -import { fontStyles } from '../../../../../../styles/common'; +import { fontStyles } from '../../../../styles/common'; import { connect } from 'react-redux'; import { isBN, @@ -19,50 +19,47 @@ import { renderFromWei, BNToHex, hexToBN, -} from '../../../../../../util/number'; -import { strings } from '../../../../../../../locales/i18n'; +} from '../../../../util/number'; +import { strings } from '../../../../../locales/i18n'; import { getTicker, getNormalizedTxState, calculateAmountsEIP1559, calculateEthEIP1559, calculateERC20EIP1559, -} from '../../../../../../util/transactions'; -import { sumHexWEIs } from '../../../../../../util/conversions'; -import Analytics from '../../../../../../core/Analytics/Analytics'; -import { MetaMetricsEvents } from '../../../../../../core/Analytics'; +} from '../../../../util/transactions'; +import { sumHexWEIs } from '../../../../util/conversions'; +import Analytics from '../../../../core/Analytics/Analytics'; +import { MetaMetricsEvents } from '../../../../core/Analytics'; import { TESTNET_FAUCETS, getNetworkNonce, isTestNet, isTestNetworkWithFaucet, -} from '../../../../../../util/networks'; -import CustomNonceModal from '../../../SendFlow/components/CustomNonceModal'; -import { - setNonce, - setProposedNonce, -} from '../../../../../../actions/transaction'; +} from '../../../../util/networks'; +import CustomNonceModal from '../../../UI/CustomNonceModal'; +import { setNonce, setProposedNonce } from '../../../../actions/transaction'; import TransactionReviewEIP1559 from '../TransactionReviewEIP1559'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; -import CustomNonce from '../../CustomNonce'; -import Logger from '../../../../../../util/Logger'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; -import AppConstants from '../../../../../../core/AppConstants'; -import WarningMessage from '../../../SendFlow/WarningMessage'; +import CustomNonce from '../../../UI/CustomNonce'; +import Logger from '../../../../util/Logger'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import AppConstants from '../../../../core/AppConstants'; +import WarningMessage from '../../../Views/SendFlow/WarningMessage'; import { selectChainId, selectTicker, -} from '../../../../../../selectors/networkController'; +} from '../../../../selectors/networkController'; import { selectConversionRate, selectCurrentCurrency, selectNativeCurrency, -} from '../../../../../../selectors/currencyRateController'; -import { selectContractExchangeRates } from '../../../../../../selectors/tokenRatesController'; -import { createBrowserNavDetails } from '../../../../Browser'; -import { isNetworkRampNativeTokenSupported } from '../../../../../../components/UI/Ramp/utils'; -import { getRampNetworks } from '../../../../../../reducers/fiatOrders'; -import Routes from '../../../../../../constants/navigation/Routes'; +} from '../../../../selectors/currencyRateController'; +import { selectContractExchangeRates } from '../../../../selectors/tokenRatesController'; +import { createBrowserNavDetails } from '../../../Views/Browser'; +import { isNetworkRampNativeTokenSupported } from '../../Ramp/utils'; +import { getRampNetworks } from '../../../../reducers/fiatOrders'; +import Routes from '../../../../constants/navigation/Routes'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.test.tsx b/app/components/UI/TransactionReview/TransactionReviewInformation/index.test.tsx similarity index 87% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.test.tsx rename to app/components/UI/TransactionReview/TransactionReviewInformation/index.test.tsx index 5232ae17c34..5cf128500e6 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewInformation/index.test.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewInformation/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import TransactionReviewInformation from '.'; +import TransactionReviewInformation from './'; import configureMockStore from 'redux-mock-store'; import { shallow } from 'enzyme'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/TransactionReviewSummary/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/TransactionReviewSummary/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.js b/app/components/UI/TransactionReview/TransactionReviewSummary/index.js similarity index 92% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.js rename to app/components/UI/TransactionReview/TransactionReviewSummary/index.js index bee8c944959..15bb40ae627 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.js +++ b/app/components/UI/TransactionReview/TransactionReviewSummary/index.js @@ -1,11 +1,11 @@ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { StyleSheet, Text, View } from 'react-native'; -import { fontStyles } from '../../../../../../styles/common'; -import { strings } from '../../../../../../../locales/i18n'; -import WarningMessage from '../../../SendFlow/WarningMessage'; -import { ThemeContext, mockTheme } from '../../../../../../util/theme'; -import { isTestNet } from '../../../../../../util/networks'; +import { fontStyles } from '../../../../styles/common'; +import { strings } from '../../../../../locales/i18n'; +import WarningMessage from '../../../Views/SendFlow/WarningMessage'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import { isTestNet } from '../../../../util/networks'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.test.tsx b/app/components/UI/TransactionReview/TransactionReviewSummary/index.test.tsx similarity index 85% rename from app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.test.tsx rename to app/components/UI/TransactionReview/TransactionReviewSummary/index.test.tsx index b177e75ecde..8b140de27d7 100644 --- a/app/components/Views/confirmations/components/TransactionReview/TransactionReviewSummary/index.test.tsx +++ b/app/components/UI/TransactionReview/TransactionReviewSummary/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import TransactionReviewSummary from '.'; +import TransactionReviewSummary from './'; import configureMockStore from 'redux-mock-store'; import { shallow } from 'enzyme'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/components/TransactionReview/__snapshots__/index.test.tsx.snap b/app/components/UI/TransactionReview/__snapshots__/index.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/components/TransactionReview/__snapshots__/index.test.tsx.snap rename to app/components/UI/TransactionReview/__snapshots__/index.test.tsx.snap index 00f87bb6292..1d5ad5ed235 100644 --- a/app/components/Views/confirmations/components/TransactionReview/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/TransactionReview/__snapshots__/index.test.tsx.snap @@ -846,7 +846,7 @@ Array [ style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 15, }, undefined, @@ -1580,8 +1580,6 @@ Array [ Object { "marginLeft": 8, }, - Object {}, - Object {}, ], ], null, @@ -1607,7 +1605,7 @@ Array [ "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/Views/confirmations/components/TransactionReview/index.js b/app/components/UI/TransactionReview/index.js similarity index 87% rename from app/components/Views/confirmations/components/TransactionReview/index.js rename to app/components/UI/TransactionReview/index.js index 2293e2c310a..12bb0cd52eb 100644 --- a/app/components/Views/confirmations/components/TransactionReview/index.js +++ b/app/components/UI/TransactionReview/index.js @@ -11,19 +11,19 @@ import Eth from 'ethjs-query'; import { isMultiLayerFeeNetwork, fetchEstimatedMultiLayerL1Fee, -} from '../../../../../util/networks'; -import Engine from '../../../../../core/Engine'; -import Logger from '../../../../../util/Logger'; -import { fontStyles } from '../../../../../styles/common'; +} from '../../../util/networks'; +import Engine from '../../../core/Engine'; +import Logger from '../../../util/Logger'; +import { fontStyles } from '../../../styles/common'; import { connect } from 'react-redux'; -import { strings } from '../../../../../../locales/i18n'; +import { strings } from '../../../../locales/i18n'; import { getTransactionReviewActionKey, getNormalizedTxState, APPROVE_FUNCTION_SIGNATURE, decodeTransferData, getTicker, -} from '../../../../../util/transactions'; +} from '../../../util/transactions'; import { weiToFiat, balanceToFiat, @@ -31,39 +31,38 @@ import { renderFromWei, fromTokenMinimalUnit, isZeroValue, -} from '../../../../../util/number'; -import { safeToChecksumAddress } from '../../../../../util/address'; -import Device from '../../../../../util/device'; -import { getBlockaidMetricsParams } from '../../../../../util/blockaid'; +} from '../../../util/number'; +import { safeToChecksumAddress } from '../../../util/address'; +import Device from '../../../util/device'; +import { getBlockaidMetricsParams } from '../../../util/blockaid'; import TransactionReviewInformation from './TransactionReviewInformation'; import TransactionReviewSummary from './TransactionReviewSummary'; import TransactionReviewData from './TransactionReviewData'; -import Analytics from '../../../../../core/Analytics/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import TransactionHeader from '../../../../UI/TransactionHeader'; -import AccountFromToInfoCard from '../../../../UI/AccountFromToInfoCard'; -import ActionView, { ConfirmButtonState } from '../../../../UI/ActionView'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import withQRHardwareAwareness from '../../../../UI/QRHardware/withQRHardwareAwareness'; -import QRSigningDetails from '../../../../UI/QRHardware/QRSigningDetails'; +import Analytics from '../../../core/Analytics/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import TransactionHeader from '../TransactionHeader'; +import AccountFromToInfoCard from '../AccountFromToInfoCard'; +import ActionView from '../ActionView'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; +import { ThemeContext, mockTheme } from '../../../util/theme'; +import withQRHardwareAwareness from '../QRHardware/withQRHardwareAwareness'; +import QRSigningDetails from '../QRHardware/QRSigningDetails'; import { withNavigation } from '@react-navigation/compat'; import { selectChainId, selectTicker, -} from '../../../../../selectors/networkController'; +} from '../../../selectors/networkController'; import { selectConversionRate, selectCurrentCurrency, -} from '../../../../../selectors/currencyRateController'; -import { selectTokenList } from '../../../../../selectors/tokenListController'; -import { selectTokens } from '../../../../../selectors/tokensController'; -import { selectContractExchangeRates } from '../../../../../selectors/tokenRatesController'; +} from '../../../selectors/currencyRateController'; +import { selectTokenList } from '../../../selectors/tokenListController'; +import { selectTokens } from '../../../selectors/tokensController'; +import { selectContractExchangeRates } from '../../../selectors/tokenRatesController'; import ApproveTransactionHeader from '../ApproveTransactionHeader'; -import AppConstants from '../../../../../core/AppConstants'; +import AppConstants from '../../../core/AppConstants'; import TransactionBlockaidBanner from '../TransactionBlockaidBanner/TransactionBlockaidBanner'; -import { ResultType } from '../BlockaidBanner/BlockaidBanner.types'; const POLLING_INTERVAL_ESTIMATED_L1_FEE = 30000; @@ -446,30 +445,6 @@ class TransactionReview extends PureComponent { return url; } - getConfirmButtonState() { - const { transaction } = this.props; - const { id, currentTransactionSecurityAlertResponse } = transaction; - let confirmButtonState = ConfirmButtonState.Normal; - if ( - id && - currentTransactionSecurityAlertResponse?.id && - currentTransactionSecurityAlertResponse.id === id - ) { - if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Malicious - ) { - confirmButtonState = ConfirmButtonState.Error; - } else if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Warning - ) { - confirmButtonState = ConfirmButtonState.Warning; - } - } - return confirmButtonState; - } - renderTransactionReview = () => { const { transactionConfirmed, @@ -506,7 +481,6 @@ class TransactionReview extends PureComponent { } = this.state; const url = this.getUrlFromBrowser(); const styles = this.getStyles(); - return ( <> diff --git a/app/components/Views/confirmations/components/TransactionReview/index.test.tsx b/app/components/UI/TransactionReview/index.test.tsx similarity index 89% rename from app/components/Views/confirmations/components/TransactionReview/index.test.tsx rename to app/components/UI/TransactionReview/index.test.tsx index 1ec7f51a0c3..31f25eaa5aa 100644 --- a/app/components/Views/confirmations/components/TransactionReview/index.test.tsx +++ b/app/components/UI/TransactionReview/index.test.tsx @@ -1,31 +1,31 @@ import React from 'react'; -import TransactionReview from '.'; +import TransactionReview from './'; import configureMockStore from 'redux-mock-store'; import { shallow } from 'enzyme'; import { Provider } from 'react-redux'; // eslint-disable-next-line import/no-namespace -import * as TransactionUtils from '../../../../../util/transactions'; +import * as TransactionUtils from '../../../util/transactions'; // eslint-disable-next-line import/no-namespace -import * as BlockaidUtils from '../../../../../util/blockaid'; -import analyticsV2 from '../../../../../util/analyticsV2'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import * as BlockaidUtils from '../../../util/blockaid'; +import analyticsV2 from '../../../util/analyticsV2'; +import renderWithProvider from '../../../util/test/renderWithProvider'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; import { fireEvent } from '@testing-library/react-native'; -import { TESTID_ACCORDION_CONTENT } from '../../../../../component-library/components/Accordions/Accordion/Accordion.constants'; +import { TESTID_ACCORDION_CONTENT } from '../../../component-library/components/Accordions/Accordion/Accordion.constants'; import { FALSE_POSITIVE_REPOST_LINE_TEST_ID } from '../BlockaidBanner/BlockaidBanner.constants'; -jest.mock('../../../../../util/transactions', () => ({ - ...jest.requireActual('../../../../../util/transactions'), +jest.mock('../../../util/transactions', () => ({ + ...jest.requireActual('../../../util/transactions'), getTransactionReviewActionKey: jest.fn(), })); -jest.mock('../../../../../util/ENSUtils', () => ({ - ...jest.requireActual('../../../../../util/ENSUtils'), +jest.mock('../../../util/ENSUtils', () => ({ + ...jest.requireActual('../../../util/ENSUtils'), doENSReverseLookup: jest.fn(), })); -jest.mock('../../../../../util/address', () => ({ - ...jest.requireActual('../../../../../util/address'), +jest.mock('../../../util/address', () => ({ + ...jest.requireActual('../../../util/address'), renderAccountName: jest.fn(), isQRHardwareAccount: jest.fn(), })); @@ -35,12 +35,9 @@ jest.mock('react-native-keyboard-aware-scroll-view', () => { return { KeyboardAwareScrollView }; }); -jest.mock( - '../../../../../components/UI/QRHardware/withQRHardwareAwareness', - () => (obj: any) => obj, -); +jest.mock('../QRHardware/withQRHardwareAwareness', () => (obj: any) => obj); -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../core/Engine', () => ({ context: { KeyringController: { state: { @@ -88,7 +85,7 @@ const mockState = { }, NetworkController: { providerConfig: { - chainId: '0x1', + chainId: '1', type: 'sepolia', nickname: 'Sepolia', }, diff --git a/app/components/UI/Transactions/index.js b/app/components/UI/Transactions/index.js index d4834c565a4..da8412ae08c 100644 --- a/app/components/UI/Transactions/index.js +++ b/app/components/UI/Transactions/index.js @@ -47,7 +47,7 @@ import { validateTransactionActionBalance } from '../../../util/transactions'; import withQRHardwareAwareness from '../QRHardware/withQRHardwareAwareness'; import TransactionActionModal from '../TransactionActionModal'; import TransactionElement from '../TransactionElement'; -import UpdateEIP1559Tx from '../../Views/confirmations/components/UpdateEIP1559Tx'; +import UpdateEIP1559Tx from '../UpdateEIP1559Tx'; import RetryModal from './RetryModal'; import PriceChartContext, { PriceChartProvider, @@ -69,10 +69,6 @@ import { import { getLedgerKeyring } from '../../../core/Ledger/Ledger'; import ExtendedKeyringTypes from '../../../constants/keyringTypes'; import { TOKEN_OVERVIEW_TXN_SCREEN } from '../../../../wdio/screen-objects/testIDs/Screens/TokenOverviewScreen.testIds'; -import { - speedUpTransaction, - updateIncomingTransactions, -} from '../../../util/transaction-controller'; const createStyles = (colors, typography) => StyleSheet.create({ @@ -252,13 +248,13 @@ class Transactions extends PureComponent { updateBlockExplorer = () => { const { - providerConfig: { type, rpcUrl }, + providerConfig: { type, rpcTarget }, networkConfigurations, } = this.props; let blockExplorer; if (type === RPC) { blockExplorer = - findBlockExplorerForRpc(rpcUrl, networkConfigurations) || + findBlockExplorerForRpc(rpcTarget, networkConfigurations) || NO_RPC_BLOCK_EXPLORER; } @@ -330,9 +326,11 @@ class Transactions extends PureComponent { }; onRefresh = async () => { + const { TransactionController } = Engine.context; + this.setState({ refreshing: true }); - await updateIncomingTransactions(); + await TransactionController.updateIncomingTransactions(); this.setState({ refreshing: false }); }; @@ -531,7 +529,7 @@ class Transactions extends PureComponent { }, }); } else { - await speedUpTransaction( + await Engine.context.TransactionController.speedUpTransaction( this.speedUpTxId, transactionObject?.suggestedMaxFeePerGasHex && { maxFeePerGas: `0x${transactionObject?.suggestedMaxFeePerGasHex}`, diff --git a/app/components/Views/confirmations/components/TypedSign/__snapshots__/index.test.tsx.snap b/app/components/UI/TypedSign/__snapshots__/index.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/components/TypedSign/__snapshots__/index.test.tsx.snap rename to app/components/UI/TypedSign/__snapshots__/index.test.tsx.snap index dfc3e93c6e6..f6fc8e991d3 100644 --- a/app/components/Views/confirmations/components/TypedSign/__snapshots__/index.test.tsx.snap +++ b/app/components/UI/TypedSign/__snapshots__/index.test.tsx.snap @@ -611,8 +611,6 @@ exports[`TypedSign onConfirm signs message 1`] = ` Object { "marginLeft": 8, }, - Object {}, - Object {}, ], ], null, @@ -638,7 +636,7 @@ exports[`TypedSign onConfirm signs message 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], @@ -1267,8 +1265,6 @@ exports[`TypedSign onReject rejects message 1`] = ` Object { "marginLeft": 8, }, - Object {}, - Object {}, ], ], null, @@ -1294,7 +1290,7 @@ exports[`TypedSign onReject rejects message 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/Views/confirmations/components/TypedSign/index.js b/app/components/UI/TypedSign/index.js similarity index 90% rename from app/components/Views/confirmations/components/TypedSign/index.js rename to app/components/UI/TypedSign/index.js index 8f518edae9d..04e6319623d 100644 --- a/app/components/Views/confirmations/components/TypedSign/index.js +++ b/app/components/UI/TypedSign/index.js @@ -2,15 +2,15 @@ import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { StyleSheet, View, Text } from 'react-native'; -import { fontStyles } from '../../../../../styles/common'; +import { fontStyles } from '../../../styles/common'; import SignatureRequest from '../SignatureRequest'; import ExpandedMessage from '../SignatureRequest/ExpandedMessage'; -import Device from '../../../../../util/device'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import sanitizeString from '../../../../../util/string'; +import Device from '../../../util/device'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import { KEYSTONE_TX_CANCELED } from '../../../constants/error'; +import { ThemeContext, mockTheme } from '../../../util/theme'; +import sanitizeString from '../../../util/string'; import { addSignatureErrorListener, @@ -20,10 +20,10 @@ import { shouldTruncateMessage, showWalletConnectNotification, typedSign, -} from '../../../../../util/confirmation/signatureUtils'; -import { isExternalHardwareAccount } from '../../../../../util/address'; -import createExternalSignModelNav from '../../../../../util/hardwareWallet/signatureUtils'; -import { SigningModalSelectorsIDs } from '../../../../../../e2e/selectors/Modals/SigningModal.selectors'; +} from '../../../util/confirmation/signatureUtils'; +import { isExternalHardwareAccount } from '../../../util/address'; +import createExternalSignModelNav from '../../../util/hardwareWallet/signatureUtils'; +import { SigningModalSelectorsIDs } from '../../../../e2e/selectors/Modals/SigningModal.selectors'; const createStyles = (colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/components/TypedSign/index.test.tsx b/app/components/UI/TypedSign/index.test.tsx similarity index 92% rename from app/components/Views/confirmations/components/TypedSign/index.test.tsx rename to app/components/UI/TypedSign/index.test.tsx index 147e21527df..1892b5b25de 100644 --- a/app/components/Views/confirmations/components/TypedSign/index.test.tsx +++ b/app/components/UI/TypedSign/index.test.tsx @@ -1,20 +1,20 @@ import React from 'react'; import { shallow } from 'enzyme'; -import TypedSign from '.'; +import TypedSign from './'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; -import Engine from '../../../../../core/Engine'; -import NotificationManager from '../../../../../core/NotificationManager'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; +import Engine from '../../../core/Engine'; +import NotificationManager from '../../../core/NotificationManager'; +import { WALLET_CONNECT_ORIGIN } from '../../../util/walletconnect'; import { InteractionManager } from 'react-native'; -import { strings } from '../../../../../../locales/i18n'; -import AppConstants from '../../../../../core/AppConstants'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; +import { strings } from '../../../../locales/i18n'; +import AppConstants from '../../../core/AppConstants'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; +import renderWithProvider from '../../../util/test/renderWithProvider'; import { fireEvent, waitFor } from '@testing-library/react-native'; -import analyticsV2 from '../../../../../util/analyticsV2'; +import analyticsV2 from '../../../util/analyticsV2'; -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../core/Engine', () => ({ acceptPendingApproval: jest.fn(), rejectPendingApproval: jest.fn(), context: { @@ -36,14 +36,14 @@ jest.mock('../../../../../core/Engine', () => ({ }, })); -jest.mock('../../../../../core/NotificationManager'); +jest.mock('../../../core/NotificationManager'); -jest.mock('../../../../../util/address', () => ({ - ...jest.requireActual('../../../../../util/address'), +jest.mock('../../../util/address', () => ({ + ...jest.requireActual('../../../util/address'), getAddressAccountType: jest.fn().mockReturnValue('Metamask'), })); -jest.mock('../../../../../util/analyticsV2'); +jest.mock('../../../util/analyticsV2'); const messageParamsMock = { data: { type: 'string', name: 'Message', value: 'Hi, Alice!' }, diff --git a/app/components/Views/confirmations/components/UpdateEIP1559Tx/index.tsx b/app/components/UI/UpdateEIP1559Tx/index.tsx similarity index 91% rename from app/components/Views/confirmations/components/UpdateEIP1559Tx/index.tsx rename to app/components/UI/UpdateEIP1559Tx/index.tsx index 162cbca019b..809da707647 100644 --- a/app/components/Views/confirmations/components/UpdateEIP1559Tx/index.tsx +++ b/app/components/UI/UpdateEIP1559Tx/index.tsx @@ -4,24 +4,23 @@ import EditGasFee1559Update from '../EditGasFee1559Update'; import { connect } from 'react-redux'; import { CANCEL_RATE, SPEED_UP_RATE } from '@metamask/transaction-controller'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; -import { hexToBN, fromWei, renderFromWei } from '../../../../../util/number'; +import { hexToBN, fromWei, renderFromWei } from '../../../util/number'; import BigNumber from 'bignumber.js'; -import { getTicker } from '../../../../../util/transactions'; -import AppConstants from '../../../../../core/AppConstants'; -import { strings } from '../../../../../../locales/i18n'; +import { getTicker } from '../../../util/transactions'; +import AppConstants from '../../../core/AppConstants'; +import { strings } from '../../../../locales/i18n'; import { startGasPolling, stopGasPolling, -} from '../../../../../core/GasPolling/GasPolling'; -import { GasTransactionProps } from '../../../../../core/GasPolling/types'; +} from '../../../core/GasPolling/GasPolling'; +import { GasTransactionProps } from '../../../core/GasPolling/types'; import { UpdateEIP1559Props, UpdateTx1559Options } from './types'; import { selectChainId, selectTicker, -} from '../../../../../selectors/networkController'; -import { selectAccounts } from '../../../../../selectors/accountTrackerController'; -import { selectSelectedAddress } from '../../../../../selectors/preferencesController'; -import { getDecimalChainId } from '../../../../../util/networks'; +} from '../../../selectors/networkController'; +import { selectAccounts } from '../../../selectors/accountTrackerController'; +import { selectSelectedAddress } from '../../../selectors/preferencesController'; const UpdateEIP1559Tx = ({ gas, @@ -216,7 +215,7 @@ const UpdateEIP1559Tx = ({ }; const getGasAnalyticsParams = () => ({ - chain_id: getDecimalChainId(chainId), + chain_id: chainId, gas_estimate_type: gasEstimateType, gas_mode: gasSelected ? 'Basic' : 'Advanced', speed_set: gasSelected || undefined, diff --git a/app/components/Views/confirmations/components/UpdateEIP1559Tx/types.ts b/app/components/UI/UpdateEIP1559Tx/types.ts similarity index 100% rename from app/components/Views/confirmations/components/UpdateEIP1559Tx/types.ts rename to app/components/UI/UpdateEIP1559Tx/types.ts diff --git a/app/components/UI/WarningAlert/__snapshots__/WarningAlert.test.tsx.snap b/app/components/UI/WarningAlert/__snapshots__/WarningAlert.test.tsx.snap index 6b18246ea52..0f5c933bc17 100644 --- a/app/components/UI/WarningAlert/__snapshots__/WarningAlert.test.tsx.snap +++ b/app/components/UI/WarningAlert/__snapshots__/WarningAlert.test.tsx.snap @@ -6,7 +6,7 @@ exports[`ButtonBase should render correctly 1`] = ` Array [ Object { "backgroundColor": "#FFFFFF", - "borderColor": "#BF5208", + "borderColor": "#F66A0A", "borderRadius": 8, "bottom": 20, "left": 16, diff --git a/app/components/Views/confirmations/components/WatchAssetRequest/__snapshots__/index.test.tsx.snap b/app/components/UI/WatchAssetRequest/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/components/WatchAssetRequest/__snapshots__/index.test.tsx.snap rename to app/components/UI/WatchAssetRequest/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/components/WatchAssetRequest/index.js b/app/components/UI/WatchAssetRequest/index.js similarity index 85% rename from app/components/Views/confirmations/components/WatchAssetRequest/index.js rename to app/components/UI/WatchAssetRequest/index.js index 83bfc439e0c..5460854ddd4 100644 --- a/app/components/Views/confirmations/components/WatchAssetRequest/index.js +++ b/app/components/UI/WatchAssetRequest/index.js @@ -3,24 +3,23 @@ import PropTypes from 'prop-types'; import { StyleSheet, View, Text, InteractionManager } from 'react-native'; import URL from 'url-parse'; import { useSelector } from 'react-redux'; -import { fontStyles } from '../../../../../styles/common'; -import { strings } from '../../../../../../locales/i18n'; -import ActionView from '../../../../UI/ActionView'; -import { renderFromTokenMinimalUnit } from '../../../../../util/number'; -import TokenImage from '../../../../UI/TokenImage'; -import Device from '../../../../../util/device'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; +import { fontStyles } from '../../../styles/common'; +import { strings } from '../../../../locales/i18n'; +import ActionView from '../ActionView'; +import { renderFromTokenMinimalUnit } from '../../../util/number'; +import TokenImage from '../../UI/TokenImage'; +import Device from '../../../util/device'; +import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; -import useTokenBalance from '../../../../hooks/useTokenBalance'; -import { useTheme } from '../../../../../util/theme'; -import NotificationManager from '../../../../../core/NotificationManager'; -import { selectChainId } from '../../../../../selectors/networkController'; +import useTokenBalance from '../../hooks/useTokenBalance'; +import { useTheme } from '../../../util/theme'; +import NotificationManager from '../../../core/NotificationManager'; +import { selectChainId } from '../../../selectors/networkController'; import ApproveTransactionHeader from '../ApproveTransactionHeader'; -import { getActiveTabUrl } from '../../../../../util/transactions'; +import { getActiveTabUrl } from '../../../util/transactions'; import { isEqual } from 'lodash'; -import { SigningModalSelectorsIDs } from '../../../../../../e2e/selectors/Modals/SigningModal.selectors'; -import { getDecimalChainId } from '../../../../../util/networks'; +import { SigningModalSelectorsIDs } from '../../../../e2e/selectors/Modals/SigningModal.selectors'; const createStyles = (colors) => StyleSheet.create({ @@ -121,7 +120,7 @@ const WatchAssetRequest = ({ token_address: asset?.address, token_symbol: asset?.symbol, dapp_host_name: url?.host, - chain_id: getDecimalChainId(chainId), + chain_id: chainId, source: 'Dapp suggested (watchAsset)', }; } catch (error) { diff --git a/app/components/Views/confirmations/components/WatchAssetRequest/index.test.tsx b/app/components/UI/WatchAssetRequest/index.test.tsx similarity index 84% rename from app/components/Views/confirmations/components/WatchAssetRequest/index.test.tsx rename to app/components/UI/WatchAssetRequest/index.test.tsx index 8b7796754e6..feeee957d2b 100644 --- a/app/components/Views/confirmations/components/WatchAssetRequest/index.test.tsx +++ b/app/components/UI/WatchAssetRequest/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { shallow } from 'enzyme'; -import WatchAssetRequest from '.'; +import WatchAssetRequest from './'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/UI/WhatsNewModal/types.ts b/app/components/UI/WhatsNewModal/types.ts index c10a16ac2e6..cf41881ee6a 100644 --- a/app/components/UI/WhatsNewModal/types.ts +++ b/app/components/UI/WhatsNewModal/types.ts @@ -41,7 +41,7 @@ type SlideContentType = type WhatsNewSlides = SlideContentType[][]; -type VersionString = `${number}.${number}.${number}` | `${number}.${number}`; +type VersionString = `${number}.${number}.${number}`; export interface WhatsNew { onlyUpdates: boolean; diff --git a/app/components/UI/WhatsNewModal/whatsNewList.ts b/app/components/UI/WhatsNewModal/whatsNewList.ts index d7fc56a2c5a..553d371f612 100644 --- a/app/components/UI/WhatsNewModal/whatsNewList.ts +++ b/app/components/UI/WhatsNewModal/whatsNewList.ts @@ -7,8 +7,8 @@ import { WhatsNew } from './types'; export const whatsNew: WhatsNew = { // All users that have <6.4.0 and are updating to >=6.4.0 should see onlyUpdates: false, // false: Users who updated the app and new installs will see this. true: only users who update will see it - maxLastAppVersion: '7.20', // When updating, only users who had a previous version < '7.20' may see the modal - minAppVersion: '7.16.0', // Only users whose current version is >= 7.16.0 may see the modal. This should match the version with the latest copy changes in the modal. + maxLastAppVersion: '7.15.0', // Only users who had a previous version <7.15.0 version will see this + minAppVersion: '7.15.0', // Only users who updated to a version >= 7.15.0 will see this /** * Slides utilizes a templating system in the form of a 2D array, which is eventually rendered within app/components/UI/WhatsNewModal/index.js. * The root layer determines the number of slides. Ex. To display 3 slides, the root layer should contain 3 arrays. @@ -36,13 +36,9 @@ export const whatsNew: WhatsNew = { type: 'description', description: strings('whats_new.blockaid.description_2'), }, - { - type: 'description', - description: strings('whats_new.blockaid.description_3'), - }, { type: 'button', - buttonText: strings('whats_new.blockaid.got_it'), + buttonText: strings('whats_new.blockaid.action_text'), buttonType: 'blue', onPress: (props) => props.navigation.navigate(Routes.SETTINGS_VIEW, { diff --git a/app/components/Views/AccountActions/AccountActions.test.tsx b/app/components/Views/AccountActions/AccountActions.test.tsx index a25e5ccd3ec..9ed00606399 100644 --- a/app/components/Views/AccountActions/AccountActions.test.tsx +++ b/app/components/Views/AccountActions/AccountActions.test.tsx @@ -19,7 +19,7 @@ import initialBackgroundState from '../../../util/test/initial-background-state. const mockEngine = Engine; const initialState = { - swaps: { '0x1': { isLive: true }, hasOnboarded: false, isLive: true }, + swaps: { '1': { isLive: true }, hasOnboarded: false, isLive: true }, engine: { backgroundState: { ...initialBackgroundState, diff --git a/app/components/Views/AccountActions/AccountActions.tsx b/app/components/Views/AccountActions/AccountActions.tsx index 8469f1653ef..806caec9d64 100644 --- a/app/components/Views/AccountActions/AccountActions.tsx +++ b/app/components/Views/AccountActions/AccountActions.tsx @@ -55,14 +55,14 @@ const AccountActions = () => { const networkConfigurations = useSelector(selectNetworkConfigurations); const blockExplorer = useMemo(() => { - if (providerConfig?.rpcUrl && providerConfig.type === RPC) { + if (providerConfig?.rpcTarget && providerConfig.type === RPC) { return findBlockExplorerForRpc( - providerConfig.rpcUrl, + providerConfig.rpcTarget, networkConfigurations, ); } return null; - }, [networkConfigurations, providerConfig.rpcUrl, providerConfig.type]); + }, [networkConfigurations, providerConfig.rpcTarget, providerConfig.type]); const blockExplorerName = getBlockExplorerName(blockExplorer); diff --git a/app/components/Views/AccountBackupStep1/index.js b/app/components/Views/AccountBackupStep1/index.js index 99804c6ab18..83f3e4c0a4f 100644 --- a/app/components/Views/AccountBackupStep1/index.js +++ b/app/components/Views/AccountBackupStep1/index.js @@ -7,6 +7,7 @@ import { SafeAreaView, StyleSheet, BackHandler, + InteractionManager, } from 'react-native'; import PropTypes from 'prop-types'; import { fontStyles } from '../../../styles/common'; @@ -26,12 +27,12 @@ import SeedPhraseVideo from '../../UI/SeedPhraseVideo'; import { connect } from 'react-redux'; import setOnboardingWizardStep from '../../../actions/wizard'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import DefaultPreference from 'react-native-default-preference'; import { useTheme } from '../../../util/theme'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; -import Logger from '../../../util/Logger'; import { ManualBackUpStepsSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ManualBackUpSteps.selectors'; + const createStyles = (colors) => StyleSheet.create({ mainWrapper: { @@ -127,12 +128,6 @@ const AccountBackupStep1 = (props) => { const { colors } = useTheme(); const styles = createStyles(colors); - const track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('AccountBackupStep1', `Failed to track ${event}`); - }); - }; - useEffect(() => { navigation.setOptions({ ...getOnboardingNavbarOptions( @@ -166,14 +161,18 @@ const AccountBackupStep1 = (props) => { const goNext = () => { props.navigation.navigate('AccountBackupStep1B', { ...props.route.params }); - track(MetaMetricsEvents.WALLET_SECURITY_STARTED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SECURITY_STARTED); + }); }; const showRemindLater = () => { if (hasFunds) return; setRemindLaterModal(true); - track(MetaMetricsEvents.WALLET_SECURITY_SKIP_INITIATED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SECURITY_SKIP_INITIATED); + }); }; const toggleSkipCheckbox = () => @@ -191,7 +190,9 @@ const AccountBackupStep1 = (props) => { const skip = async () => { hideRemindLaterModal(); - track(MetaMetricsEvents.WALLET_SECURITY_SKIP_CONFIRMED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SECURITY_SKIP_CONFIRMED); + }); // Get onboarding wizard state const onboardingWizard = await DefaultPreference.get(ONBOARDING_WIZARD); if (onboardingWizard) { diff --git a/app/components/Views/AccountBackupStep1B/index.js b/app/components/Views/AccountBackupStep1B/index.js index 61dbbab92dd..2b1c5378cc1 100644 --- a/app/components/Views/AccountBackupStep1B/index.js +++ b/app/components/Views/AccountBackupStep1B/index.js @@ -8,6 +8,7 @@ import { StyleSheet, Image, Dimensions, + InteractionManager, } from 'react-native'; import PropTypes from 'prop-types'; import Icon from 'react-native-vector-icons/FontAwesome'; @@ -22,10 +23,9 @@ import SeedphraseModal from '../../UI/SeedphraseModal'; import { getOnboardingNavbarOptions } from '../../UI/Navbar'; import { CHOOSE_PASSWORD_STEPS } from '../../../constants/onboarding'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { useTheme } from '../../../util/theme'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; -import Logger from '../../../util/Logger'; import { ManualBackUpStepsSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ManualBackUpSteps.selectors'; const explain_backup_seedphrase = require('../../../images/explain-backup-seedphrase.png'); // eslint-disable-line @@ -206,19 +206,17 @@ const AccountBackupStep1B = (props) => { const { colors } = useTheme(); const styles = createStyles(colors); - const track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('AccountBackupStep1B', `Failed to track ${event}`); - }); - }; - useEffect(() => { navigation.setOptions(getOnboardingNavbarOptions(route, {}, colors)); }, [navigation, route, colors]); const goNext = () => { props.navigation.navigate('ManualBackupStep1', { ...props.route.params }); - track(MetaMetricsEvents.WALLET_SECURITY_MANUAL_BACKUP_INITIATED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent( + MetaMetricsEvents.WALLET_SECURITY_MANUAL_BACKUP_INITIATED, + ); + }); }; const learnMore = () => { diff --git a/app/components/Views/AccountConnect/AccountConnect.tsx b/app/components/Views/AccountConnect/AccountConnect.tsx index c99a0f926a5..e511cd5f65f 100644 --- a/app/components/Views/AccountConnect/AccountConnect.tsx +++ b/app/components/Views/AccountConnect/AccountConnect.tsx @@ -54,7 +54,6 @@ import AccountConnectSingleSelector from './AccountConnectSingleSelector'; import AccountConnectMultiSelector from './AccountConnectMultiSelector'; import useFavicon from '../../hooks/useFavicon/useFavicon'; import URLParse from 'url-parse'; -import { trackDappVisitedEvent } from '../../../analytics'; const AccountConnect = (props: AccountConnectProps) => { const Engine = UntypedEngine as any; @@ -125,13 +124,6 @@ const AccountConnect = (props: AccountConnectProps) => { [Engine.context.PermissionController, accountsLength], ); - const triggerDappVisitedEvent = useCallback( - (numberOfConnectedAccounts: number) => - // Track dapp visited event - trackDappVisitedEvent({ hostname, numberOfConnectedAccounts }), - [hostname], - ); - const handleConnect = useCallback(async () => { const selectedAccounts: SelectedAccount[] = selectedAddresses.map( (address, index) => ({ address, lastUsed: Date.now() - index }), @@ -157,9 +149,6 @@ const AccountConnect = (props: AccountConnectProps) => { await Engine.context.PermissionController.acceptPermissionsRequest( request, ); - - triggerDappVisitedEvent(connectedAccountLength); - AnalyticsV2.trackEvent(MetaMetricsEvents.CONNECT_REQUEST_COMPLETED, { number_of_accounts: accountsLength, number_of_accounts_connected: connectedAccountLength, @@ -203,7 +192,6 @@ const AccountConnect = (props: AccountConnectProps) => { Engine.context.PermissionController, toastRef, accountsLength, - triggerDappVisitedEvent, ]); const handleCreateAccount = useCallback( diff --git a/app/components/Views/AccountPermissions/AccountPermissionsConnected/AccountPermissionsConnected.tsx b/app/components/Views/AccountPermissions/AccountPermissionsConnected/AccountPermissionsConnected.tsx index a727f51378e..c2f3cac7837 100644 --- a/app/components/Views/AccountPermissions/AccountPermissionsConnected/AccountPermissionsConnected.tsx +++ b/app/components/Views/AccountPermissions/AccountPermissionsConnected/AccountPermissionsConnected.tsx @@ -14,7 +14,6 @@ import PickerNetwork from '../../../../component-library/components/Pickers/Pick import { getNetworkNameFromProviderConfig, getNetworkImageSource, - getDecimalChainId, } from '../../../../util/networks'; import AccountSelectorList from '../../../../components/UI/AccountSelectorList'; import { AccountPermissionsScreens } from '../AccountPermissions.types'; @@ -113,7 +112,7 @@ const AccountPermissionsConnected = ({ }); AnalyticsV2.trackEvent(MetaMetricsEvents.NETWORK_SELECTOR_PRESSED, { - chain_id: getDecimalChainId(providerConfig.chainId), + chain_id: providerConfig.chainId, }); }, [providerConfig.chainId, navigate]); @@ -140,7 +139,10 @@ const AccountPermissionsConnected = ({ return ( <> - + { const navigation = useNavigation(); const selectedAddress = useSelector(selectSelectedAddress); const hasOrders = useSelector((state) => getHasOrders(state) || false); - const accountsByChainId = useSelector(selectAccountsByChainId); + const accounts = useSelector(selectAccounts); const openAccountSelector = useCallback(() => { navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, { @@ -36,10 +36,9 @@ const ActivityView = () => { }); // Track Event: "Opened Acount Switcher" AnalyticsV2.trackEvent(MetaMetricsEvents.BROWSER_OPEN_ACCOUNT_SWITCH, { - number_of_accounts: Object.keys(accountsByChainId[selectedAddress] ?? {}) - .length, + number_of_accounts: Object.keys(accounts ?? {}).length, }); - }, [navigation, accountsByChainId, selectedAddress]); + }, [navigation, accounts]); useEffect( () => { diff --git a/app/components/Views/AddAsset/__snapshots__/AddAsset.test.tsx.snap b/app/components/Views/AddAsset/__snapshots__/AddAsset.test.tsx.snap index e4fc039bcb2..09e0f6e7c5c 100644 --- a/app/components/Views/AddAsset/__snapshots__/AddAsset.test.tsx.snap +++ b/app/components/Views/AddAsset/__snapshots__/AddAsset.test.tsx.snap @@ -22,8 +22,8 @@ exports[`AddAsset component renders correctly 1`] = ` id === transaction.id); const updatedTx = { ...fullTx, transaction }; - await updateTransaction(updatedTx); + await TransactionController.updateTransaction(updatedTx); await KeyringController.resetQRKeyringState(); // For Ledger Accounts we handover the signing to the confirmation flow diff --git a/app/components/Views/confirmations/Approval/index.test.tsx b/app/components/Views/Approval/index.test.tsx similarity index 88% rename from app/components/Views/confirmations/Approval/index.test.tsx rename to app/components/Views/Approval/index.test.tsx index 5aceb63c523..f55d127f317 100644 --- a/app/components/Views/confirmations/Approval/index.test.tsx +++ b/app/components/Views/Approval/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import Approval from '.'; +import Approval from './'; import configureMockStore from 'redux-mock-store'; import { shallow } from 'enzyme'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/ApproveView/Approve/__snapshots__/index.test.tsx.snap b/app/components/Views/ApproveView/Approve/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/ApproveView/Approve/__snapshots__/index.test.tsx.snap rename to app/components/Views/ApproveView/Approve/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/ApproveView/Approve/index.js b/app/components/Views/ApproveView/Approve/index.js similarity index 91% rename from app/components/Views/confirmations/ApproveView/Approve/index.js rename to app/components/Views/ApproveView/Approve/index.js index 71617d418a0..b2db4a42357 100644 --- a/app/components/Views/confirmations/ApproveView/Approve/index.js +++ b/app/components/Views/ApproveView/Approve/index.js @@ -1,25 +1,25 @@ import React, { PureComponent } from 'react'; import { Alert, InteractionManager, AppState, View } from 'react-native'; import PropTypes from 'prop-types'; -import { getApproveNavbar } from '../../../../UI/Navbar'; +import { getApproveNavbar } from '../../../UI/Navbar'; import { connect } from 'react-redux'; import { safeToChecksumAddress, isHardwareAccount, -} from '../../../../../util/address'; -import Engine from '../../../../../core/Engine'; -import AnimatedTransactionModal from '../../../../UI/AnimatedTransactionModal'; -import ApproveTransactionReview from '../../components/ApproveTransactionReview'; -import AddNickname from '../../components/ApproveTransactionReview/AddNickname'; +} from '../../../../util/address'; +import Engine from '../../../../core/Engine'; +import AnimatedTransactionModal from '../../../UI/AnimatedTransactionModal'; +import ApproveTransactionReview from '../../../UI/ApproveTransactionReview'; +import AddNickname from '../../../UI/ApproveTransactionReview/AddNickname'; import Modal from 'react-native-modal'; -import { strings } from '../../../../../../locales/i18n'; -import { getNetworkNonce } from '../../../../../util/networks'; -import Analytics from '../../../../../core/Analytics/Analytics'; +import { strings } from '../../../../../locales/i18n'; +import { getNetworkNonce } from '../../../../util/networks'; +import Analytics from '../../../../core/Analytics/Analytics'; import { setTransactionObject, setNonce, setProposedNonce, -} from '../../../../../actions/transaction'; +} from '../../../../actions/transaction'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; import { BNToHex } from '@metamask/controller-utils'; import { @@ -27,53 +27,49 @@ import { fromWei, renderFromWei, hexToBN, -} from '../../../../../util/number'; -import { - getNormalizedTxState, - getTicker, -} from '../../../../../util/transactions'; -import { getGasLimit } from '../../../../../util/custom-gas'; +} from '../../../../util/number'; +import { getNormalizedTxState, getTicker } from '../../../../util/transactions'; +import { getGasLimit } from '../../../../util/custom-gas'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; -import NotificationManager from '../../../../../core/NotificationManager'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import Logger from '../../../../../util/Logger'; -import EditGasFee1559 from '../../components/EditGasFee1559Update'; -import EditGasFeeLegacy from '../../components/EditGasFeeLegacyUpdate'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import AppConstants from '../../../../../core/AppConstants'; -import { shallowEqual } from '../../../../../util/general'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import GlobalAlert from '../../../../UI/GlobalAlert'; -import checkIfAddressIsSaved from '../../../../../util/checkAddress'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import { createLedgerTransactionModalNavDetails } from '../../../../UI/LedgerModals/LedgerTransactionModal'; +import NotificationManager from '../../../../core/NotificationManager'; +import { MetaMetricsEvents } from '../../../../core/Analytics'; +import Logger from '../../../../util/Logger'; +import EditGasFee1559 from '../../../UI/EditGasFee1559Update'; +import EditGasFeeLegacy from '../../../UI/EditGasFeeLegacyUpdate'; +import AnalyticsV2 from '../../../../util/analyticsV2'; +import AppConstants from '../../../../core/AppConstants'; +import { shallowEqual } from '../../../../util/general'; +import { KEYSTONE_TX_CANCELED } from '../../../../constants/error'; +import GlobalAlert from '../../../UI/GlobalAlert'; +import checkIfAddressIsSaved from '../../../../util/checkAddress'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import { createLedgerTransactionModalNavDetails } from '../../../UI/LedgerModals/LedgerTransactionModal'; import { startGasPolling, stopGasPolling, -} from '../../../../../core/GasPolling/GasPolling'; +} from '../../../../core/GasPolling/GasPolling'; import { selectChainId, selectProviderType, selectTicker, - selectRpcUrl, + selectRpcTarget, selectNetworkConfigurations, -} from '../../../../../selectors/networkController'; +} from '../../../../selectors/networkController'; import { selectConversionRate, selectCurrentCurrency, selectNativeCurrency, -} from '../../../../../selectors/currencyRateController'; -import { selectTokensLength } from '../../../../../selectors/tokensController'; +} from '../../../../selectors/currencyRateController'; +import { selectTokensLength } from '../../../../selectors/tokensController'; import { selectAccounts, selectAccountsLength, -} from '../../../../../selectors/accountTrackerController'; -import ShowBlockExplorer from '../../components/ApproveTransactionReview/ShowBlockExplorer'; +} from '../../../../selectors/accountTrackerController'; +import ShowBlockExplorer from '../../../UI/ApproveTransactionReview/ShowBlockExplorer'; import createStyles from './styles'; import { ethErrors } from 'eth-rpc-errors'; -import { getLedgerKeyring } from '../../../../../core/Ledger/Ledger'; -import ExtendedKeyringTypes from '../../../../../constants/keyringTypes'; -import { updateTransaction } from '../../../../../util/transaction-controller'; +import { getLedgerKeyring } from '../../../../core/Ledger/Ledger'; +import ExtendedKeyringTypes from '../../../../constants/keyringTypes'; const EDIT = 'edit'; const REVIEW = 'review'; @@ -535,7 +531,7 @@ class Approve extends PureComponent { const fullTx = transactions.find(({ id }) => id === transaction.id); const updatedTx = { ...fullTx, transaction }; - await updateTransaction(updatedTx); + await TransactionController.updateTransaction(updatedTx); await KeyringController.resetQRKeyringState(); // For Ledger Accounts we handover the signing to the confirmation flow @@ -903,7 +899,7 @@ const mapStateToProps = (state) => ({ showCustomNonce: state.settings.showCustomNonce, addressBook: state.engine.backgroundState.AddressBookController.addressBook, providerType: selectProviderType(state), - providerRpcTarget: selectRpcUrl(state), + providerRpcTarget: selectRpcTarget(state), networkConfigurations: selectNetworkConfigurations(state), }); diff --git a/app/components/Views/confirmations/ApproveView/Approve/index.test.tsx b/app/components/Views/ApproveView/Approve/index.test.tsx similarity index 86% rename from app/components/Views/confirmations/ApproveView/Approve/index.test.tsx rename to app/components/Views/ApproveView/Approve/index.test.tsx index dee1384b50e..cce80f4adb1 100644 --- a/app/components/Views/confirmations/ApproveView/Approve/index.test.tsx +++ b/app/components/Views/ApproveView/Approve/index.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; import { shallow } from 'enzyme'; -import Approve from '.'; +import Approve from './'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/ApproveView/Approve/styles.ts b/app/components/Views/ApproveView/Approve/styles.ts similarity index 100% rename from app/components/Views/confirmations/ApproveView/Approve/styles.ts rename to app/components/Views/ApproveView/Approve/styles.ts diff --git a/app/components/Views/Asset/ActivityHeader.styles.tsx b/app/components/Views/Asset/ActivityHeader.styles.tsx index 2edbd84f17c..be6b27fe9d3 100644 --- a/app/components/Views/Asset/ActivityHeader.styles.tsx +++ b/app/components/Views/Asset/ActivityHeader.styles.tsx @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { theme: Theme }) => { diff --git a/app/components/Views/Asset/index.js b/app/components/Views/Asset/index.js index b68c7a1f7bf..a698b9999b0 100644 --- a/app/components/Views/Asset/index.js +++ b/app/components/Views/Asset/index.js @@ -32,7 +32,7 @@ import { selectChainId, selectNetworkId, selectNetworkConfigurations, - selectRpcUrl, + selectRpcTarget, } from '../../../selectors/networkController'; import { selectTokens } from '../../../selectors/tokensController'; import { sortTransactions } from '../../../util/activity'; @@ -60,11 +60,11 @@ import { selectIdentities, selectSelectedAddress, } from '../../../selectors/preferencesController'; +import Engine from '../../../core/Engine'; import { TOKEN_OVERVIEW_BUY_BUTTON, TOKEN_OVERVIEW_SWAP_BUTTON, } from '../../../../wdio/screen-objects/testIDs/Screens/TokenOverviewScreen.testIds'; -import { updateIncomingTransactions } from '../../../util/transaction-controller'; const createStyles = (colors) => StyleSheet.create({ @@ -170,7 +170,7 @@ class Asset extends PureComponent { * Object that represents the current route info like params passed to it */ route: PropTypes.object, - rpcUrl: PropTypes.string, + rpcTarget: PropTypes.string, networkConfigurations: PropTypes.object, /** * Boolean that indicates if native token is supported to buy @@ -196,13 +196,13 @@ class Asset extends PureComponent { navAddress = undefined; updateNavBar = (contentOffset = 0) => { - const { navigation, route, chainId, rpcUrl, networkConfigurations } = + const { navigation, route, chainId, rpcTarget, networkConfigurations } = this.props; const colors = this.context.colors || mockTheme.colors; const isNativeToken = route.params.isETH; const isMainnet = isMainnetByChainId(chainId); const blockExplorer = findBlockExplorerForRpc( - rpcUrl, + rpcTarget, networkConfigurations, ); @@ -441,9 +441,11 @@ class Asset extends PureComponent { }; onRefresh = async () => { + const { TransactionController } = Engine.context; + this.setState({ refreshing: true }); - await updateIncomingTransactions(); + await TransactionController.updateIncomingTransactions(); this.setState({ refreshing: false }); }; @@ -587,7 +589,7 @@ const mapStateToProps = (state) => ({ tokens: selectTokens(state), networkId: selectNetworkId(state), transactions: state.engine.backgroundState.TransactionController.transactions, - rpcUrl: selectRpcUrl(state), + rpcTarget: selectRpcTarget(state), networkConfigurations: selectNetworkConfigurations(state), isNetworkBuyNativeTokenSupported: isNetworkRampNativeTokenSupported( selectChainId(state), diff --git a/app/components/Views/AssetDetails/index.tsx b/app/components/Views/AssetDetails/index.tsx index 58a233599da..9ee39d6a8a9 100644 --- a/app/components/Views/AssetDetails/index.tsx +++ b/app/components/Views/AssetDetails/index.tsx @@ -27,7 +27,7 @@ import { balanceToFiat, renderFromTokenMinimalUnit, } from '../../../util/number'; -import WarningMessage from '../confirmations/SendFlow/WarningMessage'; +import WarningMessage from '../SendFlow/WarningMessage'; import { useTheme } from '../../../util/theme'; import { MetaMetricsEvents } from '../../../core/Analytics'; import AnalyticsV2 from '../../../util/analyticsV2'; diff --git a/app/components/Views/AssetOptions/AssetOptions.styles.ts b/app/components/Views/AssetOptions/AssetOptions.styles.ts index 4ca2e5004ac..31445ae5014 100644 --- a/app/components/Views/AssetOptions/AssetOptions.styles.ts +++ b/app/components/Views/AssetOptions/AssetOptions.styles.ts @@ -1,4 +1,4 @@ -import type { Theme } from '@metamask/design-tokens'; +import { Theme } from '@metamask/design-tokens'; import { StyleSheet, TextStyle } from 'react-native'; const styleSheet = (params: { theme: Theme }) => { diff --git a/app/components/Views/BrowserTab/index.js b/app/components/Views/BrowserTab/index.js index cea53ff6d75..a40a5eee363 100644 --- a/app/components/Views/BrowserTab/index.js +++ b/app/components/Views/BrowserTab/index.js @@ -101,7 +101,6 @@ import { TextVariant } from '../../../component-library/components/Texts/Text'; import { regex } from '../../../../app/util/regex'; import { selectChainId } from '../../../selectors/networkController'; import { BrowserViewSelectorsIDs } from '../../../../e2e/selectors/BrowserView.selectors'; -import { trackDappVisitedEvent } from '../../../analytics'; const { HOMEPAGE_URL, NOTIFICATION_NAMES } = AppConstants; const HOMEPAGE_HOST = new URL(HOMEPAGE_URL)?.hostname; @@ -259,7 +258,7 @@ export const BrowserTab = (props) => { const [progress, setProgress] = useState(0); const [initialUrl, setInitialUrl] = useState(''); const [firstUrlLoaded, setFirstUrlLoaded] = useState(false); - const [error, setError] = useState(false); + const [error, setError] = useState(null); const [showOptions, setShowOptions] = useState(false); const [entryScriptWeb3, setEntryScriptWeb3] = useState(null); const [showPhishingModal, setShowPhishingModal] = useState(false); @@ -533,27 +532,6 @@ export const BrowserTab = (props) => { [goBack, props.ipfsGateway, setIpfsBannerVisible, props.chainId], ); - const triggerDappVisitedEvent = (url) => { - const permissionsControllerState = - Engine.context.PermissionController.state; - const hostname = new URL(url).hostname; - const connectedAccounts = getPermittedAccountsByHostname( - permissionsControllerState, - hostname, - ); - - // Check if there are any connected accounts - if (!connectedAccounts.length) { - return; - } - - // Track dapp visited event - trackDappVisitedEvent({ - hostname, - numberOfConnectedAccounts: connectedAccounts.length, - }); - }; - /** * Go to a url */ @@ -596,11 +574,6 @@ export const BrowserTab = (props) => { ); } - // Skip tracking on initial open - if (!initialCall) { - triggerDappVisitedEvent(urlToGo); - } - setProgress(0); return prefixedUrl; } @@ -629,7 +602,6 @@ export const BrowserTab = (props) => { const { current } = webviewRef; current && current.reload(); - triggerDappVisitedEvent(url.current); }, []); /** @@ -911,15 +883,10 @@ export const BrowserTab = (props) => { setProgress(progress); }; - // We need to be sure we can remove this property https://github.com/react-native-webview/react-native-webview/issues/2970 - // We should check if this is fixed on the newest versions of react-native-webview const onLoad = ({ nativeEvent }) => { //For iOS url on the navigation bar should only update upon load. if (Device.isIos()) { - const { origin, pathname = '', query = '' } = new URL(nativeEvent.url); - const realUrl = `${origin}${pathname}${query}`; - changeUrl({ ...nativeEvent, url: realUrl, icon: favicon }); - changeAddressBar({ ...nativeEvent, url: realUrl, icon: favicon }); + changeUrl(nativeEvent); } }; @@ -931,6 +898,13 @@ export const BrowserTab = (props) => { if (nativeEvent.loading) { return; } + // Use URL to produce real url. This should be the actual website that the user is viewing. + const urlObj = new URL(nativeEvent.url); + const { origin, pathname = '', query = '' } = urlObj; + const realUrl = `${origin}${pathname}${query}`; + // Update navigation bar address with title of loaded url. + changeUrl({ ...nativeEvent, url: realUrl, icon: favicon }); + changeAddressBar({ ...nativeEvent, url: realUrl, icon: favicon }); }; /** @@ -1057,13 +1031,25 @@ export const BrowserTab = (props) => { * Website started to load */ const onLoadStart = async ({ nativeEvent }) => { - // Use URL to produce real url. This should be the actual website that the user is viewing. - const { - origin, - pathname = '', - query = '', - hostname, - } = new URL(nativeEvent.url); + const { hostname } = new URL(nativeEvent.url); + + if ( + nativeEvent.url !== url.current && + nativeEvent.loading && + nativeEvent.navigationType === 'backforward' + ) { + changeAddressBar({ ...nativeEvent }); + } + + setError(false); + + changeUrl(nativeEvent); + sendActiveAccount(); + + icon.current = null; + if (isHomepage(nativeEvent.url)) { + injectHomePageScripts(); + } // Reset the previous bridges backgroundBridges.current.length && @@ -1075,21 +1061,8 @@ export const BrowserTab = (props) => { return false; } - const realUrl = `${origin}${pathname}${query}`; - if (nativeEvent.url !== url.current) { - // Update navigation bar address with title of loaded url. - changeUrl({ ...nativeEvent, url: realUrl, icon: favicon }); - changeAddressBar({ ...nativeEvent, url: realUrl, icon: favicon }); - } - - sendActiveAccount(); - - icon.current = null; - if (isHomepage(nativeEvent.url)) { - injectHomePageScripts(); - } - backgroundBridges.current = []; + const origin = new URL(nativeEvent.url).origin; initializeBackgroundBridge(origin, true); }; diff --git a/app/components/Views/ChoosePassword/index.js b/app/components/Views/ChoosePassword/index.js index 547b0d1f43c..cb3e8fc8ca8 100644 --- a/app/components/Views/ChoosePassword/index.js +++ b/app/components/Views/ChoosePassword/index.js @@ -8,6 +8,7 @@ import { SafeAreaView, StyleSheet, Image, + InteractionManager, } from 'react-native'; import CheckBox from '@react-native-community/checkbox'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; @@ -54,6 +55,7 @@ import { import { CHOOSE_PASSWORD_STEPS } from '../../../constants/onboarding'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { Authentication } from '../../../core'; import AUTHENTICATION_TYPE from '../../../constants/userProperties'; import { ThemeContext, mockTheme } from '../../../util/theme'; @@ -62,7 +64,6 @@ import AnimatedFox from 'react-native-animated-fox'; import { LoginOptionsSwitch } from '../../UI/LoginOptionsSwitch'; import navigateTermsOfUse from '../../../util/termsOfUse/termsOfUse'; import { ChoosePasswordSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ChoosePassword.selectors'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; const createStyles = (colors) => StyleSheet.create({ @@ -259,12 +260,6 @@ class ChoosePassword extends PureComponent { // Flag to know if password in keyring was set or not keyringControllerPasswordSet = false; - track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('ChoosePassword', `Failed to track ${event}`); - }); - }; - updateNavBar = () => { const { route, navigation } = this.props; const colors = this.context.colors || mockTheme.colors; @@ -343,7 +338,9 @@ class ChoosePassword extends PureComponent { Alert.alert('Error', strings('choose_password.password_dont_match')); return; } - this.track(MetaMetricsEvents.WALLET_CREATION_ATTEMPTED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_CREATION_ATTEMPTED); + }); try { this.setState({ loading: true }); @@ -370,12 +367,14 @@ class ChoosePassword extends PureComponent { this.props.setLockTime(AppConstants.DEFAULT_LOCK_TIMEOUT); this.setState({ loading: false }); this.props.navigation.replace('AccountBackupStep1'); - this.track(MetaMetricsEvents.WALLET_CREATED, { - biometrics_enabled: Boolean(this.state.biometryType), - }); - this.track(MetaMetricsEvents.WALLET_SETUP_COMPLETED, { - wallet_setup_type: 'new', - new_wallet: true, + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_CREATED, { + biometrics_enabled: Boolean(this.state.biometryType), + }); + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SETUP_COMPLETED, { + wallet_setup_type: 'new', + new_wallet: true, + }); }); } catch (error) { try { @@ -398,9 +397,11 @@ class ChoosePassword extends PureComponent { } else { this.setState({ loading: false, error: error.toString() }); } - this.track(MetaMetricsEvents.WALLET_SETUP_FAILURE, { - wallet_setup_type: 'new', - error_type: error.toString(), + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SETUP_FAILURE, { + wallet_setup_type: 'new', + error_type: error.toString(), + }); }); } }; diff --git a/app/components/Views/ConnectHardware/SelectHardware/index.tsx b/app/components/Views/ConnectHardware/SelectHardware/index.tsx index 4ce99c7e148..5181d895613 100644 --- a/app/components/Views/ConnectHardware/SelectHardware/index.tsx +++ b/app/components/Views/ConnectHardware/SelectHardware/index.tsx @@ -1,30 +1,27 @@ /* eslint @typescript-eslint/no-var-requires: "off" */ /* eslint @typescript-eslint/no-require-imports: "off" */ -import { useNavigation } from '@react-navigation/native'; import React, { useEffect } from 'react'; import { - Image, + View, SafeAreaView, StyleSheet, TouchableOpacity, - View, + Image, } from 'react-native'; -import { strings } from '../../../../../locales/i18n'; -import Text, { - TextVariant, -} from '../../../../component-library/components/Texts/Text'; -import Routes from '../../../../constants/navigation/Routes'; -import { MetaMetricsEvents } from '../../../../core/Analytics'; -import { getLedgerKeyring } from '../../../../core/Ledger/Ledger'; -import { fontStyles } from '../../../../styles/common'; -import AnalyticsV2 from '../../../../util/analyticsV2'; +import { useNavigation } from '@react-navigation/native'; import { mockTheme, useAppThemeFromContext, useAssetFromTheme, } from '../../../../util/theme'; import { getNavigationOptionsTitle } from '../../../UI/Navbar'; +import { fontStyles } from '../../../../styles/common'; +import { strings } from '../../../../../locales/i18n'; +import Routes from '../../../../constants/navigation/Routes'; +import Text, { + TextVariant, +} from '../../../../component-library/components/Texts/Text'; const createStyle = (colors: any) => StyleSheet.create({ @@ -69,13 +66,6 @@ const createStyle = (colors: any) => }, }); -// Ledger Logo -const ledgerLogoLightImgPath = 'images/ledger-light.png'; -const ledgerLogoLight = require(ledgerLogoLightImgPath); - -const ledgerLogoDarkImgPath = 'images/ledger-dark.png'; -const ledgerLogoDark = require(ledgerLogoDarkImgPath); - // QR Hardware Logo const qrHardwareLogoLightImgPath = 'images/qrhardware-light.png'; const qrHardwareLogoLight = require(qrHardwareLogoLightImgPath); @@ -103,37 +93,12 @@ const SelectHardwareWallet = () => { navigation.navigate(Routes.HW.CONNECT_QR_DEVICE); }; - const navigateToConnectLedger = async () => { - const ledgerKeyring = await getLedgerKeyring(); - const accounts = await ledgerKeyring.getAccounts(); - - AnalyticsV2.trackEvent(MetaMetricsEvents.CONNECT_LEDGER, { - device_type: 'Ledger', - }); - - if (accounts.length === 0) { - navigation.navigate(Routes.HW.CONNECT_LEDGER); - } else { - navigation.navigate(Routes.HW.LEDGER_ACCOUNT, { - screen: Routes.HW.LEDGER_ACCOUNT, - params: { - accounts, - }, - }); - } - }; - const renderHardwareButton = (image: any, onPress: any) => ( ); - const LedgerButton = () => { - const ledgerLogo = useAssetFromTheme(ledgerLogoLight, ledgerLogoDark); - return renderHardwareButton(ledgerLogo, navigateToConnectLedger); - }; - const QRButton = () => { const qrHardwareLogo = useAssetFromTheme( qrHardwareLogoLight, @@ -150,7 +115,6 @@ const SelectHardwareWallet = () => { - diff --git a/app/components/Views/EditAccountName/EditAccountName.test.tsx b/app/components/Views/EditAccountName/EditAccountName.test.tsx index ac1810c6066..cc7fe1c8158 100644 --- a/app/components/Views/EditAccountName/EditAccountName.test.tsx +++ b/app/components/Views/EditAccountName/EditAccountName.test.tsx @@ -18,7 +18,7 @@ jest.mock('../../../core/Engine', () => ({ })); const mockInitialState = { - swaps: { '0x1': { isLive: true }, hasOnboarded: false, isLive: true }, + swaps: { '1': { isLive: true }, hasOnboarded: false, isLive: true }, wizard: { step: 0, }, diff --git a/app/components/Views/EditAccountName/EditAccountName.tsx b/app/components/Views/EditAccountName/EditAccountName.tsx index 20b2ddc1e06..3f204b25396 100644 --- a/app/components/Views/EditAccountName/EditAccountName.tsx +++ b/app/components/Views/EditAccountName/EditAccountName.tsx @@ -37,7 +37,6 @@ import { useTheme } from '../../../util/theme'; // Internal dependencies import styleSheet from './EditAccountName.styles'; -import { getDecimalChainId } from '../../../util/networks'; const EditAccountName = () => { const { colors } = useTheme(); @@ -91,7 +90,7 @@ const EditAccountName = () => { const analyticsProperties = async () => { const accountType = getAddressAccountType(selectedAddress); const account_type = accountType === 'QR' ? 'hardware' : accountType; - return { account_type, chain_id: getDecimalChainId(chainId) }; + return { account_type, chain_id: chainId }; }; Analytics.trackEventWithParameters( MetaMetricsEvents.ACCOUNT_RENAMED, diff --git a/app/components/Views/EditAccountName/__snapshots__/EditAccountName.test.tsx.snap b/app/components/Views/EditAccountName/__snapshots__/EditAccountName.test.tsx.snap index 1e786368a12..dd78f8e24e8 100644 --- a/app/components/Views/EditAccountName/__snapshots__/EditAccountName.test.tsx.snap +++ b/app/components/Views/EditAccountName/__snapshots__/EditAccountName.test.tsx.snap @@ -244,7 +244,7 @@ exports[`EditAccountName should render correctly 1`] = ` accessibilityRole="text" style={ Object { - "color": "#FFFFFF", + "color": "#FCFCFC", "fontFamily": "Euclid Circular B", "fontSize": 14, "fontWeight": "400", diff --git a/app/components/Views/ImportFromSecretRecoveryPhrase/index.js b/app/components/Views/ImportFromSecretRecoveryPhrase/index.js index 381908cd031..80bf58caca2 100644 --- a/app/components/Views/ImportFromSecretRecoveryPhrase/index.js +++ b/app/components/Views/ImportFromSecretRecoveryPhrase/index.js @@ -8,6 +8,7 @@ import { View, TextInput, SafeAreaView, + InteractionManager, Platform, } from 'react-native'; import { connect } from 'react-redux'; @@ -34,6 +35,7 @@ import { } from '../../../util/password'; import importAdditionalAccounts from '../../../util/importAdditionalAccounts'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { useTheme } from '../../../util/theme'; import { passwordSet, seedphraseBackedUp } from '../../../actions/user'; @@ -63,7 +65,6 @@ import { import navigateTermsOfUse from '../../../util/termsOfUse/termsOfUse'; import { ImportFromSeedSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ImportFromSeed.selectors'; import { ChoosePasswordSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ChoosePassword.selectors'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; const MINIMUM_SUPPORTED_CLIPBOARD_VERSION = 9; @@ -104,12 +105,6 @@ const ImportFromSecretRecoveryPhrase = ({ const passwordInput = React.createRef(); const confirmPasswordInput = React.createRef(); - const track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('ImportFromSecretRecoveryPhrase', `Failed to track ${event}`); - }); - }; - const updateNavBar = () => { navigation.setOptions(getOnboardingNavbarOptions(route, {}, colors)); }; @@ -189,7 +184,9 @@ const ImportFromSecretRecoveryPhrase = ({ setSeed(parsedSeed); if (loading) return; - track(MetaMetricsEvents.WALLET_IMPORT_ATTEMPTED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_IMPORT_ATTEMPTED); + }); let error = null; if (!passwordRequirementsMet(password)) { error = strings('import_from_seed.password_length_error'); @@ -205,9 +202,11 @@ const ImportFromSecretRecoveryPhrase = ({ if (error) { Alert.alert(strings('import_from_seed.error'), error); - track(MetaMetricsEvents.WALLET_SETUP_FAILURE, { - wallet_setup_type: 'import', - error_type: error, + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SETUP_FAILURE, { + wallet_setup_type: 'import', + error_type: error, + }); }); } else { try { @@ -235,12 +234,14 @@ const ImportFromSecretRecoveryPhrase = ({ passwordSet(); setLockTime(AppConstants.DEFAULT_LOCK_TIMEOUT); seedphraseBackedUp(); - track(MetaMetricsEvents.WALLET_IMPORTED, { - biometrics_enabled: Boolean(biometryType), - }); - track(MetaMetricsEvents.WALLET_SETUP_COMPLETED, { - wallet_setup_type: 'import', - new_wallet: false, + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_IMPORTED, { + biometrics_enabled: Boolean(biometryType), + }); + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SETUP_COMPLETED, { + wallet_setup_type: 'import', + new_wallet: false, + }); }); if (onboardingWizard) { navigation.replace(Routes.ONBOARDING.MANUAL_BACKUP.STEP_3); @@ -264,9 +265,11 @@ const ImportFromSecretRecoveryPhrase = ({ setError(error.message); Logger.log('Error with seed phrase import', error.message); } - track(MetaMetricsEvents.WALLET_SETUP_FAILURE, { - wallet_setup_type: 'import', - error_type: error.toString(), + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SETUP_FAILURE, { + wallet_setup_type: 'import', + error_type: error.toString(), + }); }); } } diff --git a/app/components/Views/ImportPrivateKeySuccess/__snapshots__/index.test.tsx.snap b/app/components/Views/ImportPrivateKeySuccess/__snapshots__/index.test.tsx.snap index 9ba37139c0b..12ad2e4786e 100644 --- a/app/components/Views/ImportPrivateKeySuccess/__snapshots__/index.test.tsx.snap +++ b/app/components/Views/ImportPrivateKeySuccess/__snapshots__/index.test.tsx.snap @@ -65,7 +65,7 @@ exports[`ImportPrivateKeySuccess should render correctly 1`] = ` > { const toBlockExplorer = useCallback( (address: string) => { - const { type, rpcUrl } = provider; + const { type, rpcTarget } = provider; let accountLink: string; if (type === RPC) { const blockExplorer = - findBlockExplorerForRpc(rpcUrl, frequentRpcList) || + findBlockExplorerForRpc(rpcTarget, frequentRpcList) || NO_RPC_BLOCK_EXPLORER; accountLink = `${blockExplorer}/address/${address}`; } else { diff --git a/app/components/Views/LedgerConnect/Scan.test.tsx b/app/components/Views/LedgerConnect/Scan.test.tsx index 5fc2d17f286..3962ce78e64 100644 --- a/app/components/Views/LedgerConnect/Scan.test.tsx +++ b/app/components/Views/LedgerConnect/Scan.test.tsx @@ -7,14 +7,6 @@ import configureMockStore from 'redux-mock-store'; const mockStore = configureMockStore(); const store = mockStore({}); -jest.mock('react-native-ble-plx', () => ({ - BleManager: () => ({ - onStateChange: () => ({ - remove: jest.fn(), - }), - }), -})); - describe('Scan', () => { it('should render correctly', () => { const wrapper = shallow( diff --git a/app/components/Views/LedgerConnect/index.test.tsx b/app/components/Views/LedgerConnect/index.test.tsx index 2cc9011d82b..ce4f6d50226 100644 --- a/app/components/Views/LedgerConnect/index.test.tsx +++ b/app/components/Views/LedgerConnect/index.test.tsx @@ -8,8 +8,6 @@ import configureMockStore from 'redux-mock-store'; const mockStore = configureMockStore(); const store = mockStore({}); -jest.mock('@ledgerhq/react-native-hw-transport-ble', () => null); - jest.mock('../../../core/Engine', () => ({ context: { KeyringController: { diff --git a/app/components/Views/LedgerConnect/index.tsx b/app/components/Views/LedgerConnect/index.tsx index 4c2e53fdd01..efda5df9beb 100644 --- a/app/components/Views/LedgerConnect/index.tsx +++ b/app/components/Views/LedgerConnect/index.tsx @@ -8,7 +8,6 @@ import { ActivityIndicator, } from 'react-native'; import { StackActions, useNavigation } from '@react-navigation/native'; -import { Device as NanoDevice } from '@ledgerhq/react-native-hw-transport-ble/lib/types'; import { useDispatch } from 'react-redux'; import { strings } from '../../../../locales/i18n'; import Engine from '../../../core/Engine'; @@ -116,7 +115,7 @@ const LedgerConnect = () => { const theme = useAppThemeFromContext() ?? mockTheme; const navigation = useNavigation(); const styles = useMemo(() => createStyles(theme), [theme]); - const [selectedDevice, setSelectedDevice] = useState(null); + const [selectedDevice, setSelectedDevice] = useState(null); const [errorDetail, setErrorDetails] = useState(); const [loading, setLoading] = useState(false); const [retryTimes, setRetryTimes] = useState(0); @@ -141,7 +140,7 @@ const LedgerConnect = () => { device_type: 'Ledger', }); ledgerLogicToRun(async () => { - const account = await unlockLedgerDefaultAccount(true); + const account = await unlockLedgerDefaultAccount(); await AccountTrackerController.syncBalanceWithAddresses([account]); AnalyticsV2.trackEvent(MetaMetricsEvents.CONNECT_LEDGER_SUCCESS, { device_type: 'Ledger', @@ -165,7 +164,7 @@ const LedgerConnect = () => { }; const openHowToInstallEthApp = () => { - navigation.navigate('Webview', { + navigation.push('Webview', { screen: 'SimpleWebview', params: { url: LEDGER_SUPPORT_LINK, @@ -323,7 +322,7 @@ const LedgerConnect = () => { type="confirm" onPress={connectLedger} testID={'add-network-button'} - disabled={loading || isSendingLedgerCommands} + disabled={isSendingLedgerCommands} > {loading || isSendingLedgerCommands ? ( diff --git a/app/components/Views/LockScreen/index.js b/app/components/Views/LockScreen/index.js index 96a1542ab28..f8f0284a741 100644 --- a/app/components/Views/LockScreen/index.js +++ b/app/components/Views/LockScreen/index.js @@ -133,15 +133,8 @@ class LockScreen extends PureComponent { async unlockKeychain() { const { bioStateMachineId } = this.props; try { - // Retrieve the credentials + // Retreive the credentials Logger.log('Lockscreen::unlockKeychain - getting credentials'); - - // Log to provide insights into bug research. - // Check https://github.com/MetaMask/mobile-planning/issues/1507 - const { selectedAddress } = this.props; - if (typeof selectedAddress !== 'string') { - Logger.error('unlockKeychain error', 'selectedAddress is not a string'); - } await Authentication.appTriggeredAuth({ selectedAddress: this.props.selectedAddress, bioStateMachineId, diff --git a/app/components/Views/Login/index.js b/app/components/Views/Login/index.js index d7825b3393d..9e109aa3bc8 100644 --- a/app/components/Views/Login/index.js +++ b/app/components/Views/Login/index.js @@ -366,13 +366,6 @@ class Login extends PureComponent { ); try { - // Log to provide insights into bug research. - // Check https://github.com/MetaMask/mobile-planning/issues/1507 - const { selectedAddress } = this.props; - if (typeof selectedAddress !== 'string') { - Logger.error('Login error', 'selectedAddress is not a string'); - } - await Authentication.userEntryAuth( password, authType, @@ -442,12 +435,6 @@ class Login extends PureComponent { const { current: field } = this.fieldRef; field?.blur(); try { - // Log to provide insights into bug research. - // Check https://github.com/MetaMask/mobile-planning/issues/1507 - const { selectedAddress } = this.props; - if (typeof selectedAddress !== 'string') { - Logger.error('unlockKeychain error', 'selectedAddress is not a string'); - } await Authentication.appTriggeredAuth({ selectedAddress: this.props.selectedAddress, }); diff --git a/app/components/Views/ManualBackupStep1/index.js b/app/components/Views/ManualBackupStep1/index.js index c804c305a33..952de38fb1d 100644 --- a/app/components/Views/ManualBackupStep1/index.js +++ b/app/components/Views/ManualBackupStep1/index.js @@ -4,6 +4,7 @@ import { View, SafeAreaView, ActivityIndicator, + InteractionManager, TextInput, KeyboardAvoidingView, Appearance, @@ -14,7 +15,6 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view import FeatherIcons from 'react-native-vector-icons/Feather'; import { BlurView } from '@react-native-community/blur'; import { wordlist } from '@metamask/scure-bip39/dist/wordlists/english'; -import Logger from '../../../util/Logger'; import { baseStyles } from '../../../styles/common'; import StyledButton from '../../UI/StyledButton'; import OnboardingProgress from '../../UI/OnboardingProgress'; @@ -34,8 +34,8 @@ import { uint8ArrayToMnemonic } from '../../../util/mnemonic'; import { createStyles } from './styles'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { Authentication } from '../../../core'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; import { ManualBackUpStepsSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ManualBackUpSteps.selectors'; /** @@ -70,12 +70,6 @@ const ManualBackupStep1 = ({ route, navigation, appTheme }) => { return uint8ArrayToMnemonic(uint8ArrayMnemonic, wordlist).split(' '); }; - const track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('ManualBackupStep1', `Failed to track ${event}`); - }); - }; - useEffect(() => { const getSeedphrase = async () => { if (!words.length) { @@ -87,7 +81,6 @@ const ManualBackupStep1 = ({ route, navigation, appTheme }) => { setView(CONFIRM_PASSWORD); } } catch (e) { - Logger.error('Error trying to recover SRP from keyring-controller'); setView(CONFIRM_PASSWORD); } } @@ -116,7 +109,9 @@ const ManualBackupStep1 = ({ route, navigation, appTheme }) => { const revealSeedPhrase = () => { setSeedPhraseHidden(false); - track(MetaMetricsEvents.WALLET_SECURITY_PHRASE_REVEALED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SECURITY_PHRASE_REVEALED); + }); }; const tryUnlockWithPassword = async (password) => { diff --git a/app/components/Views/ManualBackupStep2/index.js b/app/components/Views/ManualBackupStep2/index.js index 79fc1f626aa..d26f50b0e06 100644 --- a/app/components/Views/ManualBackupStep2/index.js +++ b/app/components/Views/ManualBackupStep2/index.js @@ -18,10 +18,9 @@ import MaterialIcon from 'react-native-vector-icons/MaterialCommunityIcons'; import { getOnboardingNavbarOptions } from '../../UI/Navbar'; import { shuffle, compareMnemonics } from '../../../util/mnemonic'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import { useTheme } from '../../../util/theme'; import createStyles from './styles'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; -import Logger from '../../../util/Logger'; import { ManualBackUpStepsSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ManualBackUpSteps.selectors'; const ManualBackupStep2 = ({ navigation, seedphraseBackedUp, route }) => { @@ -47,12 +46,6 @@ const ManualBackupStep2 = ({ navigation, seedphraseBackedUp, route }) => { setWordsDict(dict); }; - const track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('ManualBackupStep2', `Failed to track ${event}`); - }); - }; - const updateNavBar = useCallback(() => { navigation.setOptions(getOnboardingNavbarOptions(route, {}, colors)); }, [colors, navigation, route]); @@ -130,13 +123,15 @@ const ManualBackupStep2 = ({ navigation, seedphraseBackedUp, route }) => { const goNext = () => { if (validateWords()) { seedphraseBackedUp(); - InteractionManager.runAfterInteractions(async () => { + InteractionManager.runAfterInteractions(() => { const words = route.params?.words; navigation.navigate('ManualBackupStep3', { steps: route.params?.steps, words, }); - track(MetaMetricsEvents.WALLET_SECURITY_PHRASE_CONFIRMED); + AnalyticsV2.trackEvent( + MetaMetricsEvents.WALLET_SECURITY_PHRASE_CONFIRMED, + ); }); } else { Alert.alert( diff --git a/app/components/Views/ManualBackupStep3/index.js b/app/components/Views/ManualBackupStep3/index.js index e71a2767d17..e767cbb02d2 100644 --- a/app/components/Views/ManualBackupStep3/index.js +++ b/app/components/Views/ManualBackupStep3/index.js @@ -7,6 +7,7 @@ import { StyleSheet, Keyboard, TouchableOpacity, + InteractionManager, } from 'react-native'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; @@ -28,10 +29,9 @@ import { SEED_PHRASE_HINTS, } from '../../../constants/storage'; import { MetaMetricsEvents } from '../../../core/Analytics'; +import AnalyticsV2 from '../../../util/analyticsV2'; import DefaultPreference from 'react-native-default-preference'; import { ThemeContext, mockTheme } from '../../../util/theme'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; -import Logger from '../../../util/Logger'; import { ManualBackUpStepsSelectorsIDs } from '../../../../e2e/selectors/Onboarding/ManualBackUpSteps.selectors'; const createStyles = (colors) => @@ -118,12 +118,6 @@ class ManualBackupStep3 extends PureComponent { setOnboardingWizardStep: PropTypes.func, }; - track = (event, properties) => { - trackAfterInteractions(event, properties).catch(() => { - Logger.log('ManualBackupStep3', `Failed to track ${event}`); - }); - }; - updateNavBar = () => { const { navigation } = this.props; const colors = this.context.colors || mockTheme.colors; @@ -145,7 +139,9 @@ class ManualBackupStep3 extends PureComponent { this.setState({ hintText: manualBackup, }); - this.track(MetaMetricsEvents.WALLET_SECURITY_COMPLETED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent(MetaMetricsEvents.WALLET_SECURITY_COMPLETED); + }); BackHandler.addEventListener(HARDWARE_BACK_PRESS, hardwareBackPress); }; @@ -191,7 +187,11 @@ class ManualBackupStep3 extends PureComponent { SEED_PHRASE_HINTS, JSON.stringify({ ...parsedHints, manualBackup: hintText }), ); - this.track(MetaMetricsEvents.WALLET_SECURITY_RECOVERY_HINT_SAVED); + InteractionManager.runAfterInteractions(() => { + AnalyticsV2.trackEvent( + MetaMetricsEvents.WALLET_SECURITY_RECOVERY_HINT_SAVED, + ); + }); }; done = async () => { diff --git a/app/components/Views/NetworkSelector/NetworkSelector.test.tsx b/app/components/Views/NetworkSelector/NetworkSelector.test.tsx index 6c8f9df227f..ab737d93190 100644 --- a/app/components/Views/NetworkSelector/NetworkSelector.test.tsx +++ b/app/components/Views/NetworkSelector/NetworkSelector.test.tsx @@ -55,18 +55,18 @@ const initialState = { type: 'mainnet', nickname: 'Ethereum mainnet', ticket: 'eth', - chainId: '0x1', + chainId: '1', }, networkConfigurations: { networkId1: { - chainId: '0xa86a', + chainId: '43114', nickname: 'Avalanche Mainnet C-Chain', rpcPrefs: { blockExplorerUrl: 'https://snowtrace.io' }, rpcUrl: 'https://api.avax.network/ext/bc/C/rpc', ticker: 'AVAX', }, networkId2: { - chainId: '0x89', + chainId: '137', nickname: 'Polygon Mainnet', rpcPrefs: { blockExplorerUrl: 'https://polygonscan.com' }, rpcUrl: @@ -74,7 +74,7 @@ const initialState = { ticker: 'MATIC', }, networkId3: { - chainId: '0xa', + chainId: '10', nickname: 'Optimism', rpcPrefs: { blockExplorerUrl: 'https://optimistic.etherscan.io' }, rpcUrl: @@ -82,7 +82,7 @@ const initialState = { ticker: 'ETH', }, networkId4: { - chainId: '0x64', + chainId: '100', nickname: 'Gnosis Chain', rpcPrefs: { blockExplorerUrl: 'https://blockscout.com/xdai/mainnet/', @@ -104,8 +104,8 @@ const initialState = { }, }, NftController: { - allNfts: { '0x': { '0x1': [] } }, - allNftContracts: { '0x': { '0x1': [] } }, + allNfts: { '0x': { '1': [] } }, + allNftContracts: { '0x': { '1': [] } }, }, }, }, @@ -160,7 +160,7 @@ describe('Network Selector', () => { type: 'mainnet', nickname: 'Goerli mainnet', ticket: 'eth', - chainId: '0x5', + chainId: '5', }, }, }, diff --git a/app/components/Views/NetworkSelector/NetworkSelector.tsx b/app/components/Views/NetworkSelector/NetworkSelector.tsx index 15f70fa600c..511472e8660 100644 --- a/app/components/Views/NetworkSelector/NetworkSelector.tsx +++ b/app/components/Views/NetworkSelector/NetworkSelector.tsx @@ -25,7 +25,6 @@ import { selectShowTestNetworks } from '../../../selectors/preferencesController import Networks, { compareRpcUrls, getAllNetworks, - getDecimalChainId, getNetworkImageSource, isTestNet, } from '../../../util/networks'; @@ -52,7 +51,6 @@ import { TextColor, TextVariant, } from '../../../component-library/components/Texts/Text'; -import { updateIncomingTransactions } from '../../../util/transaction-controller'; // Internal dependencies import styles from './NetworkSelector.styles'; @@ -68,24 +66,20 @@ const NetworkSelector = () => { const networkConfigurations = useSelector(selectNetworkConfigurations); const onNetworkChange = (type: string) => { - const { - NetworkController, - CurrencyRateController, - AccountTrackerController, - } = Engine.context; + const { NetworkController, CurrencyRateController, TransactionController } = + Engine.context; CurrencyRateController.setNativeCurrency('ETH'); NetworkController.setProviderType(type); - AccountTrackerController.refresh(); setTimeout(async () => { - await updateIncomingTransactions(); + await TransactionController.updateIncomingTransactions(); }, 1000); sheetRef.current?.onCloseBottomSheet(); analyticsV2.trackEvent(MetaMetricsEvents.NETWORK_SWITCHED, { - chain_id: getDecimalChainId(providerConfig.chainId), + chain_id: providerConfig.chainId, from_network: providerConfig.type === 'rpc' ? providerConfig.nickname @@ -111,7 +105,7 @@ const NetworkSelector = () => { sheetRef.current?.onCloseBottomSheet(); analyticsV2.trackEvent(MetaMetricsEvents.NETWORK_SWITCHED, { - chain_id: getDecimalChainId(providerConfig.chainId), + chain_id: providerConfig.chainId, from_network: providerConfig.type, to_network: nickname, }); @@ -130,7 +124,8 @@ const NetworkSelector = () => { imageSource: images.ETHEREUM, }} isSelected={ - chainId === providerConfig.chainId && !providerConfig.rpcUrl + chainId.toString() === providerConfig.chainId && + !providerConfig.rpcTarget } onPress={() => onNetworkChange(MAINNET)} style={styles.networkCell} @@ -149,7 +144,7 @@ const NetworkSelector = () => { name: lineaMainnetName, imageSource: images['LINEA-MAINNET'], }} - isSelected={chainId === providerConfig.chainId} + isSelected={chainId.toString() === providerConfig.chainId} onPress={() => onNetworkChange(LINEA_MAINNET)} /> ); @@ -174,7 +169,8 @@ const NetworkSelector = () => { imageSource: image, }} isSelected={Boolean( - chainId === providerConfig.chainId && providerConfig.rpcUrl, + chainId.toString() === providerConfig.chainId && + providerConfig.rpcTarget, )} onPress={() => onSetRpcTarget(rpcUrl)} style={styles.networkCell} @@ -199,7 +195,7 @@ const NetworkSelector = () => { name, imageSource, }} - isSelected={chainId === providerConfig.chainId} + isSelected={chainId.toString() === providerConfig.chainId} onPress={() => onNetworkChange(networkType)} style={styles.networkCell} /> diff --git a/app/components/Views/Onboarding/index.js b/app/components/Views/Onboarding/index.js index bd95e63f98e..f54be07c796 100644 --- a/app/components/Views/Onboarding/index.js +++ b/app/components/Views/Onboarding/index.js @@ -26,6 +26,7 @@ import { strings } from '../../../../locales/i18n'; import Button from '@metamask/react-native-button'; import { connect } from 'react-redux'; import FadeOutOverlay from '../../UI/FadeOutOverlay'; +import Analytics from '../../../core/Analytics/Analytics'; import { saveOnboardingEvent } from '../../../actions/onboarding'; import { getTransparentBackOnboardingNavbarOptions, @@ -38,9 +39,11 @@ import { loadingSet, loadingUnset } from '../../../actions/user'; import PreventScreenshot from '../../../core/PreventScreenshot'; import WarningExistingUserModal from '../../UI/WarningExistingUserModal'; import { PREVIOUS_SCREEN, ONBOARDING } from '../../../constants/navigation'; -import { EXISTING_USER } from '../../../constants/storage'; +import { EXISTING_USER, METRICS_OPT_IN } from '../../../constants/storage'; import { MetaMetricsEvents } from '../../../core/Analytics'; -import { withMetricsAwareness } from '../../hooks/useMetrics'; +import AnalyticsV2 from '../../../util/analyticsV2'; + +import DefaultPreference from 'react-native-default-preference'; import { Authentication } from '../../../core'; import { ThemeContext, mockTheme } from '../../../util/theme'; import AnimatedFox from 'react-native-animated-fox'; @@ -161,10 +164,6 @@ class Onboarding extends PureComponent { * Object that represents the current route info like params passed to it */ route: PropTypes.object, - /** - * Metrics injected by withMetricsAwareness HOC - */ - metrics: PropTypes.object, }; notificationAnimated = new Animated.Value(100); @@ -277,8 +276,8 @@ class Onboarding extends PureComponent { onPressCreate = () => { const action = async () => { - const { metrics } = this.props; - if (metrics.isEnabled()) { + const metricsOptIn = await DefaultPreference.get(METRICS_OPT_IN); + if (metricsOptIn) { this.props.navigation.navigate('ChoosePassword', { [PREVIOUS_SCREEN]: ONBOARDING, }); @@ -299,8 +298,8 @@ class Onboarding extends PureComponent { onPressImport = () => { const action = async () => { - const { metrics } = this.props; - if (metrics.isEnabled()) { + const metricsOptIn = await DefaultPreference.get(METRICS_OPT_IN); + if (metricsOptIn) { this.props.navigation.push( Routes.ONBOARDING.IMPORT_FROM_SECRET_RECOVERY_PHRASE, ); @@ -319,13 +318,15 @@ class Onboarding extends PureComponent { this.handleExistingUser(action); }; - track = (event) => { + track = (...eventArgs) => { InteractionManager.runAfterInteractions(async () => { - const { metrics } = this.props; - if (metrics.isEnabled()) { - metrics.trackEvent(event); - } else { - this.props.saveOnboardingEvent(event.category); + if (Analytics.checkEnabled()) { + AnalyticsV2.trackEvent(...eventArgs); + return; + } + const metricsOptIn = await DefaultPreference.get(METRICS_OPT_IN); + if (!metricsOptIn) { + this.props.saveOnboardingEvent(eventArgs); } }); }; @@ -499,7 +500,4 @@ const mapDispatchToProps = (dispatch) => ({ saveOnboardingEvent: (event) => dispatch(saveOnboardingEvent(event)), }); -export default connect( - mapStateToProps, - mapDispatchToProps, -)(withMetricsAwareness(Onboarding)); +export default connect(mapStateToProps, mapDispatchToProps)(Onboarding); diff --git a/app/components/Views/OnboardingCarousel/index.js b/app/components/Views/OnboardingCarousel/index.js index 248e1c6ac9b..0a9932838a8 100644 --- a/app/components/Views/OnboardingCarousel/index.js +++ b/app/components/Views/OnboardingCarousel/index.js @@ -7,6 +7,7 @@ import { StyleSheet, Image, Dimensions, + InteractionManager, Platform, } from 'react-native'; import { MetaMetricsEvents } from '../../../core/Analytics'; @@ -20,12 +21,13 @@ import OnboardingScreenWithBg from '../../UI/OnboardingScreenWithBg'; import Device from '../../../util/device'; import { saveOnboardingEvent } from '../../../actions/onboarding'; import { connect } from 'react-redux'; +import AnalyticsV2 from '../../../util/analyticsV2'; +import DefaultPreference from 'react-native-default-preference'; +import { METRICS_OPT_IN } from '../../../constants/storage'; import { ThemeContext, mockTheme } from '../../../util/theme'; import { WELCOME_SCREEN_CAROUSEL_TITLE_ID } from '../../../../wdio/screen-objects/testIDs/Screens/WelcomeScreen.testIds'; import { OnboardingCarouselSelectorIDs } from '../../../../e2e/selectors/Onboarding/OnboardingCarousel.selectors'; import generateTestId from '../../../../wdio/utils/generateTestId'; -import trackAfterInteractions from '../../../util/metrics/TrackAfterInteraction/trackAfterInteractions'; -import Logger from '../../../util/Logger'; const IMAGE_3_RATIO = 215 / 315; const IMAGE_2_RATIO = 222 / 239; const IMAGE_1_RATIO = 285 / 203; @@ -141,26 +143,27 @@ class OnboardingCarousel extends PureComponent { currentTab: 1, }; - track = (event, properties) => { - trackAfterInteractions( - event, - properties, - this.props.saveOnboardingEvent, - ).catch(() => { - Logger.log('OnboardingCarousel', `Failed to track ${event}`); + trackEvent = (eventArgs) => { + InteractionManager.runAfterInteractions(async () => { + const metricsOptIn = await DefaultPreference.get(METRICS_OPT_IN); + if (metricsOptIn) { + AnalyticsV2.trackEvent(eventArgs); + } else { + this.props.saveOnboardingEvent(eventArgs); + } }); }; onPressGetStarted = () => { this.props.navigation.navigate('Onboarding'); - this.track(MetaMetricsEvents.ONBOARDING_STARTED); + this.trackEvent(MetaMetricsEvents.ONBOARDING_STARTED); }; renderTabBar = () => ; onChangeTab = (obj) => { this.setState({ currentTab: obj.i + 1 }); - this.track(MetaMetricsEvents.ONBOARDING_WELCOME_SCREEN_ENGAGEMENT, { + this.trackEvent(MetaMetricsEvents.ONBOARDING_WELCOME_SCREEN_ENGAGEMENT, { message_title: strings(`onboarding_carousel.title${[obj.i + 1]}`, { locale: 'en', }), @@ -176,7 +179,7 @@ class OnboardingCarousel extends PureComponent { componentDidMount = () => { this.updateNavBar(); - this.track(MetaMetricsEvents.ONBOARDING_WELCOME_MESSAGE_VIEWED); + this.trackEvent(MetaMetricsEvents.ONBOARDING_WELCOME_MESSAGE_VIEWED); }; componentDidUpdate = () => { diff --git a/app/components/Views/RestoreWallet/WalletRestored.tsx b/app/components/Views/RestoreWallet/WalletRestored.tsx index bdab7d609f2..78c90d211de 100644 --- a/app/components/Views/RestoreWallet/WalletRestored.tsx +++ b/app/components/Views/RestoreWallet/WalletRestored.tsx @@ -13,7 +13,6 @@ import Text, { TextVariant, } from '../../../component-library/components/Texts/Text'; import StyledButton from '../../UI/StyledButton'; -import Logger from '../../../util/Logger'; import { createNavigationDetails } from '../../../util/navigation/navUtils'; import Routes from '../../../constants/navigation/Routes'; import { SafeAreaView } from 'react-native-safe-area-context'; @@ -50,11 +49,6 @@ const WalletRestored = () => { const finishWalletRestore = useCallback(async (): Promise => { try { - // Log to provide insights into bug research. - // Check https://github.com/MetaMask/mobile-planning/issues/1507 - if (typeof selectedAddress !== 'string') { - Logger.error('Wallet restore error', 'selectedAddress is not a string'); - } await Authentication.appTriggeredAuth({ selectedAddress }); navigation.replace(Routes.ONBOARDING.HOME_NAV); } catch (e) { diff --git a/app/components/Views/RestoreWallet/styles.ts b/app/components/Views/RestoreWallet/styles.ts index 16070c45870..e57f1e5e6e6 100644 --- a/app/components/Views/RestoreWallet/styles.ts +++ b/app/components/Views/RestoreWallet/styles.ts @@ -1,5 +1,5 @@ /* eslint-disable import/prefer-default-export */ -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; import { StyleSheet } from 'react-native'; export const createStyles = (colors: ThemeColors) => diff --git a/app/components/Views/SDKSessionsManager/SDKSessionItem.tsx b/app/components/Views/SDKSessionsManager/SDKSessionItem.tsx index fe09a15ae15..f70d0b920e7 100644 --- a/app/components/Views/SDKSessionsManager/SDKSessionItem.tsx +++ b/app/components/Views/SDKSessionsManager/SDKSessionItem.tsx @@ -1,5 +1,5 @@ -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; -import type { ThemeTypography } from '@metamask/design-tokens/dist/types/js/typography'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; +import { ThemeTypography } from '@metamask/design-tokens/dist/js/typography'; import React, { useEffect, useState } from 'react'; import { StyleSheet, TextStyle, View } from 'react-native'; import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context'; diff --git a/app/components/Views/SDKSessionsManager/SDKSessionsManager.tsx b/app/components/Views/SDKSessionsManager/SDKSessionsManager.tsx index 7dc4a90dea1..def3e13913a 100644 --- a/app/components/Views/SDKSessionsManager/SDKSessionsManager.tsx +++ b/app/components/Views/SDKSessionsManager/SDKSessionsManager.tsx @@ -5,8 +5,8 @@ import { EdgeInsets, useSafeAreaInsets } from 'react-native-safe-area-context'; import { strings } from '../../../../locales/i18n'; import { useTheme } from '../../../util/theme'; -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; -import type { ThemeTypography } from '@metamask/design-tokens/dist/types/js/typography'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; +import { ThemeTypography } from '@metamask/design-tokens/dist/js/typography'; import { SDKSelectorsIDs } from '../../../../e2e/selectors/Settings/SDK.selectors'; import ActionModal from '../../../components/UI/ActionModal'; import { getNavigationOptionsTitle } from '../../../components/UI/Navbar'; diff --git a/app/components/Views/confirmations/Send/__snapshots__/index.test.tsx.snap b/app/components/Views/Send/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/Send/__snapshots__/index.test.tsx.snap rename to app/components/Views/Send/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/Send/index.js b/app/components/Views/Send/index.js similarity index 90% rename from app/components/Views/confirmations/Send/index.js rename to app/components/Views/Send/index.js index 0aeb712218b..8be85260523 100644 --- a/app/components/Views/confirmations/Send/index.js +++ b/app/components/Views/Send/index.js @@ -7,61 +7,57 @@ import { StyleSheet, View, } from 'react-native'; -import Engine from '../../../../core/Engine'; -import EditAmount from '../SendFlow/Amount'; -import ConfirmSend from '../SendFlow/Confirm'; +import Engine from '../../../core/Engine'; +import EditAmount from '../../Views/SendFlow/Amount'; +import ConfirmSend from '../../Views/SendFlow/Confirm'; import { toBN, BNToHex, hexToBN, fromWei, fromTokenMinimalUnit, -} from '../../../../util/number'; +} from '../../../util/number'; import { toChecksumAddress } from 'ethereumjs-util'; -import { strings } from '../../../../../locales/i18n'; -import { getTransactionOptionsTitle } from '../../../UI/Navbar'; +import { strings } from '../../../../locales/i18n'; +import { getTransactionOptionsTitle } from '../../UI/Navbar'; import { connect } from 'react-redux'; import { resetTransaction, setTransactionObject, -} from '../../../../actions/transaction'; -import { toggleDappTransactionModal } from '../../../../actions/modals'; -import NotificationManager from '../../../../core/NotificationManager'; -import { showAlert } from '../../../../actions/alert'; -import Analytics from '../../../../core/Analytics/Analytics'; -import { MetaMetricsEvents } from '../../../../core/Analytics'; +} from '../../../actions/transaction'; +import { toggleDappTransactionModal } from '../../../actions/modals'; +import NotificationManager from '../../../core/NotificationManager'; +import { showAlert } from '../../../actions/alert'; +import Analytics from '../../../core/Analytics/Analytics'; +import { MetaMetricsEvents } from '../../../core/Analytics'; import { getTransactionReviewActionKey, decodeTransferData, getTransactionToName, generateTransferData, -} from '../../../../util/transactions'; -import Logger from '../../../../util/Logger'; -import { getAddress } from '../../../../util/address'; -import TransactionTypes from '../../../../core/TransactionTypes'; -import { MAINNET } from '../../../../constants/network'; +} from '../../../util/transactions'; +import Logger from '../../../util/Logger'; +import { getAddress } from '../../../util/address'; +import TransactionTypes from '../../../core/TransactionTypes'; +import { MAINNET } from '../../../constants/network'; import BigNumber from 'bignumber.js'; import { WalletDevice } from '@metamask/transaction-controller'; -import AnalyticsV2 from '../../../../util/analyticsV2'; -import { - addTransaction, - estimateGas, -} from '../../../../util/transaction-controller'; +import AnalyticsV2 from '../../../util/analyticsV2'; -import { KEYSTONE_TX_CANCELED } from '../../../../constants/error'; -import { ThemeContext, mockTheme } from '../../../../util/theme'; +import { KEYSTONE_TX_CANCELED } from '../../../constants/error'; +import { ThemeContext, mockTheme } from '../../../util/theme'; import { selectChainId, selectProviderType, -} from '../../../../selectors/networkController'; -import { selectTokenList } from '../../../../selectors/tokenListController'; -import { selectTokens } from '../../../../selectors/tokensController'; -import { selectAccounts } from '../../../../selectors/accountTrackerController'; -import { selectContractBalances } from '../../../../selectors/tokenBalancesController'; +} from '../../../selectors/networkController'; +import { selectTokenList } from '../../../selectors/tokenListController'; +import { selectTokens } from '../../../selectors/tokensController'; +import { selectAccounts } from '../../../selectors/accountTrackerController'; +import { selectContractBalances } from '../../../selectors/tokenBalancesController'; import { selectIdentities, selectSelectedAddress, -} from '../../../../selectors/preferencesController'; +} from '../../../selectors/preferencesController'; import { ethErrors } from 'eth-rpc-errors'; const REVIEW = 'review'; @@ -169,7 +165,8 @@ class Send extends PureComponent { */ async reset() { const { transaction } = this.props; - const { gas, gasPrice } = await estimateGas(transaction); + const { gas, gasPrice } = + await Engine.context.TransactionController.estimateGas(transaction); this.props.setTransactionObject({ gas: hexToBN(gas), gasPrice: hexToBN(gasPrice), @@ -392,7 +389,10 @@ class Send extends PureComponent { // if gas and gasPrice is not defined in the deeplink, we should define them if (!gas && !gasPrice) { - const { gas, gasPrice } = await estimateGas(this.props.transaction); + const { gas, gasPrice } = + await Engine.context.TransactionController.estimateGas( + this.props.transaction, + ); newTxMeta = { ...newTxMeta, gas, @@ -531,8 +531,12 @@ class Send extends PureComponent { * and returns to edit transaction */ onConfirm = async () => { - const { AddressBookController, KeyringController, ApprovalController } = - Engine.context; + const { + TransactionController, + AddressBookController, + KeyringController, + ApprovalController, + } = Engine.context; this.setState({ transactionConfirmed: true }); const { transaction: { selectedAsset, assetType }, @@ -546,10 +550,11 @@ class Send extends PureComponent { } else { transaction = this.prepareAssetTransaction(transaction, selectedAsset); } - const { result, transactionMeta } = await addTransaction(transaction, { - deviceConfirmedOn: WalletDevice.MM_MOBILE, - origin: TransactionTypes.MMM, - }); + const { result, transactionMeta } = + await TransactionController.addTransaction(transaction, { + deviceConfirmedOn: WalletDevice.MM_MOBILE, + origin: TransactionTypes.MMM, + }); await KeyringController.resetQRKeyringState(); await ApprovalController.accept(transactionMeta.id, undefined, { waitForResult: true, diff --git a/app/components/Views/confirmations/Send/index.test.tsx b/app/components/Views/Send/index.test.tsx similarity index 95% rename from app/components/Views/confirmations/Send/index.test.tsx rename to app/components/Views/Send/index.test.tsx index 8c31e841287..ca6ae19cd5f 100644 --- a/app/components/Views/confirmations/Send/index.test.tsx +++ b/app/components/Views/Send/index.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { shallow } from 'enzyme'; -import Send from '.'; +import Send from './'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.styles.ts b/app/components/Views/SendFlow/AddressElement/AddressElement.styles.ts similarity index 94% rename from app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.styles.ts rename to app/components/Views/SendFlow/AddressElement/AddressElement.styles.ts index 8dab6a672fe..ef3e1867bec 100644 --- a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.styles.ts +++ b/app/components/Views/SendFlow/AddressElement/AddressElement.styles.ts @@ -1,5 +1,5 @@ import { StyleSheet } from 'react-native'; -import { Colors } from '../../../../../util/theme/models'; +import { Colors } from '../../../../util/theme/models'; const styleSheet = (colors: Colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.test.tsx b/app/components/Views/SendFlow/AddressElement/AddressElement.test.tsx similarity index 76% rename from app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.test.tsx rename to app/components/Views/SendFlow/AddressElement/AddressElement.test.tsx index f05e299668b..ab3ea4831fc 100644 --- a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.test.tsx +++ b/app/components/Views/SendFlow/AddressElement/AddressElement.test.tsx @@ -1,16 +1,16 @@ import React from 'react'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; +import renderWithProvider from '../../../../util/test/renderWithProvider'; -import AddressElement from '.'; -import Engine from '../../../../../core/Engine'; -import { renderShortAddress } from '../../../../../util/address'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import AddressElement from './'; +import Engine from '../../../../core/Engine'; +import { renderShortAddress } from '../../../../util/address'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockEngine = Engine; jest.unmock('react-redux'); -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../../core/Engine', () => ({ init: () => mockEngine.init({}), context: { NetworkController: { diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.tsx b/app/components/Views/SendFlow/AddressElement/AddressElement.tsx similarity index 83% rename from app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.tsx rename to app/components/Views/SendFlow/AddressElement/AddressElement.tsx index 05a18ca4426..d0147cd22c2 100644 --- a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.tsx +++ b/app/components/Views/SendFlow/AddressElement/AddressElement.tsx @@ -8,19 +8,19 @@ import { View, TouchableOpacity } from 'react-native'; import { renderShortAddress, getLabelTextByAddress, -} from '../../../../../util/address'; -import Identicon from '../../../../UI/Identicon'; +} from '../../../../util/address'; +import Identicon from '../../../UI/Identicon'; import { useSelector } from 'react-redux'; -import { useTheme } from '../../../../../util/theme'; -import Text from '../../../../../component-library/components/Texts/Text/Text'; -import { TextVariant } from '../../../../../component-library/components/Texts/Text'; -import { selectChainId } from '../../../../../selectors/networkController'; -import { doENSReverseLookup } from '../../../../../util/ENSUtils'; -import { strings } from '../../../../../../locales/i18n'; +import { useTheme } from '../../../../util/theme'; +import Text from '../../../../component-library/components/Texts/Text/Text'; +import { TextVariant } from '../../../../component-library/components/Texts/Text'; +import { selectChainId } from '../../../../selectors/networkController'; +import { doENSReverseLookup } from '../../../../util/ENSUtils'; +import { strings } from '../../../../../locales/i18n'; import Icon, { IconName, IconSize, -} from '../../../../../component-library/components/Icons/Icon'; +} from '../../../../component-library/components/Icons/Icon'; // Internal dependecies import styleSheet from './AddressElement.styles'; diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.types.ts b/app/components/Views/SendFlow/AddressElement/AddressElement.types.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressElement/AddressElement.types.ts rename to app/components/Views/SendFlow/AddressElement/AddressElement.types.ts diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/__snapshots__/AddressElement.test.tsx.snap b/app/components/Views/SendFlow/AddressElement/__snapshots__/AddressElement.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressElement/__snapshots__/AddressElement.test.tsx.snap rename to app/components/Views/SendFlow/AddressElement/__snapshots__/AddressElement.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/AddressElement/index.tsx b/app/components/Views/SendFlow/AddressElement/index.tsx similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressElement/index.tsx rename to app/components/Views/SendFlow/AddressElement/index.tsx diff --git a/app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.test.tsx b/app/components/Views/SendFlow/AddressFrom/AddressFrom.test.tsx similarity index 87% rename from app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.test.tsx rename to app/components/Views/SendFlow/AddressFrom/AddressFrom.test.tsx index d75c6b592e9..e218f25f42f 100644 --- a/app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.test.tsx +++ b/app/components/Views/SendFlow/AddressFrom/AddressFrom.test.tsx @@ -4,11 +4,11 @@ import configureMockStore from 'redux-mock-store'; import { render } from '@testing-library/react-native'; -import SendFlowAddressFrom from '.'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import SendFlowAddressFrom from './'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; -jest.mock('../../../../../util/ENSUtils', () => ({ - ...jest.requireActual('../../../../../util/ENSUtils'), +jest.mock('../../../../util/ENSUtils', () => ({ + ...jest.requireActual('../../../../util/ENSUtils'), doENSReverseLookup: jest.fn(), })); @@ -19,7 +19,7 @@ jest.mock('@react-navigation/native', () => ({ createNavigatorFactory: () => ({}), })); -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../../core/Engine', () => ({ context: { KeyringController: { state: { diff --git a/app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.tsx b/app/components/Views/SendFlow/AddressFrom/AddressFrom.tsx similarity index 85% rename from app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.tsx rename to app/components/Views/SendFlow/AddressFrom/AddressFrom.tsx index b9dd98f7be8..d9ce5a2ba1e 100644 --- a/app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.tsx +++ b/app/components/Views/SendFlow/AddressFrom/AddressFrom.tsx @@ -6,21 +6,21 @@ import { useNavigation } from '@react-navigation/native'; import { newAssetTransaction, setSelectedAsset, -} from '../../../../../actions/transaction'; -import Routes from '../../../../../constants/navigation/Routes'; +} from '../../../../actions/transaction'; +import Routes from '../../../../constants/navigation/Routes'; import { selectChainId, selectTicker, -} from '../../../../../selectors/networkController'; -import { selectAccounts } from '../../../../../selectors/accountTrackerController'; +} from '../../../../selectors/networkController'; +import { selectAccounts } from '../../../../selectors/accountTrackerController'; import { selectIdentities, selectSelectedAddress, -} from '../../../../../selectors/preferencesController'; -import { doENSReverseLookup } from '../../../../../util/ENSUtils'; -import { renderFromWei, hexToBN } from '../../../../../util/number'; -import { getEther, getTicker } from '../../../../../util/transactions'; -import { AddressFrom } from '../../../../UI/AddressInputs'; +} from '../../../../selectors/preferencesController'; +import { doENSReverseLookup } from '../../../../util/ENSUtils'; +import { renderFromWei, hexToBN } from '../../../../util/number'; +import { getEther, getTicker } from '../../../../util/transactions'; +import { AddressFrom } from '../../../UI/AddressInputs'; import { SFAddressFromProps } from './AddressFrom.types'; const SendFlowAddressFrom = ({ diff --git a/app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.types.ts b/app/components/Views/SendFlow/AddressFrom/AddressFrom.types.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressFrom/AddressFrom.types.ts rename to app/components/Views/SendFlow/AddressFrom/AddressFrom.types.ts diff --git a/app/components/Views/confirmations/SendFlow/AddressFrom/__snapshots__/AddressFrom.test.tsx.snap b/app/components/Views/SendFlow/AddressFrom/__snapshots__/AddressFrom.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressFrom/__snapshots__/AddressFrom.test.tsx.snap rename to app/components/Views/SendFlow/AddressFrom/__snapshots__/AddressFrom.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/AddressFrom/index.ts b/app/components/Views/SendFlow/AddressFrom/index.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressFrom/index.ts rename to app/components/Views/SendFlow/AddressFrom/index.ts diff --git a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.styles.ts b/app/components/Views/SendFlow/AddressList/AddressList.styles.ts similarity index 92% rename from app/components/Views/confirmations/SendFlow/AddressList/AddressList.styles.ts rename to app/components/Views/SendFlow/AddressList/AddressList.styles.ts index a86c5604416..66c02127ac8 100644 --- a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.styles.ts +++ b/app/components/Views/SendFlow/AddressList/AddressList.styles.ts @@ -1,6 +1,6 @@ import { StyleSheet } from 'react-native'; -import { Colors } from '../../../../../util/theme/models'; +import { Colors } from '../../../../util/theme/models'; const styleSheet = (colors: Colors) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.test.tsx b/app/components/Views/SendFlow/AddressList/AddressList.test.tsx similarity index 64% rename from app/components/Views/confirmations/SendFlow/AddressList/AddressList.test.tsx rename to app/components/Views/SendFlow/AddressList/AddressList.test.tsx index 0d9dfa01197..245d85d53d8 100644 --- a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.test.tsx +++ b/app/components/Views/SendFlow/AddressList/AddressList.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; -import renderWithProvider from '../../../../../util/test/renderWithProvider'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import AddressList from '.'; +import renderWithProvider from '../../../../util/test/renderWithProvider'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; +import AddressList from './'; -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../../core/Engine', () => ({ context: { KeyringController: { state: { @@ -19,14 +19,12 @@ const initialState = { ...initialBackgroundState, AddressBookController: { addressBook: { - '0x1': { - '0xC4955C0d639D99699Bfd7Ec54d9FaFEe40e4D272': { - address: '0xC4955C0d639D99699Bfd7Ec54d9FaFEe40e4D272', - chainId: '0x1', - isEns: false, - memo: '', - name: 'aa', - }, + '0xC4955C0d639D99699Bfd7Ec54d9FaFEe40e4D272': { + address: '0xC4955C0d639D99699Bfd7Ec54d9FaFEe40e4D272', + chainId: '1', + isEns: false, + memo: '', + name: 'aa', }, }, }, diff --git a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.tsx b/app/components/Views/SendFlow/AddressList/AddressList.tsx similarity index 92% rename from app/components/Views/confirmations/SendFlow/AddressList/AddressList.tsx rename to app/components/Views/SendFlow/AddressList/AddressList.tsx index 117a5580703..e5672424657 100644 --- a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.tsx +++ b/app/components/Views/SendFlow/AddressList/AddressList.tsx @@ -9,16 +9,16 @@ import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view import { AddressBookEntry } from '@metamask/address-book-controller'; // External dependencies -import { isSmartContractAddress } from '../../../../../util/transactions'; -import { strings } from '../../../../../../locales/i18n'; +import { isSmartContractAddress } from '../../../../util/transactions'; +import { strings } from '../../../../../locales/i18n'; import AddressElement from '../AddressElement'; -import { useTheme } from '../../../../../util/theme'; -import Text from '../../../../../component-library/components/Texts/Text/Text'; -import { TextVariant } from '../../../../../component-library/components/Texts/Text'; -import { selectChainId } from '../../../../../selectors/networkController'; -import { selectIdentities } from '../../../../../selectors/preferencesController'; -import { regex } from '../../../../../util/regex'; -import { SendViewSelectorsIDs } from '../../../../../../e2e/selectors/SendView.selectors'; +import { useTheme } from '../../../../util/theme'; +import Text from '../../../../component-library/components/Texts/Text/Text'; +import { TextVariant } from '../../../../component-library/components/Texts/Text'; +import { selectChainId } from '../../../../selectors/networkController'; +import { selectIdentities } from '../../../../selectors/preferencesController'; +import { regex } from '../../../../util/regex'; +import { SendViewSelectorsIDs } from '../../../../../e2e/selectors/SendView.selectors'; // Internal dependencies import { AddressListProps, Contact } from './AddressList.types'; diff --git a/app/components/Views/confirmations/SendFlow/AddressList/AddressList.types.ts b/app/components/Views/SendFlow/AddressList/AddressList.types.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressList/AddressList.types.ts rename to app/components/Views/SendFlow/AddressList/AddressList.types.ts diff --git a/app/components/Views/confirmations/SendFlow/AddressList/__snapshots__/AddressList.test.tsx.snap b/app/components/Views/SendFlow/AddressList/__snapshots__/AddressList.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressList/__snapshots__/AddressList.test.tsx.snap rename to app/components/Views/SendFlow/AddressList/__snapshots__/AddressList.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/AddressList/index.tsx b/app/components/Views/SendFlow/AddressList/index.tsx similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressList/index.tsx rename to app/components/Views/SendFlow/AddressList/index.tsx diff --git a/app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.test.tsx b/app/components/Views/SendFlow/AddressTo/AddressTo.test.tsx similarity index 91% rename from app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.test.tsx rename to app/components/Views/SendFlow/AddressTo/AddressTo.test.tsx index b27d732889d..93de69ada20 100644 --- a/app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.test.tsx +++ b/app/components/Views/SendFlow/AddressTo/AddressTo.test.tsx @@ -4,8 +4,8 @@ import configureMockStore from 'redux-mock-store'; import { render } from '@testing-library/react-native'; -import SendFlowAddressTo from '.'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import SendFlowAddressTo from './'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; jest.mock('@react-navigation/native', () => ({ useNavigation: () => ({ diff --git a/app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.tsx b/app/components/Views/SendFlow/AddressTo/AddressTo.tsx similarity index 85% rename from app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.tsx rename to app/components/Views/SendFlow/AddressTo/AddressTo.tsx index 6a4a53b7644..680d88b2a5e 100644 --- a/app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.tsx +++ b/app/components/Views/SendFlow/AddressTo/AddressTo.tsx @@ -4,13 +4,13 @@ import { useDispatch } from 'react-redux'; import { useNavigation } from '@react-navigation/native'; -import { strings } from '../../../../../../locales/i18n'; -import { showAlert } from '../../../../../actions/alert'; -import { NetworkSwitchErrorType } from '../../../../../constants/error'; -import Routes from '../../../../../constants/navigation/Routes'; -import { handleNetworkSwitch } from '../../../../../util/networks'; -import { AddressTo } from '../../../../UI/AddressInputs'; -import { createQRScannerNavDetails } from '../../../QRScanner'; +import { strings } from '../../../../../locales/i18n'; +import { showAlert } from '../../../../actions/alert'; +import { NetworkSwitchErrorType } from '../../../../constants/error'; +import Routes from '../../../../constants/navigation/Routes'; +import { handleNetworkSwitch } from '../../../../util/networks'; +import { AddressTo } from '../../../UI/AddressInputs'; +import { createQRScannerNavDetails } from '../../QRScanner'; import { SFAddressToProps } from './AddressTo.types'; const SendFlowAddressTo = ({ diff --git a/app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.types.ts b/app/components/Views/SendFlow/AddressTo/AddressTo.types.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressTo/AddressTo.types.ts rename to app/components/Views/SendFlow/AddressTo/AddressTo.types.ts diff --git a/app/components/Views/confirmations/SendFlow/AddressTo/__snapshots__/AddressTo.test.tsx.snap b/app/components/Views/SendFlow/AddressTo/__snapshots__/AddressTo.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressTo/__snapshots__/AddressTo.test.tsx.snap rename to app/components/Views/SendFlow/AddressTo/__snapshots__/AddressTo.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/AddressTo/index.ts b/app/components/Views/SendFlow/AddressTo/index.ts similarity index 100% rename from app/components/Views/confirmations/SendFlow/AddressTo/index.ts rename to app/components/Views/SendFlow/AddressTo/index.ts diff --git a/app/components/Views/confirmations/SendFlow/Amount/__snapshots__/index.test.tsx.snap b/app/components/Views/SendFlow/Amount/__snapshots__/index.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/SendFlow/Amount/__snapshots__/index.test.tsx.snap rename to app/components/Views/SendFlow/Amount/__snapshots__/index.test.tsx.snap index 8a5a8fb4b4d..3a1117e9550 100644 --- a/app/components/Views/confirmations/SendFlow/Amount/__snapshots__/index.test.tsx.snap +++ b/app/components/Views/SendFlow/Amount/__snapshots__/index.test.tsx.snap @@ -375,7 +375,7 @@ exports[`Amount should convert ERC-20 token value to USD 1`] = ` ({ +jest.mock('../../../../core/Engine', () => ({ init: () => mockEngine.init({}), context: { GasFeeController: { @@ -64,15 +64,6 @@ jest.mock('../../../../../core/Engine', () => ({ }, })); -jest.mock('../../../../../util/transaction-controller', () => ({ - __esModule: true, - estimateGas: jest.fn(() => - Promise.resolve({ - gas: mockTransactionTypes.CUSTOM_GAS.DEFAULT_GAS_LIMIT, - }), - ), -})); - const mockNavigate = jest.fn(); const CURRENT_ACCOUNT = '0x1a'; @@ -87,7 +78,7 @@ const initialState = { providerConfig: { ticker: 'ETH', type: 'mainnet', - chainId: '0x1', + chainId: '1', }, }, AccountTrackerController: { @@ -103,8 +94,8 @@ const initialState = { }, }, NftController: { - allNfts: { [CURRENT_ACCOUNT]: { '0x1': [] } }, - allNftContracts: { [CURRENT_ACCOUNT]: { '0x1': [] } }, + allNfts: { [CURRENT_ACCOUNT]: { '1': [] } }, + allNftContracts: { [CURRENT_ACCOUNT]: { '1': [] } }, }, }, }, diff --git a/app/components/Views/confirmations/SendFlow/Confirm/__snapshots__/index.test.tsx.snap b/app/components/Views/SendFlow/Confirm/__snapshots__/index.test.tsx.snap similarity index 99% rename from app/components/Views/confirmations/SendFlow/Confirm/__snapshots__/index.test.tsx.snap rename to app/components/Views/SendFlow/Confirm/__snapshots__/index.test.tsx.snap index 7ebb3012bd2..6897b84e9fb 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/__snapshots__/index.test.tsx.snap +++ b/app/components/Views/SendFlow/Confirm/__snapshots__/index.test.tsx.snap @@ -812,7 +812,7 @@ exports[`Confirm should render correctly 1`] = ` style={ Array [ Object { - "color": "#1C8234", + "color": "#28A745", "fontSize": 15, }, undefined, @@ -1650,14 +1650,11 @@ exports[`Confirm should render correctly 1`] = ` "backgroundColor": "#0376C9", "minHeight": 50, }, - Array [ - Object { - "alignSelf": "flex-end", - "flex": 1, - "marginHorizontal": 24, - }, - Object {}, - ], + Object { + "alignSelf": "flex-end", + "flex": 1, + "marginHorizontal": 24, + }, ], Object { "opacity": 0.6, @@ -1686,7 +1683,7 @@ exports[`Confirm should render correctly 1`] = ` "textAlign": "center", }, Object { - "color": "#FFFFFF", + "color": "#FCFCFC", }, undefined, ], diff --git a/app/components/Views/confirmations/SendFlow/Confirm/index.js b/app/components/Views/SendFlow/Confirm/index.js similarity index 88% rename from app/components/Views/confirmations/SendFlow/Confirm/index.js rename to app/components/Views/SendFlow/Confirm/index.js index 0d0037f4c0f..1c09a91024e 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/index.js +++ b/app/components/Views/SendFlow/Confirm/index.js @@ -1,5 +1,5 @@ import React, { PureComponent } from 'react'; -import { baseStyles } from '../../../../../styles/common'; +import { baseStyles } from '../../../../styles/common'; import { InteractionManager, View, @@ -10,7 +10,7 @@ import { Platform, } from 'react-native'; import { connect } from 'react-redux'; -import { getSendFlowTitle } from '../../../../UI/Navbar'; +import { getSendFlowTitle } from '../../../UI/Navbar'; import PropTypes from 'prop-types'; import Eth from 'ethjs-query'; import { @@ -21,36 +21,36 @@ import { isDecimal, hexToBN, BNToHex, -} from '../../../../../util/number'; +} from '../../../../util/number'; import { getTicker, decodeTransferData, getNormalizedTxState, -} from '../../../../../util/transactions'; -import StyledButton from '../../../../UI/StyledButton'; +} from '../../../../util/transactions'; +import StyledButton from '../../../UI/StyledButton'; import { WalletDevice } from '@metamask/transaction-controller'; -import { ChainId } from '@metamask/controller-utils'; +import { NetworksChainId } from '@metamask/controller-utils'; import { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller'; import { prepareTransaction, resetTransaction, setNonce, setProposedNonce, -} from '../../../../../actions/transaction'; -import { getGasLimit } from '../../../../../util/custom-gas'; -import Engine from '../../../../../core/Engine'; -import Logger from '../../../../../util/Logger'; -import { WALLET_CONNECT_ORIGIN } from '../../../../../util/walletconnect'; -import CustomNonceModal from '../components/CustomNonceModal'; -import NotificationManager from '../../../../../core/NotificationManager'; -import { strings } from '../../../../../../locales/i18n'; -import CollectibleMedia from '../../../../UI/CollectibleMedia'; +} from '../../../../actions/transaction'; +import { getGasLimit } from '../../../../util/custom-gas'; +import Engine from '../../../../core/Engine'; +import Logger from '../../../../util/Logger'; +import { WALLET_CONNECT_ORIGIN } from '../../../../util/walletconnect'; +import CustomNonceModal from '../../../UI/CustomNonceModal'; +import NotificationManager from '../../../../core/NotificationManager'; +import { strings } from '../../../../../locales/i18n'; +import CollectibleMedia from '../../../UI/CollectibleMedia'; import Modal from 'react-native-modal'; import IonicIcon from 'react-native-vector-icons/Ionicons'; -import TransactionTypes from '../../../../../core/TransactionTypes'; -import Analytics from '../../../../../core/Analytics/Analytics'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import { shallowEqual, renderShortText } from '../../../../../util/general'; +import TransactionTypes from '../../../../core/TransactionTypes'; +import Analytics from '../../../../core/Analytics/Analytics'; +import { MetaMetricsEvents } from '../../../../core/Analytics'; +import { shallowEqual, renderShortText } from '../../../../util/general'; import { isTestNet, getNetworkNonce, @@ -59,63 +59,60 @@ import { fetchEstimatedMultiLayerL1Fee, TESTNET_FAUCETS, isTestNetworkWithFaucet, - getDecimalChainId, -} from '../../../../../util/networks'; -import Text from '../../../../Base/Text'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; +} from '../../../../util/networks'; +import Text from '../../../Base/Text'; +import AnalyticsV2 from '../../../../util/analyticsV2'; import { addHexPrefix } from 'ethereumjs-util'; -import { removeFavoriteCollectible } from '../../../../../actions/collectibles'; +import { removeFavoriteCollectible } from '../../../../actions/collectibles'; import { SafeAreaView } from 'react-native-safe-area-context'; -import AccountFromToInfoCard from '../../../../UI/AccountFromToInfoCard'; -import TransactionReview from '../../components/TransactionReview/TransactionReviewEIP1559Update'; -import CustomNonce from '../../components/CustomNonce'; -import AppConstants from '../../../../../core/AppConstants'; +import AccountFromToInfoCard from '../../../UI/AccountFromToInfoCard'; +import TransactionReview from '../../../UI/TransactionReview/TransactionReviewEIP1559Update'; +import CustomNonce from '../../../UI/CustomNonce'; +import AppConstants from '../../../../core/AppConstants'; import { getAddressAccountType, isQRHardwareAccount, isHardwareAccount, -} from '../../../../../util/address'; -import { KEYSTONE_TX_CANCELED } from '../../../../../constants/error'; -import { ThemeContext, mockTheme } from '../../../../../util/theme'; -import Routes from '../../../../../constants/navigation/Routes'; +} from '../../../../util/address'; +import { KEYSTONE_TX_CANCELED } from '../../../../constants/error'; +import { ThemeContext, mockTheme } from '../../../../util/theme'; +import Routes from '../../../../constants/navigation/Routes'; import WarningMessage from '../WarningMessage'; -import { showAlert } from '../../../../../actions/alert'; -import ClipboardManager from '../../../../../core/ClipboardManager'; -import GlobalAlert from '../../../../UI/GlobalAlert'; +import { showAlert } from '../../../../actions/alert'; +import ClipboardManager from '../../../../core/ClipboardManager'; +import GlobalAlert from '../../../UI/GlobalAlert'; import createStyles from './styles'; import { startGasPolling, stopGasPolling, -} from '../../../../../core/GasPolling/GasPolling'; +} from '../../../../core/GasPolling/GasPolling'; import { selectChainId, selectProviderType, selectTicker, -} from '../../../../../selectors/networkController'; +} from '../../../../selectors/networkController'; import { selectConversionRate, selectCurrentCurrency, -} from '../../../../../selectors/currencyRateController'; - -import { selectContractExchangeRates } from '../../../../../selectors/tokenRatesController'; -import { selectAccounts } from '../../../../../selectors/accountTrackerController'; -import { selectContractBalances } from '../../../../../selectors/tokenBalancesController'; -import generateTestId from '../../../../../../wdio/utils/generateTestId'; -import { COMFIRM_TXN_AMOUNT } from '../../../../../../wdio/screen-objects/testIDs/Screens/TransactionConfirm.testIds'; -import { isNetworkRampNativeTokenSupported } from '../../../../../components/UI/Ramp/utils'; -import { getRampNetworks } from '../../../../../reducers/fiatOrders'; -import { ConfirmViewSelectorsIDs } from '../../../../../../e2e/selectors/SendFlow/ConfirmView.selectors'; -import ExtendedKeyringTypes from '../../../../../constants/keyringTypes'; -import { getLedgerKeyring } from '../../../../../core/Ledger/Ledger'; +} from '../../../../selectors/currencyRateController'; +import { selectContractExchangeRates } from '../../../../selectors/tokenRatesController'; +import { selectAccounts } from '../../../../selectors/accountTrackerController'; +import { selectContractBalances } from '../../../../selectors/tokenBalancesController'; +import generateTestId from '../../../../../wdio/utils/generateTestId'; +import { COMFIRM_TXN_AMOUNT } from '../../../../../wdio/screen-objects/testIDs/Screens/TransactionConfirm.testIds'; +import { isNetworkRampNativeTokenSupported } from '../../../UI/Ramp/utils'; +import { getRampNetworks } from '../../../../reducers/fiatOrders'; +import CustomGasModal from '../../../UI/CustomGasModal'; +import { ConfirmViewSelectorsIDs } from '../../../../../e2e/selectors/SendFlow/ConfirmView.selectors'; +import ExtendedKeyringTypes from '../../../..//constants/keyringTypes'; +import { getLedgerKeyring } from '../../../../core/Ledger/Ledger'; +import { createLedgerTransactionModalNavDetails } from '../../../UI/LedgerModals/LedgerTransactionModal'; import { getBlockaidMetricsParams, isBlockaidFeatureEnabled, -} from '../../../../../util/blockaid'; -import ppomUtil from '../../../../../lib/ppom/ppom-util'; -import TransactionBlockaidBanner from '../../components/TransactionBlockaidBanner/TransactionBlockaidBanner'; -import { createLedgerTransactionModalNavDetails } from '../../../../../components/UI/LedgerModals/LedgerTransactionModal'; -import CustomGasModal from './components/CustomGasModal'; -import { ResultType } from '../../components/BlockaidBanner/BlockaidBanner.types'; +} from '../../../../util/blockaid'; +import ppomUtil from '../../../../lib/ppom/ppom-util'; +import TransactionBlockaidBanner from '../../../../components/UI/TransactionBlockaidBanner/TransactionBlockaidBanner'; const EDIT = 'edit'; const EDIT_NONCE = 'edit_nonce'; @@ -277,7 +274,7 @@ class Confirm extends PureComponent { return { active_currency: { value: selectedAsset?.symbol, anonymous: true }, account_type: getAddressAccountType(fromSelectedAddress), - chain_id: getDecimalChainId(chainId), + chain_id: chainId, gas_estimate_type: gasEstimateType, gas_mode: gasSelected ? 'Basic' : 'Advanced', speed_set: gasSelected || undefined, @@ -674,7 +671,7 @@ class Confirm extends PureComponent { chainId, } = this.props; const { fromSelectedAddress } = this.state; - if (assetType === 'ERC721' && chainId !== ChainId.mainnet) { + if (assetType === 'ERC721' && chainId !== NetworksChainId.mainnet) { const { NftController } = Engine.context; removeFavoriteCollectible(fromSelectedAddress, chainId, selectedAsset); NftController.removeNft(selectedAsset.address, selectedAsset.tokenId); @@ -937,19 +934,15 @@ class Confirm extends PureComponent { this.setState({ hexDataModalVisible: !hexDataModalVisible }); }; - updateTransactionStateWithUpdatedNonce = (nonceValue) => { - this.props.setNonce(nonceValue); - this.setState({ preparedTransaction: {} }); - }; - renderCustomNonceModal = () => { + const { setNonce } = this.props; const { proposedNonce, nonce } = this.props.transaction; return ( this.toggleConfirmationModal(REVIEW)} - save={this.updateTransactionStateWithUpdatedNonce} + save={setNonce} /> ); }; @@ -1091,34 +1084,6 @@ class Confirm extends PureComponent { ); }; - getConfirmButtonStyles() { - const { transactionMeta } = this.state; - const { transaction } = this.props; - const { currentTransactionSecurityAlertResponse } = transaction; - const colors = this.context.colors || mockTheme.colors; - const styles = createStyles(colors); - - let confirmButtonStyle = {}; - if ( - transactionMeta.id && - currentTransactionSecurityAlertResponse?.id && - currentTransactionSecurityAlertResponse.id === transactionMeta.id - ) { - if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Malicious - ) { - confirmButtonStyle = styles.confirmButtonError; - } else if ( - currentTransactionSecurityAlertResponse?.response?.result_type === - ResultType.Warning - ) { - confirmButtonStyle = styles.confirmButtonWarning; - } - } - return confirmButtonStyle; - } - render = () => { const { selectedAsset, paymentRequest } = this.props.transactionState; const { @@ -1314,7 +1279,7 @@ class Confirm extends PureComponent { Boolean(errorMessage) || isAnimating } - containerStyle={[styles.buttonNext, this.getConfirmButtonStyles()]} + containerStyle={styles.buttonNext} onPress={this.onNext} testID={ConfirmViewSelectorsIDs.SEND_BUTTON} > diff --git a/app/components/Views/confirmations/SendFlow/Confirm/index.test.tsx b/app/components/Views/SendFlow/Confirm/index.test.tsx similarity index 76% rename from app/components/Views/confirmations/SendFlow/Confirm/index.test.tsx rename to app/components/Views/SendFlow/Confirm/index.test.tsx index 63fba6cbb5b..aaed64ca1f4 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/index.test.tsx +++ b/app/components/Views/SendFlow/Confirm/index.test.tsx @@ -2,12 +2,12 @@ import React from 'react'; import { ConnectedComponent } from 'react-redux'; import { waitFor } from '@testing-library/react-native'; import Confirm from '.'; -import { renderScreen } from '../../../../../util/test/renderWithProvider'; -import Routes from '../../../../../constants/navigation/Routes'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; -import analyticsV2 from '../../../../../util/analyticsV2'; -import { TESTID_ACCORDION_CONTENT } from '../../../../../component-library/components/Accordions/Accordion/Accordion.constants'; -import { FALSE_POSITIVE_REPOST_LINE_TEST_ID } from '../../components/BlockaidBanner/BlockaidBanner.constants'; +import { renderScreen } from '../../../../util/test/renderWithProvider'; +import Routes from '../../../../constants/navigation/Routes'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; +import analyticsV2 from '../../../../util/analyticsV2'; +import { TESTID_ACCORDION_CONTENT } from '../../../../component-library/components/Accordions/Accordion/Accordion.constants'; +import { FALSE_POSITIVE_REPOST_LINE_TEST_ID } from '../../../../components/UI/BlockaidBanner/BlockaidBanner.constants'; const mockInitialState = { engine: { @@ -80,23 +80,23 @@ jest.mock('react-redux', () => ({ .mockImplementation((callback) => callback(mockInitialState)), })); -jest.mock('../../../../../core/GasPolling/GasPolling', () => ({ - ...jest.requireActual('../../../../../core/GasPolling/GasPolling'), +jest.mock('../../../../core/GasPolling/GasPolling', () => ({ + ...jest.requireActual('../../../../core/GasPolling/GasPolling'), startGasPolling: jest.fn(), stopGasPolling: jest.fn(), })); -jest.mock('../../../../../util/ENSUtils', () => ({ - ...jest.requireActual('../../../../../util/ENSUtils'), +jest.mock('../../../../util/ENSUtils', () => ({ + ...jest.requireActual('../../../../util/ENSUtils'), doENSReverseLookup: jest.fn(), })); -jest.mock('../../../../../lib/ppom/ppom-util', () => ({ - ...jest.requireActual('../../../../../lib/ppom/ppom-util'), +jest.mock('../../../../lib/ppom/ppom-util', () => ({ + ...jest.requireActual('../../../../lib/ppom/ppom-util'), validateRequest: jest.fn(), })); -jest.mock('../../../../../core/Engine', () => ({ +jest.mock('../../../../core/Engine', () => ({ context: { TokensController: { addToken: jest.fn(), @@ -121,12 +121,12 @@ jest.mock('../../../../../core/Engine', () => ({ }, }, })); -jest.mock('../../../../../util/custom-gas', () => ({ - ...jest.requireActual('../../../../../util/custom-gas'), +jest.mock('../../../../util/custom-gas', () => ({ + ...jest.requireActual('../../../../util/custom-gas'), getGasLimit: jest.fn(), })); -jest.mock('../../../../../util/transactions', () => ({ - ...jest.requireActual('../../../../../util/transactions'), +jest.mock('../../../../util/transactions', () => ({ + ...jest.requireActual('../../../../util/transactions'), decodeTransferData: jest.fn().mockImplementation(() => ['0x2']), })); diff --git a/app/components/Views/confirmations/SendFlow/Confirm/styles.ts b/app/components/Views/SendFlow/Confirm/styles.ts similarity index 91% rename from app/components/Views/confirmations/SendFlow/Confirm/styles.ts rename to app/components/Views/SendFlow/Confirm/styles.ts index c6b50648b83..7ef91543c95 100644 --- a/app/components/Views/confirmations/SendFlow/Confirm/styles.ts +++ b/app/components/Views/SendFlow/Confirm/styles.ts @@ -1,4 +1,4 @@ -import { fontStyles } from '../../../../../styles/common'; +import { fontStyles } from '../../../../styles/common'; import { StyleSheet } from 'react-native'; const createStyles = (colors: any) => @@ -138,14 +138,6 @@ const createStyles = (colors: any) => marginTop: 20, marginHorizontal: 10, }, - confirmButtonError: { - backgroundColor: colors.error.default, - borderColor: colors.error.default, - }, - confirmButtonWarning: { - backgroundColor: colors.warning.default, - borderColor: colors.warning.default, - }, }); export default createStyles; diff --git a/app/components/Views/confirmations/SendFlow/ErrorMessage/__snapshots__/index.test.tsx.snap b/app/components/Views/SendFlow/ErrorMessage/__snapshots__/index.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/ErrorMessage/__snapshots__/index.test.tsx.snap rename to app/components/Views/SendFlow/ErrorMessage/__snapshots__/index.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/ErrorMessage/index.js b/app/components/Views/SendFlow/ErrorMessage/index.js similarity index 86% rename from app/components/Views/confirmations/SendFlow/ErrorMessage/index.js rename to app/components/Views/SendFlow/ErrorMessage/index.js index 21c1fff72b8..b0a08f1d02d 100644 --- a/app/components/Views/confirmations/SendFlow/ErrorMessage/index.js +++ b/app/components/Views/SendFlow/ErrorMessage/index.js @@ -1,10 +1,10 @@ import React from 'react'; import { StyleSheet, View, TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types'; -import { strings } from '../../../../../../locales/i18n'; -import Alert, { AlertType } from '../../../../Base/Alert'; -import Text from '../../../../Base/Text'; -import { CommonSelectorsIDs } from '../../../../../../e2e/selectors/Common.selectors'; +import { strings } from '../../../../../locales/i18n'; +import Alert, { AlertType } from '../../../Base/Alert'; +import Text from '../../../Base/Text'; +import { CommonSelectorsIDs } from '../../../../../e2e/selectors/Common.selectors'; const styles = StyleSheet.create({ button: { diff --git a/app/components/Views/confirmations/SendFlow/ErrorMessage/index.test.tsx b/app/components/Views/SendFlow/ErrorMessage/index.test.tsx similarity index 89% rename from app/components/Views/confirmations/SendFlow/ErrorMessage/index.test.tsx rename to app/components/Views/SendFlow/ErrorMessage/index.test.tsx index b05ae978583..6b0c7ed4dc3 100644 --- a/app/components/Views/confirmations/SendFlow/ErrorMessage/index.test.tsx +++ b/app/components/Views/SendFlow/ErrorMessage/index.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { shallow } from 'enzyme'; -import ErrorMessage from '.'; +import ErrorMessage from './'; describe('ErrorMessage', () => { it('should render correctly', () => { diff --git a/app/components/Views/confirmations/SendFlow/SendTo/SendTo.test.tsx b/app/components/Views/SendFlow/SendTo/SendTo.test.tsx similarity index 90% rename from app/components/Views/confirmations/SendFlow/SendTo/SendTo.test.tsx rename to app/components/Views/SendFlow/SendTo/SendTo.test.tsx index 53eaaa428b1..16e4c0a7907 100644 --- a/app/components/Views/confirmations/SendFlow/SendTo/SendTo.test.tsx +++ b/app/components/Views/SendFlow/SendTo/SendTo.test.tsx @@ -3,7 +3,7 @@ import { shallow } from 'enzyme'; import SendTo from '.'; import configureMockStore from 'redux-mock-store'; import { Provider } from 'react-redux'; -import initialBackgroundState from '../../../../../util/test/initial-background-state.json'; +import initialBackgroundState from '../../../../util/test/initial-background-state.json'; const mockStore = configureMockStore(); const initialState = { diff --git a/app/components/Views/confirmations/SendFlow/SendTo/__snapshots__/SendTo.test.tsx.snap b/app/components/Views/SendFlow/SendTo/__snapshots__/SendTo.test.tsx.snap similarity index 100% rename from app/components/Views/confirmations/SendFlow/SendTo/__snapshots__/SendTo.test.tsx.snap rename to app/components/Views/SendFlow/SendTo/__snapshots__/SendTo.test.tsx.snap diff --git a/app/components/Views/confirmations/SendFlow/SendTo/index.js b/app/components/Views/SendFlow/SendTo/index.js similarity index 92% rename from app/components/Views/confirmations/SendFlow/SendTo/index.js rename to app/components/Views/SendFlow/SendTo/index.js index ba972537fbf..1bd66b4c0dc 100644 --- a/app/components/Views/confirmations/SendFlow/SendTo/index.js +++ b/app/components/Views/SendFlow/SendTo/index.js @@ -12,66 +12,63 @@ import { connect } from 'react-redux'; import { toChecksumAddress } from 'ethereumjs-util'; import { SafeAreaView } from 'react-native-safe-area-context'; import Icon from 'react-native-vector-icons/FontAwesome'; -import Analytics from '../../../../../core/Analytics/Analytics'; -import AddressList from '../AddressList'; -import Text from '../../../../Base/Text'; +import Analytics from '../../../../core/Analytics/Analytics'; +import AddressList from './../AddressList'; +import Text from '../../../Base/Text'; import WarningMessage from '../WarningMessage'; -import { getSendFlowTitle } from '../../../../UI/Navbar'; -import StyledButton from '../../../../UI/StyledButton'; -import { MetaMetricsEvents } from '../../../../../core/Analytics'; -import AnalyticsV2 from '../../../../../util/analyticsV2'; -import { - getDecimalChainId, - handleNetworkSwitch, -} from '../../../../../util/networks'; +import { getSendFlowTitle } from '../../../UI/Navbar'; +import StyledButton from '../../../UI/StyledButton'; +import { MetaMetricsEvents } from '../../../../core/Analytics'; +import AnalyticsV2 from '../../../../util/analyticsV2'; +import { handleNetworkSwitch } from '../../../../util/networks'; import { isENS, isValidHexAddress, validateAddressOrENS, -} from '../../../../../util/address'; -import { getEther, getTicker } from '../../../../../util/transactions'; +} from '../../../../util/address'; +import { getEther, getTicker } from '../../../../util/transactions'; import { getConfusablesExplanations, hasZeroWidthPoints, -} from '../../../../../util/confusables'; -import { mockTheme, ThemeContext } from '../../../../../util/theme'; -import { showAlert } from '../../../../../actions/alert'; +} from '../../../../util/confusables'; +import { mockTheme, ThemeContext } from '../../../../util/theme'; +import { showAlert } from '../../../../actions/alert'; import { newAssetTransaction, resetTransaction, setRecipient, setSelectedAsset, -} from '../../../../../actions/transaction'; +} from '../../../../actions/transaction'; import ErrorMessage from '../ErrorMessage'; -import { strings } from '../../../../../../locales/i18n'; -import Routes from '../../../../../constants/navigation/Routes'; +import { strings } from '../../../../../locales/i18n'; +import Routes from '../../../../constants/navigation/Routes'; import { CONTACT_ALREADY_SAVED, NetworkSwitchErrorType, SYMBOL_ERROR, -} from '../../../../../constants/error'; +} from '../../../../constants/error'; import createStyles from './styles'; import { ADD_ADDRESS_BUTTON, SEND_SCREEN_ID, -} from '../../../../../../wdio/screen-objects/testIDs/Screens/SendScreen.testIds'; -import generateTestId from '../../../../../../wdio/utils/generateTestId'; +} from '../../../../../wdio/screen-objects/testIDs/Screens/SendScreen.testIds'; +import generateTestId from '../../../../../wdio/utils/generateTestId'; import { selectChainId, selectProviderType, selectTicker, -} from '../../../../../selectors/networkController'; +} from '../../../../selectors/networkController'; import { selectIdentities, selectSelectedAddress, -} from '../../../../../selectors/preferencesController'; -import AddToAddressBookWrapper from '../../../../UI/AddToAddressBookWrapper'; -import { isNetworkRampNativeTokenSupported } from '../../../../../components/UI/Ramp/utils'; -import { getRampNetworks } from '../../../../../reducers/fiatOrders'; +} from '../../../../selectors/preferencesController'; +import AddToAddressBookWrapper from '../../../UI/AddToAddressBookWrapper'; +import { isNetworkRampNativeTokenSupported } from '../../../UI/Ramp/utils'; +import { getRampNetworks } from '../../../../reducers/fiatOrders'; import SendFlowAddressFrom from '../AddressFrom'; import SendFlowAddressTo from '../AddressTo'; import { includes } from 'lodash'; -import { SendViewSelectorsIDs } from '../../../../../../e2e/selectors/SendView.selectors'; +import { SendViewSelectorsIDs } from '../../../../../e2e/selectors/SendView.selectors'; const dummy = () => true; @@ -272,7 +269,7 @@ class SendFlow extends PureComponent { break; default: alertMessage = strings('send.network_not_found_description', { - chain_id: getDecimalChainId(chainId), + chain_id: chainId, }); } Alert.alert(strings('send.network_not_found_title'), alertMessage); @@ -426,7 +423,7 @@ class SendFlow extends PureComponent { AnalyticsV2.trackEvent( MetaMetricsEvents.SEND_FLOW_SELECT_DUPLICATE_ADDRESS, { - chain_id: getDecimalChainId(this.props.chainId), + chain_id: this.props.chainId, }, ); } diff --git a/app/components/Views/confirmations/SendFlow/SendTo/styles.ts b/app/components/Views/SendFlow/SendTo/styles.ts similarity index 97% rename from app/components/Views/confirmations/SendFlow/SendTo/styles.ts rename to app/components/Views/SendFlow/SendTo/styles.ts index dd3a3965068..b9cd4749fe0 100644 --- a/app/components/Views/confirmations/SendFlow/SendTo/styles.ts +++ b/app/components/Views/SendFlow/SendTo/styles.ts @@ -1,5 +1,5 @@ import { StyleSheet } from 'react-native'; -import { fontStyles } from '../../../../../styles/common'; +import { fontStyles } from '../../../../styles/common'; const createStyles = (colors: any) => StyleSheet.create({ diff --git a/app/components/Views/confirmations/SendFlow/WarningMessage/index.tsx b/app/components/Views/SendFlow/WarningMessage/index.tsx similarity index 89% rename from app/components/Views/confirmations/SendFlow/WarningMessage/index.tsx rename to app/components/Views/SendFlow/WarningMessage/index.tsx index 83fb6ceb71e..4f2a2fe206a 100644 --- a/app/components/Views/confirmations/SendFlow/WarningMessage/index.tsx +++ b/app/components/Views/SendFlow/WarningMessage/index.tsx @@ -1,8 +1,8 @@ import React, { ReactNode } from 'react'; import { StyleProp, StyleSheet, ViewStyle } from 'react-native'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; -import Alert, { AlertType } from '../../../../Base/Alert'; -import { useTheme } from '../../../../../util/theme'; +import Alert, { AlertType } from '../../../Base/Alert'; +import { useTheme } from '../../../../util/theme'; interface Props { /** diff --git a/app/components/Views/Settings/AdvancedSettings/EthSignFriction/EthSignFriction.styles.ts b/app/components/Views/Settings/AdvancedSettings/EthSignFriction/EthSignFriction.styles.ts index 068b14f1008..d76209d01d5 100644 --- a/app/components/Views/Settings/AdvancedSettings/EthSignFriction/EthSignFriction.styles.ts +++ b/app/components/Views/Settings/AdvancedSettings/EthSignFriction/EthSignFriction.styles.ts @@ -1,7 +1,7 @@ // Third party dependencies. import { StyleSheet, TextStyle } from 'react-native'; import { typography } from '@metamask/design-tokens'; -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; /** * Style sheet function for EthSignFriction component. * diff --git a/app/components/Views/Settings/AdvancedSettings/index.js b/app/components/Views/Settings/AdvancedSettings/index.js index 9bb53c3230c..aa6e08e275e 100644 --- a/app/components/Views/Settings/AdvancedSettings/index.js +++ b/app/components/Views/Settings/AdvancedSettings/index.js @@ -52,7 +52,6 @@ import Banner, { BannerAlertSeverity, BannerVariant, } from '../../../../component-library/components/Banners/Banner'; -import { wipeTransactions } from '../../../../util/transaction-controller'; const createStyles = (colors) => StyleSheet.create({ @@ -241,8 +240,9 @@ class AdvancedSettings extends PureComponent { }; resetAccount = () => { + const { TransactionController } = Engine.context; const { navigation } = this.props; - wipeTransactions(true); + TransactionController.wipeTransactions(true); navigation.navigate('WalletView'); }; diff --git a/app/components/Views/Settings/Contacts/AmbiguousAddressSheet/AmbiguousAddressSheet.styles.ts b/app/components/Views/Settings/Contacts/AmbiguousAddressSheet/AmbiguousAddressSheet.styles.ts index f03505a6ba7..5cf4b710c6d 100644 --- a/app/components/Views/Settings/Contacts/AmbiguousAddressSheet/AmbiguousAddressSheet.styles.ts +++ b/app/components/Views/Settings/Contacts/AmbiguousAddressSheet/AmbiguousAddressSheet.styles.ts @@ -1,7 +1,7 @@ // Third party dependencies. import { StyleSheet, TextStyle } from 'react-native'; import { typography } from '@metamask/design-tokens'; -import type { ThemeColors } from '@metamask/design-tokens/dist/types/js/themes/types'; +import { ThemeColors } from '@metamask/design-tokens/dist/js/themes/types'; /** * Style sheet function for AmbiguousAddressSheet component. * diff --git a/app/components/Views/Settings/Contacts/ContactForm/index.js b/app/components/Views/Settings/Contacts/ContactForm/index.js index cbdc91e0d01..4242c3ee0cc 100644 --- a/app/components/Views/Settings/Contacts/ContactForm/index.js +++ b/app/components/Views/Settings/Contacts/ContactForm/index.js @@ -21,7 +21,7 @@ import { renderShortAddress, validateAddressOrENS, } from '../../../../../util/address'; -import ErrorMessage from '../../../confirmations/SendFlow/ErrorMessage'; +import ErrorMessage from '../../../SendFlow/ErrorMessage'; import AntIcon from 'react-native-vector-icons/AntDesign'; import ActionSheet from 'react-native-actionsheet'; import { mockTheme, ThemeContext } from '../../../../../util/theme'; diff --git a/app/components/Views/Settings/Contacts/index.js b/app/components/Views/Settings/Contacts/index.js index e1c1e68d4ac..48809f72878 100644 --- a/app/components/Views/Settings/Contacts/index.js +++ b/app/components/Views/Settings/Contacts/index.js @@ -4,7 +4,7 @@ import PropTypes from 'prop-types'; import { strings } from '../../../../../locales/i18n'; import { getNavigationOptionsTitle } from '../../../UI/Navbar'; import { connect } from 'react-redux'; -import AddressList from '../../confirmations/SendFlow/AddressList'; +import AddressList from '../../SendFlow/AddressList'; import StyledButton from '../../../UI/StyledButton'; import Engine from '../../../../core/Engine'; import ActionSheet from 'react-native-actionsheet'; diff --git a/app/components/Views/Settings/ExperimentalSettings/BlockaidIndicator/__snapshots__/BlockaidIndicator.test.tsx.snap b/app/components/Views/Settings/ExperimentalSettings/BlockaidIndicator/__snapshots__/BlockaidIndicator.test.tsx.snap index 81076bd90fd..afa0adb30ab 100644 --- a/app/components/Views/Settings/ExperimentalSettings/BlockaidIndicator/__snapshots__/BlockaidIndicator.test.tsx.snap +++ b/app/components/Views/Settings/ExperimentalSettings/BlockaidIndicator/__snapshots__/BlockaidIndicator.test.tsx.snap @@ -34,7 +34,7 @@ Array [ } > ({ context: { PreferencesController: { state: { - securityAlertsEnabled: true, + securityAlertsEnabled: false, }, setSecurityAlertsEnabled: () => undefined, }, NetworkController: { state: { providerConfig: { - chainId: '0x1', + chainId: 1, }, }, }, @@ -92,6 +92,6 @@ describe('ExperimentalSettings', () => { const toggle = wrapper.getByTestId(SECURITY_ALERTS_TOGGLE_TEST_ID); expect(toggle).toBeDefined(); - expect(toggle.props.value).toBe(true); + expect(toggle.props.value).toBe(false); }); }); diff --git a/app/components/Views/Settings/ExperimentalSettings/index.tsx b/app/components/Views/Settings/ExperimentalSettings/index.tsx index 303e813c580..0a360041535 100644 --- a/app/components/Views/Settings/ExperimentalSettings/index.tsx +++ b/app/components/Views/Settings/ExperimentalSettings/index.tsx @@ -58,15 +58,13 @@ const ExperimentalSettings = ({ navigation, route }: Props) => { const toggleSecurityAlertsEnabled = () => { if (securityAlertsEnabled) { - PreferencesController?.setSecurityAlertsEnabled(false); + PreferencesController?.setSecurityAlertsEnabled(!securityAlertsEnabled); AnalyticsV2.trackEvent( MetaMetricsEvents.SETTINGS_EXPERIMENTAL_SECURITY_ALERTS_ENABLED, { security_alerts_enabled: false, }, ); - } else if (Device.isIos()) { - PreferencesController?.setSecurityAlertsEnabled(true); } else { navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, { screen: Routes.SHEET.BLOCKAID_INDICATOR, diff --git a/app/components/Views/Settings/NetworksSettings/NetworkSettings/index.js b/app/components/Views/Settings/NetworksSettings/NetworkSettings/index.js index e273664931e..70aae0f706d 100644 --- a/app/components/Views/Settings/NetworksSettings/NetworkSettings/index.js +++ b/app/components/Views/Settings/NetworksSettings/NetworkSettings/index.js @@ -7,10 +7,9 @@ import { TextInput, SafeAreaView, Linking, + Platform, } from 'react-native'; import { connect } from 'react-redux'; -import { isSafeChainId, toHex } from '@metamask/controller-utils'; - import { fontStyles, colors as staticColors, @@ -20,6 +19,7 @@ import { strings } from '../../../../../../locales/i18n'; import Networks, { isprivateConnection, getAllNetworks, + isSafeChainId, getIsNetworkOnboarded, } from '../../../../../util/networks'; import { getEtherscanBaseUrl } from '../../../../../util/etherscan'; @@ -37,7 +37,7 @@ import AnalyticsV2 from '../../../../../util/analyticsV2'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import DefaultTabBar from 'react-native-scrollable-tab-view/DefaultTabBar'; import PopularList from '../../../../../util/networks/customNetworks'; -import WarningMessage from '../../../confirmations/SendFlow/WarningMessage'; +import WarningMessage from '../../../../Views/SendFlow/WarningMessage'; import InfoModal from '../../../../UI/Swaps/components/InfoModal'; import { DEFAULT_MAINNET_CUSTOM_NAME, @@ -55,6 +55,18 @@ import hideKeyFromUrl from '../../../../../util/hideKeyFromUrl'; import { themeAppearanceLight } from '../../../../../constants/storage'; import { scale, moderateScale } from 'react-native-size-matters'; import CustomNetwork from './CustomNetworkView/CustomNetwork'; +import generateTestId from '../../../../../../wdio/utils/generateTestId'; +import { + INPUT_CHAIN_ID_FIELD, + INPUT_RPC_URL_FIELD, + INPUT_NETWORK_NAME, + NETWORKS_SYMBOL_INPUT_FIELD, + BLOCK_EXPLORER_FIELD, + REMOVE_NETWORK_BUTTON, + CUSTOM_NETWORKS_TAB_ID, + POPULAR_NETWORKS_TAB_ID, + RPC_WARNING_BANNER_ID, +} from '../../../../../../wdio/screen-objects/testIDs/Screens/NetworksScreen.testids'; import Button, { ButtonVariants, ButtonSize, @@ -66,7 +78,6 @@ import { } from '../../../../../selectors/networkController'; import { regex } from '../../../../../../app/util/regex'; import { NetworksViewSelectorsIDs } from '../../../../../../e2e/selectors/Settings/NetworksView.selectors'; -import { updateIncomingTransactions } from '../../../../../util/transaction-controller'; const createStyles = (colors) => StyleSheet.create({ @@ -108,7 +119,7 @@ const createStyles = (colors) => paddingRight: 4, }, warningContainer: { - marginTop: 16, + marginTop: 24, flexGrow: 1, flexShrink: 1, }, @@ -245,17 +256,14 @@ class NetworkSettings extends PureComponent { addMode: false, warningRpcUrl: undefined, warningChainId: undefined, - warningSymbol: undefined, validatedRpcURL: true, validatedChainId: true, - validatedSymbol: true, initialState: undefined, enableAction: false, inputWidth: { width: '99%' }, showPopularNetworkModal: false, popularNetwork: {}, showWarningModal: false, - showNetworkDetailsModal: false, }; inputRpcURL = React.createRef(); @@ -376,6 +384,18 @@ class NetworkSettings extends PureComponent { return parseInt(chainId, 16).toString(10); } + /** + * Return the decimal chainId string as number + * + * @param {string} chainId - The chainId decimal as string to convert. + * @returns {number} The chainId decimal as number + */ + getDecimalChainIdNumber(chainId) { + const decimalChainIdString = this.getDecimalChainId(chainId); + const decimalChainIdNumber = parseInt(decimalChainIdString, 10); + return decimalChainIdNumber; + } + /** * Validates the chain ID by checking it against the `eth_chainId` return * value from the given RPC URL. @@ -474,11 +494,7 @@ class NetworkSettings extends PureComponent { route.params?.shouldNetworkSwitchPopToWallet ?? true; // Check if CTA is disabled const isCtaDisabled = - !enableAction || - this.disabledByRpcUrl() || - this.disabledByChainId() || - this.disabledBySymbol(); - + !enableAction || this.disabledByRpcUrl() || this.disabledByChainId(); if (isCtaDisabled) { return; } @@ -512,14 +528,14 @@ class NetworkSettings extends PureComponent { if (this.validateRpcUrl() && isNetworkExists.length === 0) { const url = new URL(rpcUrl); - + const decimalChainId = this.getDecimalChainId(chainId); !isprivateConnection(url.hostname) && url.set('protocol', 'https:'); CurrencyRateController.setNativeCurrency(ticker); // Remove trailing slashes NetworkController.upsertNetworkConfiguration( { rpcUrl: url.href, - chainId, + chainId: decimalChainId, ticker, nickname, rpcPrefs: { @@ -551,7 +567,7 @@ class NetworkSettings extends PureComponent { } const analyticsParamsAdd = { - chain_id: this.getDecimalChainId(chainId), + chain_id: decimalChainId, source: 'Custom network form', symbol: ticker, }; @@ -647,7 +663,7 @@ class NetworkSettings extends PureComponent { } // Check if it's a valid chainId number - if (!isSafeChainId(toHex(chainId))) { + if (!isSafeChainId(this.getDecimalChainIdNumber(chainId))) { return this.setState({ warningChainId: strings('app_settings.invalid_number_range', { maxSafeChainId: AppConstants.MAX_SAFE_CHAIN_ID, @@ -658,20 +674,6 @@ class NetworkSettings extends PureComponent { this.setState({ warningChainId: undefined, validatedChainId: true }); }; - /** - * Validates if symbol exists - * @returns - */ - validateSymbol = () => { - const { ticker } = this.state; - if (!ticker) { - return this.setState({ - warningSymbol: strings('app_settings.symbol_required'), - validatedSymbol: true, - }); - } - this.setState({ warningSymbol: undefined, validatedSymbol: true }); - }; /** * Allows to identify if any element of the form changed, in order to enable add or save button @@ -719,18 +721,6 @@ class NetworkSettings extends PureComponent { return validatedChainId && !!warningChainId; }; - /** - * Returns if action button should be disabled because of the symbol field - * Symbol field represents the ticker and needs to be set - */ - disabledBySymbol = () => { - const { ticker, validatedSymbol, warningSymbol } = this.state; - if (!ticker) { - return true; - } - return validatedSymbol && !!warningSymbol; - }; - onRpcUrlChange = async (url) => { await this.setState({ rpcUrl: url, @@ -752,7 +742,7 @@ class NetworkSettings extends PureComponent { }; onTickerChange = async (ticker) => { - await this.setState({ ticker, validatedSymbol: false }); + await this.setState({ ticker }); this.getCurrentState(); }; @@ -779,13 +769,14 @@ class NetworkSettings extends PureComponent { }; switchToMainnet = () => { - const { NetworkController, CurrencyRateController } = Engine.context; + const { NetworkController, CurrencyRateController, TransactionController } = + Engine.context; CurrencyRateController.setNativeCurrency('ETH'); NetworkController.setProviderType(MAINNET); setTimeout(async () => { - await updateIncomingTransactions(); + await TransactionController.updateIncomingTransactions(); }, 1000); }; @@ -793,7 +784,7 @@ class NetworkSettings extends PureComponent { const { navigation, networkConfigurations, providerConfig } = this.props; const { rpcUrl } = this.state; if ( - compareSanitizedUrl(rpcUrl, providerConfig.rpcUrl) && + compareSanitizedUrl(rpcUrl, providerConfig.rpcTarget) && providerConfig.type === RPC ) { this.switchToMainnet(); @@ -811,18 +802,6 @@ class NetworkSettings extends PureComponent { navigation.goBack(); }; - showNetworkModal = (networkConfiguration) => { - this.setState({ - showPopularNetworkModal: true, - popularNetwork: { - ...networkConfiguration, - formattedRpcUrl: networkConfiguration.warning - ? null - : hideKeyFromUrl(networkConfiguration.rpcUrl), - }, - }); - }; - customNetwork = (networkTypeOrRpcUrl) => { const { rpcUrl, @@ -834,7 +813,6 @@ class NetworkSettings extends PureComponent { addMode, warningRpcUrl, warningChainId, - warningSymbol, enableAction, inputWidth, } = this.state; @@ -863,39 +841,12 @@ class NetworkSettings extends PureComponent { ]; const isRPCEditable = isCustomMainnet || editable; const isActionDisabled = - !enableAction || - this.disabledByRpcUrl() || - this.disabledByChainId() || - this.disabledBySymbol(); + !enableAction || this.disabledByRpcUrl() || this.disabledByChainId(); const rpcActionStyle = isActionDisabled ? { ...styles.button, ...styles.disabledButton } : styles.button; - const url = new URL(rpcUrl); - - const selectedNetwork = { - rpcUrl: url.href, - ticker, - nickname, - rpcPrefs: { - blockExplorerUrl, - }, - }; - - const shouldNetworkSwitchPopToWallet = - route.params?.shouldNetworkSwitchPopToWallet ?? true; - - return this.state.showNetworkDetailsModal ? ( - - ) : ( + return ( @@ -939,13 +890,13 @@ class NetworkSettings extends PureComponent { placeholder={strings('app_settings.network_rpc_placeholder')} placeholderTextColor={colors.text.muted} onSubmitEditing={this.jumpToChainId} - testID={NetworksViewSelectorsIDs.RPC_URL_INPUT} + {...generateTestId(Platform, INPUT_RPC_URL_FIELD)} keyboardAppearance={themeAppearance} /> {warningRpcUrl && ( {warningRpcUrl} @@ -967,7 +918,7 @@ class NetworkSettings extends PureComponent { placeholderTextColor={colors.text.muted} onSubmitEditing={this.jumpToSymbol} keyboardType={'numbers-and-punctuation'} - testID={NetworksViewSelectorsIDs.CHAIN_INPUT} + {...generateTestId(Platform, INPUT_CHAIN_ID_FIELD)} keyboardAppearance={themeAppearance} /> {warningChainId ? ( @@ -987,20 +938,13 @@ class NetworkSettings extends PureComponent { value={ticker} editable={editable} onChangeText={this.onTickerChange} - onBlur={this.validateSymbol} - placeholder={strings('app_settings.network_symbol_label')} + placeholder={strings('app_settings.network_symbol_placeholder')} placeholderTextColor={colors.text.muted} onSubmitEditing={this.jumpBlockExplorerURL} - testID={NetworksViewSelectorsIDs.NETWORKS_SYMBOL_INPUT} + {...generateTestId(Platform, NETWORKS_SYMBOL_INPUT_FIELD)} keyboardAppearance={themeAppearance} /> - {warningSymbol ? ( - - {warningSymbol} - - ) : null} - {strings('app_settings.network_block_explorer_label')} @@ -1015,9 +959,9 @@ class NetworkSettings extends PureComponent { placeholder={strings( 'app_settings.network_block_explorer_placeholder', )} - testID={NetworksViewSelectorsIDs.BLOCK_EXPLORER_INPUT} + {...generateTestId(Platform, BLOCK_EXPLORER_FIELD)} placeholderTextColor={colors.text.muted} - onSubmitEditing={this.toggleNetworkDetailsModal} + onSubmitEditing={this.addRpcUrl} keyboardAppearance={themeAppearance} /> @@ -1041,7 +985,7 @@ class NetworkSettings extends PureComponent { variant={ButtonVariants.Secondary} isDanger onPress={this.removeRpcUrl} - testID={NetworksViewSelectorsIDs.REMOVE_NETWORK_BUTTON} + testID={REMOVE_NETWORK_BUTTON} style={{ ...styles.button, ...styles.cancel }} label={strings('app_settings.delete')} /> @@ -1060,7 +1004,7 @@ class NetworkSettings extends PureComponent {