Skip to content

Commit

Permalink
feat: Replace "Manage in settings" with "No thanks" in the STX Opt In…
Browse files Browse the repository at this point in the history
… modal, only show the modal for non-zero balances (#10337)
  • Loading branch information
dan437 authored Jul 18, 2024
1 parent 32049ff commit 104cedb
Show file tree
Hide file tree
Showing 20 changed files with 46 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
Linking,
ImageBackground,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { strings } from '../../../../locales/i18n';
import Device from '../../../util/device';
import AsyncStorage from '../../../store/async-storage-wrapper';
Expand All @@ -32,7 +31,6 @@ import backgroundImage from '../../../images/smart-transactions-opt-in-bg.png';
import { MetaMetricsEvents, useMetrics } from '../../hooks/useMetrics';
import { useDispatch } from 'react-redux';
import { updateOptInModalAppVersionSeen } from '../../../core/redux/slices/smartTransactions';
import Routes from '../../../constants/navigation/Routes';

const MODAL_MARGIN = 24;
const MODAL_PADDING = 24;
Expand Down Expand Up @@ -139,7 +137,6 @@ const SmartTransactionsOptInModal = () => {
const { colors } = useTheme();
const { trackEvent } = useMetrics();
const dispatch = useDispatch();
const navigation = useNavigation();

const styles = createStyles(colors);

Expand Down Expand Up @@ -173,9 +170,7 @@ const SmartTransactionsOptInModal = () => {
});
hasOptedIn.current = false;
await markOptInModalAsSeen();
navigation.navigate(Routes.SETTINGS_VIEW, {
screen: Routes.SETTINGS.ADVANCED_SETTINGS,
});
dismissModal();
};

const handleDismiss = async () => {
Expand Down Expand Up @@ -254,11 +249,11 @@ const SmartTransactionsOptInModal = () => {
onPress={optOut}
label={
<Text style={styles.secondaryButtonText}>
{strings('whats_new.stx.secondary_button')}
{strings('whats_new.stx.no_thanks')}
</Text>
}
>
{strings('whats_new.stx.secondary_button')}
{strings('whats_new.stx.no_thanks')}
</Button>
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
import React from 'react';
import { fireEvent, waitFor } from '@testing-library/react-native';
import { fireEvent } from '@testing-library/react-native';
import SmartTransactionsOptInModal from './SmartTranactionsOptInModal';
import renderWithProvider from '../../../util/test/renderWithProvider';
import { backgroundState } from '../../../util/test/initial-root-state';
import { strings } from '../../../../locales/i18n';
import Engine from '../../../core/Engine';
import { shouldShowWhatsNewModal } from '../../../util/onboarding';
import { updateOptInModalAppVersionSeen } from '../../../core/redux/slices/smartTransactions';
import Routes from '../../../constants/navigation/Routes';

const mockNavigate = jest.fn();
jest.mock('@react-navigation/native', () => {
Expand Down Expand Up @@ -79,11 +78,10 @@ describe('SmartTransactionsOptInModal', () => {
const primaryButton = getByText(strings('whats_new.stx.primary_button'));
expect(primaryButton).toBeDefined();

const secondaryButton = getByText(
strings('whats_new.stx.secondary_button'),
);
const secondaryButton = getByText(strings('whats_new.stx.no_thanks'));
expect(secondaryButton).toBeDefined();
});

it('should opt user in when primary button is pressed', () => {
const { getByText } = renderWithProvider(<SmartTransactionsOptInModal />, {
state: initialState,
Expand All @@ -96,26 +94,20 @@ describe('SmartTransactionsOptInModal', () => {
Engine.context.PreferencesController.setSmartTransactionsOptInStatus,
).toHaveBeenCalledWith(true);
});
it('opts user out when secondary button is pressed and navigate to Advanced Settings', async () => {

it('opts user out when secondary button is pressed', async () => {
const { getByText } = renderWithProvider(<SmartTransactionsOptInModal />, {
state: initialState,
});

const secondaryButton = getByText(
strings('whats_new.stx.secondary_button'),
);
const secondaryButton = getByText(strings('whats_new.stx.no_thanks'));
fireEvent.press(secondaryButton);

expect(
Engine.context.PreferencesController.setSmartTransactionsOptInStatus,
).toHaveBeenCalledWith(false);
expect(updateOptInModalAppVersionSeen).toHaveBeenCalledWith(VERSION);
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith(Routes.SETTINGS_VIEW, {
screen: Routes.SETTINGS.ADVANCED_SETTINGS,
});
});
});

it('should update last app version seen on primary button press', () => {
const { getByText } = renderWithProvider(<SmartTransactionsOptInModal />, {
state: initialState,
Expand All @@ -126,14 +118,13 @@ describe('SmartTransactionsOptInModal', () => {

expect(updateOptInModalAppVersionSeen).toHaveBeenCalledWith(VERSION);
});

it('should update last app version seen on secondary button press', () => {
const { getByText } = renderWithProvider(<SmartTransactionsOptInModal />, {
state: initialState,
});

const secondaryButton = getByText(
strings('whats_new.stx.secondary_button'),
);
const secondaryButton = getByText(strings('whats_new.stx.no_thanks'));
fireEvent.press(secondaryButton);

expect(updateOptInModalAppVersionSeen).toHaveBeenCalledWith(VERSION);
Expand Down
9 changes: 7 additions & 2 deletions app/components/Views/Wallet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,16 @@ const Wallet = ({
// Fired on the first load of the wallet and also on network switch
const checkSmartTransactionsOptInModal = async () => {
try {
const showShowStxOptInModal =
const accountHasZeroBalance = hexToBN(
accountBalanceByChainId?.balance || '0x0',
).isZero();
const shouldShowStxOptInModal =
await shouldShowSmartTransactionsOptInModal(
providerConfig.chainId,
providerConfig.rpcUrl,
accountHasZeroBalance,
);
if (showShowStxOptInModal) {
if (shouldShowStxOptInModal) {
navigation.navigate(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.MODAL.SMART_TRANSACTIONS_OPT_IN,
});
Expand All @@ -385,6 +389,7 @@ const Wallet = ({
networkOnboardingState,
prevChainId,
checkNftAutoDetectionModal,
accountBalanceByChainId?.balance,
]);

useEffect(
Expand Down
26 changes: 21 additions & 5 deletions app/util/onboarding/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,50 +25,66 @@ describe('shouldShowSmartTransactionOptInModal', () => {
(store.getState as jest.Mock).mockClear();
});

it('returns true if a user has not seen the modal, is on Ethereum mainnet with default RPC URL and has non-zero balance', async () => {
(AsyncStorage.getItem as jest.Mock).mockResolvedValueOnce('7.24.0'); // currentAppVersion
(store.getState as jest.Mock).mockReturnValueOnce(getMockState(null)); // versionSeen

const result = await shouldShowSmartTransactionsOptInModal(
NETWORKS_CHAIN_ID.MAINNET,
undefined,
false,
);
expect(result).toBe(true);
});

test.each([
[NETWORKS_CHAIN_ID.MAINNET, 'http://mainnet-url.example.com'],
[NETWORKS_CHAIN_ID.ARBITRUM, 'http://arbitrum-url.example.com'],
])(
`should return false if chainId not ${NETWORKS_CHAIN_ID.MAINNET} or providerConfigRpcUrl is defined`,
`returns false if chainId is not ${NETWORKS_CHAIN_ID.MAINNET} or providerConfigRpcUrl is defined`,
async (chainId, rpcUrl) => {
const result = await shouldShowSmartTransactionsOptInModal(
chainId,
rpcUrl,
false,
);
expect(result).toBe(false);
},
);

it('should return false if user has seen the modal', async () => {
it('returns false if user has seen the modal', async () => {
(AsyncStorage.getItem as jest.Mock).mockResolvedValueOnce('7.24.0'); // currentAppVersion
(store.getState as jest.Mock).mockReturnValueOnce(getMockState('7.24.0')); // versionSeen

const result = await shouldShowSmartTransactionsOptInModal(
NETWORKS_CHAIN_ID.MAINNET,
undefined,
false,
);
expect(result).toBe(false);
});

it('should return false if app version is not correct', async () => {
it('returns false if app version is not correct', async () => {
(AsyncStorage.getItem as jest.Mock).mockResolvedValueOnce('7.0.0'); // currentAppVersion
(store.getState as jest.Mock).mockReturnValueOnce(getMockState(null)); // versionSeen

const result = await shouldShowSmartTransactionsOptInModal(
NETWORKS_CHAIN_ID.MAINNET,
undefined,
false,
);
expect(result).toBe(false);
});

it('should return true if has not seen and is on mainnet with default RPC url', async () => {
it('returns false if a user has 0 balance on Ethereum Mainnet with default RPC URL', async () => {
(AsyncStorage.getItem as jest.Mock).mockResolvedValueOnce('7.24.0'); // currentAppVersion
(store.getState as jest.Mock).mockReturnValueOnce(getMockState(null)); // versionSeen

const result = await shouldShowSmartTransactionsOptInModal(
NETWORKS_CHAIN_ID.MAINNET,
undefined,
true,
);
expect(result).toBe(true);
expect(result).toBe(false);
});
});
11 changes: 5 additions & 6 deletions app/util/onboarding/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,13 @@ const STX_OPT_IN_MIN_APP_VERSION = '7.24.0';
export const shouldShowSmartTransactionsOptInModal = async (
chainId: string,
providerConfigRpcUrl: string | undefined,
accountHasZeroBalance: boolean,
) => {
// Check chain and RPC, undefined is the default RPC
if (
!(
chainId === NETWORKS_CHAIN_ID.MAINNET &&
providerConfigRpcUrl === undefined
) ||
process.env.IS_TEST === 'true'
process.env.IS_TEST === 'true' ||
chainId !== NETWORKS_CHAIN_ID.MAINNET ||
providerConfigRpcUrl !== undefined || // undefined is the default RPC URL (Infura).
accountHasZeroBalance
) {
return false;
}
Expand Down
1 change: 0 additions & 1 deletion locales/languages/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Verbesserter Transaktionsschutz",
"description_1": "Erzielen Sie mit Smart Transactions höhere Erfolgsraten, einen Frontrunning-Schutz und eine bessere Transparenz.",
"description_2": "Nur auf Ethereum verfügbar. Sie können diese Funktion jederzeit in den Einstellungen aktivieren oder deaktivieren.",
"secondary_button": "In Einstellungen verwalten",
"primary_button": "Aktivieren",
"learn_more": "Erfahren Sie mehr.",
"benefit_1_1": "Erfolgsrate:",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/el.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Ενισχυμένη Προστασία Συναλλαγών",
"description_1": "Ξεκλειδώστε υψηλότερα ποσοστά επιτυχίας, προστασία εκ των προτέρων και καλύτερη ορατότητα με τις Έξυπνες Συναλλαγές.",
"description_2": "Διατίθεται μόνο στο Ethereum. Ενεργοποίηση ή απενεργοποίηση ανά πάσα στιγμή στις ρυθμίσεις.",
"secondary_button": "Διαχείριση στις ρυθμίσεις",
"primary_button": "Ενεργοποίηση",
"learn_more": "Μάθετε περισσότερα.",
"benefit_1_1": "99,5% ποσοστό",
Expand Down
2 changes: 1 addition & 1 deletion locales/languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2706,7 +2706,7 @@
"header": "Enhanced Transaction Protection",
"description_1": "Unlock higher success rates, frontrunning protection, and better visibility with Smart Transactions.",
"description_2": "Only available on Ethereum. Enable or disable any time in settings.",
"secondary_button": "Manage in settings",
"no_thanks": "No thanks",
"primary_button": "Enable",
"learn_more": "Learn more.",
"benefit_1_1": "99.5% success",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Protección mejorada de transacciones",
"description_1": "Desbloquee índices de éxito más altos, protección contra frontrunning y mejor visibilidad con transacciones inteligentes.",
"description_2": "Solo disponible en Ethereum. Active o desactive en cualquier momento en la configuración.",
"secondary_button": "Administrar en configuración",
"primary_button": "Activar",
"learn_more": "Más información.",
"benefit_1_1": "99,5 % de índice",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Protection renforcée des transactions",
"description_1": "Bénéficiez de taux de réussite plus élevés, d’une protection contre le « front running » et d’une meilleure visibilité grâce aux transactions intelligentes.",
"description_2": "Disponible uniquement sur Ethereum. Vous pouvez activer ou désactiver cette option à tout moment dans les paramètres.",
"secondary_button": "Gérer dans les paramètres",
"primary_button": "Activer",
"learn_more": "En savoir plus.",
"benefit_1_1": "Taux de réussite de",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "उन्नत ट्रांसेक्शन सुरक्षा",
"description_1": "स्मार्ट ट्रांसेक्शन के साथ उच्च सफलता दर, फ्रंटरनिंग सुरक्षा और बेहतर दृश्यता अनलॉक करें।",
"description_2": "केवल Ethereum पर उपलब्ध है। सेटिंग्स में किसी भी समय चालू करें या बंद करें।",
"secondary_button": "सेटिंग्स में मैनेज करें",
"primary_button": "चालू करें",
"learn_more": "अधिक जानें।",
"benefit_1_1": "99.5% सफलता",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Peningkatan Perlindungan Transaksi",
"description_1": "Raih tingkat keberhasilan yang lebih tinggi, perlindungan frontrunning, dan visibilitas yang lebih baik dengan Transaksi Pintar.",
"description_2": "Hanya tersedia di Ethereum. Aktifkan atau nonaktifkan setiap saat di pengaturan.",
"secondary_button": "Kelola di pengaturan",
"primary_button": "Aktifkan",
"learn_more": "Selengkapnya.",
"benefit_1_1": "Keberhasilan 99,5%",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "強化されたトランザクション保護",
"description_1": "スマートトランザクションで、成功率を上げ、フロントランニングを防ぎ、可視性を高めましょう。",
"description_2": "イーサリアムでのみご利用いただけ、いつでも設定で有効・無効を切り替えられます。",
"secondary_button": "設定で管理",
"primary_button": "有効にする",
"learn_more": "詳細。",
"benefit_1_1": "99.5%の",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "트랜잭션 보호 강화",
"description_1": "스마트 트랜잭션으로 선행거래를 방지하고 더 높은 성공률과 가시성을 확보하세요.",
"description_2": "이더리움에서만 사용할 수 있습니다. 설정에서 언제든지 활성화하거나 비활성화할 수 있습니다.",
"secondary_button": "설정에서 관리",
"primary_button": "활성화",
"learn_more": "자세히 알아보세요.",
"benefit_1_1": "99.5% 성공",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Proteção de transações aprimorada",
"description_1": "Desbloqueie taxas de sucesso maiores, proteção contra front running e melhor visibilidade com as transações inteligentes.",
"description_2": "Disponível somente na Ethereum. Ative ou desative a qualquer momento nas configurações.",
"secondary_button": "Gerenciar nas configurações",
"primary_button": "Ativar",
"learn_more": "Saiba mais.",
"benefit_1_1": "99,5% de taxa de",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Улучшенная защита транзакций",
"description_1": "Откройте для себя более высокие коэффициенты успеха, передовую защиту и лучшую прозрачность с помощью смарт-транзакций.",
"description_2": "Доступно только на Ethereum. Включайте или отключайте в любое время в настройках.",
"secondary_button": "Управляйте в настройках",
"primary_button": "Включить",
"learn_more": "Подробнее.",
"benefit_1_1": "Показатель успеха:",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/tl.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Pinahusay na Proteksyon sa Transaksyon",
"description_1": "I-unlock ang mas mataas na tiyansa ng tagumpay, proteksyon sa frontrunning, at mas mahusay na visibility sa mga Smart Transaction.",
"description_2": "Available lamang sa Ethereum. I-enable o i-disable anumang oras sa mga setting.",
"secondary_button": "Pamahalaan sa mga setting",
"primary_button": "I-enable",
"learn_more": "Matuto pa.",
"benefit_1_1": "99.5% tagumpay",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "İyileştirilmiş İşlem Koruması",
"description_1": "Akıllı İşlemler ile daha yüksek başarı oranlarının, arkadan çalıştırma korumasının ve daha iyi görünürlüğün kilidini açın.",
"description_2": "Sadece Ethereum'da mevcuttur. Dilediğiniz zaman ayarlar kısmında etkinleştirin veya devre dışı bırakın.",
"secondary_button": "Ayarlar kısmında yönet",
"primary_button": "Etkinleştir",
"learn_more": "Daha fazla bilgi edinin.",
"benefit_1_1": "%99,5 başarı oranı",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "Tăng cường bảo vệ giao dịch",
"description_1": "Đạt tỷ lệ thành công cao hơn, bảo vệ chống hành vi lợi dụng thông tin biết trước và khả năng hiển thị tốt hơn với Giao dịch thông minh.",
"description_2": "Chỉ có sẵn trên Ethereum. Có thể bật/tắt bất cứ lúc nào trong phần Cài đặt.",
"secondary_button": "Quản lý trong phần cài đặt",
"primary_button": "Bật",
"learn_more": "Tìm hiểu thêm.",
"benefit_1_1": "Tỷ lệ thành công",
Expand Down
1 change: 0 additions & 1 deletion locales/languages/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -2652,7 +2652,6 @@
"header": "增强型交易保护",
"description_1": "通过智能交易解锁更高的成功率、抢先交易保护和更高的透明度。",
"description_2": "仅适用于以太坊。可随时在设置中启用或禁用。",
"secondary_button": "在设置中管理",
"primary_button": "启用",
"learn_more": "了解更多。",
"benefit_1_1": "99.5% 的成功",
Expand Down

0 comments on commit 104cedb

Please sign in to comment.