From 0aa9a6a687f64f28fafe998d0d9c05d871c310a0 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 09:27:38 +0530 Subject: [PATCH 1/6] Pause new USDT wallet setup and commerce Keep existing USDT wallets, Send, Receive, history, and backup routes. Remove new wallet creation and import entry points, plus buy, sell, and swap entry points. Leave the legacy GasFree Send implementation intact until a working replacement is verified. --- src/context/Localization/language/en.json | 2 + src/context/Localization/language/es.json | 2 + src/hooks/useUSDTWallets.ts | 7 + src/navigation/Navigator.tsx | 8 - .../Home/components/Wallet/HomeWallet.tsx | 189 +----------------- src/screens/Home/components/buyBtc/BuyBtc.tsx | 104 +--------- src/screens/USDT/UsdtDetails.tsx | 61 +++--- 7 files changed, 54 insertions(+), 319 deletions(-) diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index 3a451be67..a865c1c5c 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -2153,6 +2153,8 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { + "pausedTitle": "Some USDT options are paused", + "pausedBody": "New USDT wallets, buying, selling and swapping are unavailable for now. Your existing wallet, address, balance and transaction history remain here.", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index 4670ae75d..6d0f7426d 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -2134,6 +2134,8 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { + "pausedTitle": "Algunas opciones de USDT están pausadas", + "pausedBody": "Por ahora no se pueden crear nuevas carteras de USDT ni comprar, vender o intercambiar USDT. Tu cartera, dirección, saldo e historial de transacciones siguen aquí.", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/hooks/useUSDTWallets.ts b/src/hooks/useUSDTWallets.ts index 12578e9f7..f10f538f5 100644 --- a/src/hooks/useUSDTWallets.ts +++ b/src/hooks/useUSDTWallets.ts @@ -32,6 +32,9 @@ export interface UseUSDTWalletsOptions { includeHidden?: boolean; } +// Existing USDT wallets remain readable, but new wallet creation and import are paused. +export const USDT_WALLET_CREATION_PAUSED = true; + export interface UseUSDTWalletsReturn { usdtWallets: USDTWallet[]; error: string | null; @@ -101,6 +104,10 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall primaryMnemonic?: string; importDetails?: USDTWalletImportDetails; }): Promise<{ newWallet?: USDTWallet; error?: string }> => { + if (USDT_WALLET_CREATION_PAUSED) { + return { error: 'USDT wallet setup is paused' }; + } + try { setError(null); const walletNetworkType = USDTWalletSupportedNetwork; diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index dd9327ee9..50fa3849a 100644 --- a/src/navigation/Navigator.tsx +++ b/src/navigation/Navigator.tsx @@ -154,10 +154,8 @@ import SetupAdditionalServerKey from 'src/screens/SigningDevices/SetupAdditional import { MultiUserScreen } from 'src/screens/AppSettings/MultiUserScreen'; import { AddMultipleXpubFiles } from 'src/screens/AddSigner/AddMultipleXpubFiles'; import { SignMessageScreen } from 'src/screens/WalletDetails/SignMessageScreen'; -import AddUsdtWallet from 'src/screens/USDT/UsdtAddWallet'; import UsdtDetails from 'src/screens/USDT/UsdtDetails'; import RecieveUsdt from 'src/screens/USDT/RecieveUsdt'; -import BuyUstd from 'src/screens/USDT/BuyUstd'; import SendUsdt from 'src/screens/USDT/SendUsdt'; import UsdtAmount from 'src/screens/USDT/UsdtAmount'; import UsdtSendConfirmation from 'src/screens/USDT/UsdtSendConfirmation'; @@ -170,8 +168,6 @@ import KeeperSupport from 'src/screens/KeeperConcierge/KeeperSupport'; import Advisors from 'src/screens/Advisors/Advisors'; import FilterAdvisor from 'src/screens/Advisors/FilterAdvisor'; import AdvisorDetail from 'src/screens/Advisors/AdvisorDetail'; -import { Swaps } from 'src/screens/Home/components/buyBtc/Swap/Swaps'; -import { SwapDetails } from 'src/screens/Home/components/buyBtc/Swap/SwapDetails'; import { SwapHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapHistory'; import { SwapHistoryDetail } from 'src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail'; import { SwapAllHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapAllHistory'; @@ -295,10 +291,8 @@ function AppStack() { - - @@ -384,8 +378,6 @@ function AppStack() { - - diff --git a/src/screens/Home/components/Wallet/HomeWallet.tsx b/src/screens/Home/components/Wallet/HomeWallet.tsx index f277a0b79..95978a000 100644 --- a/src/screens/Home/components/Wallet/HomeWallet.tsx +++ b/src/screens/Home/components/Wallet/HomeWallet.tsx @@ -1,7 +1,6 @@ import { Box, useColorMode, View } from '@gluestack-ui/themed-native-base'; import React, { useContext, useState, useEffect } from 'react'; import { FlatList, StyleSheet, TouchableOpacity } from 'react-native'; -import DashedCta from 'src/components/DashedCta'; import WalletCard from './WalletCard'; import Colors from 'src/theme/Colors'; import useWallets from 'src/hooks/useWallets'; @@ -10,11 +9,11 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; import useWalletAsset from 'src/hooks/useWalletAsset'; -import { EntityKind, VisibilityType, WalletType } from 'src/services/wallets/enums'; -import { useNavigation, useFocusEffect, CommonActions } from '@react-navigation/native'; +import { EntityKind, VisibilityType } from 'src/services/wallets/enums'; +import { useNavigation } from '@react-navigation/native'; import KeeperModal from 'src/components/KeeperModal'; import Text from 'src/components/KeeperText'; -import { hp, windowWidth, wp } from 'src/constants/responsive'; +import { hp, wp } from 'src/constants/responsive'; import NewWalletIcon from 'src/assets/images/wallet-white-small.svg'; import ImportWalletIcon from 'src/assets/images/import.svg'; @@ -23,26 +22,18 @@ import CollaborativeWalletIcon from 'src/assets/images/collaborative_vault_white import { useAppSelector } from 'src/store/hooks'; import { resetCollaborativeSession } from 'src/store/reducers/vaults'; import { useDispatch } from 'react-redux'; -import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets'; +import { autoSyncWallets } from 'src/store/sagaActions/wallets'; import { RefreshControl } from 'react-native'; import { ELECTRUM_CLIENT } from 'src/services/electrum/client'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; import CircleIconWrapper from 'src/components/CircleIconWrapper'; -import ThemedColor from 'src/components/ThemedColor/ThemedColor'; -import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import { LocalizationContext } from 'src/context/Localization/LocContext'; -import BitCoinWalletLogo from 'src/assets/images/bitcoin-wallet-logo.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; import { getAvailableBalanceUSDTWallet, USDTWallet, - USDTWalletSupportedNetwork, - USDTWalletType, } from 'src/services/wallets/factories/USDTWalletFactory'; import useToastMessage from 'src/hooks/useToastMessage'; -import TickIcon from 'src/assets/images/icon_tick.svg'; -import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Fab from 'src/components/Fab'; import AddIcon from 'src/assets/images/add_white.svg'; import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability'; @@ -105,28 +96,24 @@ function WalletCardItem({ const HomeWallet = () => { const { colorMode } = useColorMode(); - const isDarkMode = colorMode === 'dark'; const navigation = useNavigation(); const { wallets } = useWallets({ getAll: true }); const { translations } = useContext(LocalizationContext); - const { wallet: walletText, home, common, usdtWalletText } = translations; + const { wallet: walletText, home, common } = translations; const { getWalletCardGradient, getWalletTags } = useWalletAsset(); const { allVaults } = useVault({ includeArchived: false, getFirst: true, getHiddenWallets: false, }); - const { usdtWallets, createWallet } = useUSDTWallets(); + const { usdtWallets } = useUSDTWallets(); const { collaborativeSession } = useAppSelector((state) => state.vault); - const { bitcoinNetworkType } = useAppSelector((state) => state.settings); const dispatch = useDispatch(); const [showAddWalletModal, setShowAddWalletModal] = useState(false); const [collabSessionExistsModalVisible, setCollabSessionExistsModalVisible] = useState(false); const [pullRefresh, setPullRefresh] = useState(false); const { walletSyncing } = useAppSelector((state) => state.wallet); - const [pickWalletType, setPickWalletType] = useState(false); - const [createUsdtWallet, setCreateUsdtWallet] = useState(false); const syncing = ELECTRUM_CLIENT.isClientConnected && Object.values(walletSyncing).some((isSyncing) => isSyncing); @@ -140,12 +127,6 @@ const HomeWallet = () => { ...usdtWallets, ].filter((item) => item !== null); const [isShowAmount, setIsShowAmount] = useState(false); - const DashedCta_hexagonBackgroundColor = ThemedColor({ - name: 'DashedCta_hexagonBackgroundColor', - }); - const dashed_CTA_background = ThemedColor({ - name: 'dashed_CTA_background', - }); const { showToast } = useToastMessage(); const pendingDustToast = useAppSelector((state: any) => state.utxos.pendingDustToast); @@ -176,35 +157,6 @@ const HomeWallet = () => { setPullRefresh(false); }; - const importUSDTWallet = async (mnemonic) => { - try { - const { newWallet, error } = await createWallet({ - type: USDTWalletType.IMPORTED, - name: 'USDT Wallet', - description: 'Imported USDT Wallet', - importDetails: { - mnemonic, - }, - }); - - if (newWallet) { - showToast('USDT wallet imported successfully!', ); - setTimeout(() => { - navigation.dispatch( - CommonActions.navigate({ - name: 'Home', - params: { selectedOption: 'Wallets' }, - }) - ); - }, 900); - } else { - throw new Error(error); - } - } catch (err) { - showToast(`Failed to import USDT wallet: ${err.message}`, ); - } - }; - const CREATE_WALLET_OPTIONS = [ { title: walletText.createWallet, @@ -234,38 +186,6 @@ const HomeWallet = () => { id: 'collaborativeWallet', }, ]; - const CREATE_USDT_WALLET_OPTIONS = [ - { - title: walletText.createWallet, - subtitle: 'Create a new USDT wallet', - icon: , - onPress: () => { - navigation.navigate('addUsdtWallet'); - setCreateUsdtWallet(false); - }, - id: 'usdtnewWallet', - }, - { - title: home.ImportWallet, - subtitle: walletText.restoreExistingWallet, - icon: , - onPress: () => { - setCreateUsdtWallet(false); - navigation.dispatch( - CommonActions.navigate({ - name: 'EnterSeedScreen', - params: { - isImport: true, - isUSDTWallet: true, - importSeedCta: importUSDTWallet, - }, - }) - ); - }, - id: 'usdtimportWallet', - }, - ]; - const renderWalletCard = ({ item }: { item: Wallet | Vault | USDTWallet }) => ( { } - onPress={() => setPickWalletType(true)} + onPress={() => setShowAddWalletModal(true)} /> { )} /> - setCreateUsdtWallet(false)} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - showCloseIcon - Content={() => ( - - {CREATE_USDT_WALLET_OPTIONS.map((option, index) => ( - - ))} - - )} - /> setCollabSessionExistsModalVisible(false)} @@ -343,63 +247,6 @@ const HomeWallet = () => { navigation.navigate('SetupCollaborativeWallet'); }} /> - setPickWalletType(false)} - title={usdtWalletText.pickWalletType} - subTitle={usdtWalletText.selectCurrency} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - modalBackground={`${colorMode}.modalWhiteBackground`} - Content={() => ( - - { - setShowAddWalletModal(true); - setPickWalletType(false); - }} - > - - } - backgroundColor={Colors.BrightOrange} - /> - - {usdtWalletText.bitcoinWallet} - - - - {bitcoinNetworkType === USDTWalletSupportedNetwork ? ( - { - setCreateUsdtWallet(true); - setPickWalletType(false); - }} - > - - } - backgroundColor={Colors.DesaturatedTeal} - /> - - {usdtWalletText.dollarWallet} - - - - ) : null} - - )} - /> ); }; @@ -457,26 +304,4 @@ const styles = StyleSheet.create({ borderRadius: 12, borderWidth: 1, }, - customStyle: { - marginBottom: hp(10), - }, - DashedCtaStyle: { - width: windowWidth * 0.88, - }, - walletTypeContainer: { - gap: wp(15), - marginBottom: hp(10), - flexDirection: 'row', - justifyContent: 'center', - alignContent: 'center', - }, - typeCard: { - width: wp(148), - height: hp(104), - alignItems: 'center', - borderWidth: 1, - justifyContent: 'center', - borderRadius: 12, - gap: wp(10), - }, }); diff --git a/src/screens/Home/components/buyBtc/BuyBtc.tsx b/src/screens/Home/components/buyBtc/BuyBtc.tsx index ecb21234a..060c20ef4 100644 --- a/src/screens/Home/components/buyBtc/BuyBtc.tsx +++ b/src/screens/Home/components/buyBtc/BuyBtc.tsx @@ -19,11 +19,11 @@ import useToastMessage from 'src/hooks/useToastMessage'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import AcquireCard from './AcquireCard'; import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; -import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; -import { fetchSellBtcLink, fetchSellUsdtLink } from 'src/services/thirdparty/ramp'; -import Buttons from 'src/components/Buttons'; +import { fetchSellBtcLink } from 'src/services/thirdparty/ramp'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; +import { useQuery } from '@realm/react'; +import { RealmSchema } from 'src/storage/realm/enum'; +import { SwapHistory } from './Swap/SwapHistory'; const BuyBtc = () => { const { colorMode } = useColorMode(); @@ -35,21 +35,17 @@ const BuyBtc = () => { const { buyBTC: buyBTCText, common } = translations; const [visibleBuyBtc, setVisibleBuyBtc] = useState(false); const [selectedWallet, setSelectedWallet] = useState(null); - const [selectedUsdtWallet, setSelectedUsdtWallet] = useState(null); const navigation = useNavigation(); const [graphData, setGraphData] = useState([]); const [error, setError] = useState(false); const [stats, setStats] = useState(null); const [visibleSellBtc, setVisibleSellBtc] = useState(false); - const [visibleSellUsdt, setVisibleSellUsdt] = useState(false); - const [visibleBuyUsdt, setVisibleBuyUsdt] = useState(false); const { wallets } = useWallets(); const { allVaults } = useVault({ getHiddenWallets: false }); const { showToast } = useToastMessage(); const allWallets = [...wallets, ...allVaults]; - const { usdtWallets } = useUSDTWallets(); - const [usdtPrice, setUsdtPrice] = useState(null); + const previousSwaps = useQuery(RealmSchema.SwapHistory); const [loading, setLoading] = useState(false); useEffect(() => { @@ -58,13 +54,9 @@ const BuyBtc = () => { const loadBtcPrice = async () => { try { - let [usdtData, btcPrice] = await Promise.all([ - Relay.getUsdtPrice(currencyCode), - Relay.getBtcPrice(currencyCode), - ]); + const btcPrice = await Relay.getBtcPrice(currencyCode); const { dailyPrice, high24h, latestPrice, low24h, percentChange, valueChange } = manipulateBitcoinPrices(btcPrice?.prices); - setUsdtPrice(usdtData[0].current_price.toFixed(2)); setGraphData(dailyPrice); setStats({ high24h, low24h, latestPrice, percentChange, valueChange }); } catch (error) { @@ -106,31 +98,8 @@ const BuyBtc = () => { }} graphContent={} /> - } - amount={`${BtcPrice?.symbol} ${usdtPrice ?? '--'} `} - buyCallback={() => { - if (usdtWallets.length) setVisibleBuyUsdt(true); - else showToast('Please create a USDT wallet to proceed.', ); - }} - sellCallback={() => { - if (usdtWallets.length > 0) { - setVisibleSellUsdt(true); - } else showToast("You don't have USDT yet.", ); - }} - /> + {previousSwaps.length > 0 && } - - { - navigation.dispatch(CommonActions.navigate('Swaps')); - }} - fullWidth - /> - {buyBTCText.transactionOnRamp} @@ -164,30 +133,6 @@ const BuyBtc = () => { ); }} /> - setVisibleBuyUsdt(false)} - title={buyBTCText.selectWallet} - subTitle={buyBTCText.selectWalletDesc} - modalBackground={`${colorMode}.modalWhiteBackground`} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - Content={() => ( - - )} - buttonText={selectedUsdtWallet ? common.proceed : null} - buttonCallback={() => { - if (!selectedUsdtWallet) return; - setVisibleBuyUsdt(false); - navigation.dispatch( - CommonActions.navigate({ name: 'buyUstd', params: { usdtWallet: selectedUsdtWallet } }) - ); - }} - /> setVisibleSellBtc(false)} @@ -218,36 +163,6 @@ const BuyBtc = () => { } }} /> - setVisibleSellUsdt(false)} - title={buyBTCText.proceedToRamp} - modalBackground={`${colorMode}.modalWhiteBackground`} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - Content={() => ( - - {buyBTCText.rediredctToRampPage} - - )} - buttonText={common.confirm} - buttonCallback={async () => { - try { - setLoading(true); - setVisibleSellUsdt(false); - const url = await fetchSellUsdtLink(); - Linking.openURL(url.toString()); - } catch (error) { - showToast('Error while fetching ramp url'); - } finally { - setLoading(false); - } - }} - /> ); @@ -296,11 +211,6 @@ const styles = StyleSheet.create({ width: wp(160), borderRadius: 8, }, - button_container: { - width: windowWidth, - marginVertical: hp(10), - paddingHorizontal: wp(12), - }, info_container: { maxWidth: windowWidth, paddingHorizontal: wp(12), diff --git a/src/screens/USDT/UsdtDetails.tsx b/src/screens/USDT/UsdtDetails.tsx index 745964ce3..1f0d03536 100644 --- a/src/screens/USDT/UsdtDetails.tsx +++ b/src/screens/USDT/UsdtDetails.tsx @@ -13,9 +13,6 @@ import { getAvailableBalanceUSDTWallet } from 'src/services/wallets/factories/US import WalletDetailHeader from '../WalletDetails/components/WalletDetailHeader'; import DetailCards from '../WalletDetails/components/DetailCards'; import ThemedColor from 'src/components/ThemedColor/ThemedColor'; -import MoreCard from '../WalletDetails/components/MoreCard'; -import KeeperModal from 'src/components/KeeperModal'; -import SwapSvg from 'src/assets/images/swap.svg'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) { @@ -39,13 +36,12 @@ const UsdtDetails = ({ route }) => { const { colorMode } = useColorMode(); const navigation = useNavigation(); const { translations } = useContext(LocalizationContext); - const { common } = translations; + const { common, usdtWalletText } = translations; const { getWalletCardGradient, getWalletTags } = useWalletAsset(); const [pullRefresh, setPullRefresh] = useState(false); const { usdtWalletId } = route.params || {}; const { getWalletById } = useUSDTWallets(); const usdtWallet = getWalletById(usdtWalletId); - const [showmore, setShowMore] = useState(false); const viewAll_color = ThemedColor({ name: 'viewAll_color' }); return ( @@ -64,21 +60,28 @@ const UsdtDetails = ({ route }) => { navigation.dispatch(CommonActions.navigate('sendUsdt', { usdtWallet })) } receiveCallback={() => navigation.dispatch(CommonActions.navigate('usdtReceive', { usdtWallet })) } - buyCallback={() => - navigation.dispatch(CommonActions.navigate('buyUstd', { usdtWallet })) - } wallet={usdtWallet} /> + + + {usdtWalletText.pausedTitle} + + + {usdtWalletText.pausedBody} + + {usdtWallet ? ( { )} - setShowMore(false)} - title={common.moreOptions} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - textColor={`${colorMode}.textGreen`} - modalBackground={`${colorMode}.modalWhiteBackground`} - Content={() => { - return ( - - { - setShowMore(false); - }} - Icon={} - /> - - ); - }} - /> ); }; @@ -168,7 +150,7 @@ const styles = StyleSheet.create({ paddingHorizontal: 18, }, walletContainer: { - paddingTop: wp(30), + paddingTop: hp(8), paddingBottom: 20, flex: 1, justifyContent: 'space-between', @@ -227,6 +209,21 @@ const styles = StyleSheet.create({ justifyContent: 'center', marginTop: hp(20), }, + pausedNotice: { + marginHorizontal: wp(22), + marginTop: hp(65), + paddingHorizontal: wp(16), + paddingVertical: hp(12), + borderWidth: 1, + borderRadius: 10, + }, + pausedTitle: { + fontSize: wp(14), + }, + pausedBody: { + fontSize: wp(12), + marginTop: hp(6), + }, detailCardsContainer: { zIndex: 1000, }, From bec7cd9d39026e3351af48a2fd1f2ad794fdb988 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 09:36:43 +0530 Subject: [PATCH 2/6] Retire GasFree client and pause legacy USDT sends Keep saved USDT wallets, receive addresses, chain reads, history, and backup recovery. Make Send show a pause message and warn before new deposits. Reject retired GasFree and swap credentials in release inputs and direct Android builds. --- android/app/build.gradle | 9 +- appcenter-pre-build.sh | 15 +- package.json | 2 +- scripts/verify-channel-config.cjs | 7 +- scripts/verify-channel-config.test.cjs | 66 +++ src/context/Localization/language/en.json | 7 +- src/context/Localization/language/es.json | 7 +- src/navigation/Navigator.tsx | 6 - .../buyBtc/Swap/SwapHistoryDetail.tsx | 2 +- .../Home/components/buyBtc/Swap/Swaps.tsx | 34 +- .../buyBtc/Swap/component/CoinLogo.tsx | 36 ++ .../Swap/component/SwapTransactionCard.tsx | 2 +- src/screens/USDT/RecieveUsdt.tsx | 33 +- src/screens/USDT/UsdtDetails.tsx | 17 +- src/services/rest/SwapClient.ts | 30 - .../wallets/factories/USDTWalletFactory.ts | 61 +- .../wallets/operations/dollars/GasFree.ts | 538 +----------------- .../wallets/operations/dollars/USDT.ts | 424 ++------------ src/utils/service-utilities/config.ts | 5 - tests/recovery/usdtBackup.test.cjs | 12 +- tests/services/usdtPause.test.cjs | 136 +++++ 21 files changed, 405 insertions(+), 1044 deletions(-) create mode 100644 scripts/verify-channel-config.test.cjs create mode 100644 src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx delete mode 100644 src/services/rest/SwapClient.ts create mode 100644 tests/services/usdtPause.test.cjs diff --git a/android/app/build.gradle b/android/app/build.gradle index b73b4caad..498a07327 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -2,6 +2,13 @@ apply plugin: "com.android.application" apply plugin: "com.facebook.react" apply plugin: 'com.google.gms.google-services' apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" +// react-native-config embeds every selected env key, even when JavaScript does not use it. +// Check the resolved env map so direct Gradle builds cannot package retired credentials. +def retiredCredentialKeys = ['GASFREE_API_KEY', 'GASFREE_API_SECRET', + 'LETS_EXCHANGE_API_KEY'].collectMany { [it, "RN_${it}"] } +if (retiredCredentialKeys.any { project.ext.env.containsKey(it) }) { + throw new GradleException('Retired API credentials must not be included in an Android build') +} apply plugin: 'kotlin-android' /** @@ -205,4 +212,4 @@ dependencies { implementation 'com.itextpdf:itextg:5.5.10' -} \ No newline at end of file +} diff --git a/appcenter-pre-build.sh b/appcenter-pre-build.sh index 6adc321a7..3705a26b9 100644 --- a/appcenter-pre-build.sh +++ b/appcenter-pre-build.sh @@ -1,8 +1,19 @@ #!/usr/bin/env bash # Creates an .env from ENV variables for use with react-native-config +set -eu + +if [ -n "${RN_GASFREE_API_KEY+x}" ] || [ -n "${RN_GASFREE_API_SECRET+x}" ] || [ -n "${RN_LETS_EXCHANGE_API_KEY+x}" ]; then + printf "Retired API credentials must not be included in a mobile build\n" >&2 + exit 1 +fi + ENV_WHITELIST=${ENV_WHITELIST:-"^RN_"} printf "Creating an .env file with the following whitelist:\n" printf "%s\n" $ENV_WHITELIST set | egrep -e $ENV_WHITELIST | sed 's/^RN_//g' > .env -printf "\n.env created with contents:\n\n" -cat .env \ No newline at end of file +if grep -Eq '^(RN_)?(GASFREE_API_(KEY|SECRET)|LETS_EXCHANGE_API_KEY)=' .env; then + rm .env + printf "Retired API credentials must not be included in a mobile build\n" >&2 + exit 1 +fi +printf ".env created\n" diff --git a/package.json b/package.json index ad0eeb2c1..b0344c35d 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "iosProd": "npx react-native run-ios --scheme=hexa_keeper --simulator 'iPhone 16' ", "start": "react-native start", "test": "jest", - "test:release": "node --test scripts/release-version.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'", + "test:release": "node --test scripts/release-version.test.cjs scripts/verify-channel-config.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'", "version:inspect": "node scripts/release-version.cjs inspect", "version:check": "node scripts/release-version.cjs check", "version:apply": "node scripts/release-version.cjs apply", diff --git a/scripts/verify-channel-config.cjs b/scripts/verify-channel-config.cjs index 18ecc3173..401bd7be0 100644 --- a/scripts/verify-channel-config.cjs +++ b/scripts/verify-channel-config.cjs @@ -7,7 +7,12 @@ if (!envFile || !fs.existsSync(envFile)) { throw new Error('Production environment file is missing'); } -const matches = fs.readFileSync(envFile, 'utf8') +const envContents = fs.readFileSync(envFile, 'utf8'); +if (/^\s*(?:export\s+)?(?:RN_)?(?:GASFREE_API_(?:KEY|SECRET)|LETS_EXCHANGE_API_KEY)\s*=/m.test(envContents)) { + throw new Error('Retired API credentials must not be included in a release environment'); +} + +const matches = envContents .split(/\r?\n/) .map(line => line.match(/^\s*(?:export\s+)?CHANNEL_URL\s*=\s*(.*?)\s*$/)) .filter(Boolean) diff --git a/scripts/verify-channel-config.test.cjs b/scripts/verify-channel-config.test.cjs new file mode 100644 index 000000000..844253bc9 --- /dev/null +++ b/scripts/verify-channel-config.test.cjs @@ -0,0 +1,66 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const verifier = path.join(__dirname, 'verify-channel-config.cjs'); +const prebuild = path.join(__dirname, '..', 'appcenter-pre-build.sh'); +const channel = 'CHANNEL_URL=https://channel.bitcoinkeeper.app/\n'; + +function withTempDirectory(run) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-usdt-env-')); + try { + return run(directory); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +test('release env accepts reviewed channel without retired credentials', () => + withTempDirectory((directory) => { + const envFile = path.join(directory, '.env.production'); + fs.writeFileSync(envFile, channel); + const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + })); + +for (const name of ['GASFREE_API_KEY', 'GASFREE_API_SECRET', 'RN_GASFREE_API_KEY', + 'LETS_EXCHANGE_API_KEY', 'RN_LETS_EXCHANGE_API_KEY']) { + test(`release env rejects ${name} without logging its value`, () => + withTempDirectory((directory) => { + const envFile = path.join(directory, '.env.production'); + const secret = 'synthetic-secret-not-for-output'; + fs.writeFileSync(envFile, `${channel}${name}=${secret}\n`); + const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' }); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); +} + +test('AppCenter rejects retired credential input before writing .env', () => + withTempDirectory((directory) => { + const secret = 'synthetic-secret-not-for-output'; + const result = spawnSync('bash', [prebuild], { + cwd: directory, + env: { PATH: process.env.PATH, RN_GASFREE_API_SECRET: secret }, + encoding: 'utf8', + }); + assert.notEqual(result.status, 0); + assert.equal(fs.existsSync(path.join(directory, '.env')), false); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); + +test('AppCenter rejects retired swap credential input before writing .env', () => + withTempDirectory((directory) => { + const secret = 'synthetic-secret-not-for-output'; + const result = spawnSync('bash', [prebuild], { + cwd: directory, + env: { PATH: process.env.PATH, RN_LETS_EXCHANGE_API_KEY: secret }, + encoding: 'utf8', + }); + assert.notEqual(result.status, 0); + assert.equal(fs.existsSync(path.join(directory, '.env')), false); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index a865c1c5c..b93cb5be2 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -2153,8 +2153,11 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { - "pausedTitle": "Some USDT options are paused", - "pausedBody": "New USDT wallets, buying, selling and swapping are unavailable for now. Your existing wallet, address, balance and transaction history remain here.", + "pausedTitle": "USDT activity is limited", + "pausedBody": "New USDT wallets, sending, buying, selling and swapping are paused. This wallet, its balance and history remain available.", + "sendingPausedTitle": "USDT sending is paused", + "sendingPausedBody": "Keeper cannot send USDT from this wallet right now. Your wallet details, balance and transaction history remain available.", + "receivePausedWarning": "This is your wallet's saved receive address. Keeper cannot send USDT from this wallet while sending is paused. Funds received here cannot be sent through Keeper during the pause. Do not deposit new USDT unless you understand this limitation.", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index 6d0f7426d..803c3e55d 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -2134,8 +2134,11 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { - "pausedTitle": "Algunas opciones de USDT están pausadas", - "pausedBody": "Por ahora no se pueden crear nuevas carteras de USDT ni comprar, vender o intercambiar USDT. Tu cartera, dirección, saldo e historial de transacciones siguen aquí.", + "pausedTitle": "La actividad de USDT está limitada", + "pausedBody": "La creación de carteras de USDT, el envío, la compra, la venta y el intercambio están pausados. Esta cartera, su saldo e historial siguen disponibles.", + "sendingPausedTitle": "El envío de USDT está pausado", + "sendingPausedBody": "Keeper no puede enviar USDT desde esta cartera ahora mismo. Los detalles, el saldo y el historial de transacciones de la cartera siguen disponibles.", + "receivePausedWarning": "Esta es la dirección de recepción guardada de tu cartera. Keeper no puede enviar USDT desde esta cartera mientras el envío esté pausado. Los fondos recibidos aquí no se pueden enviar mediante Keeper durante la pausa. No deposites nuevos USDT a menos que comprendas esta limitación.", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index 50fa3849a..b89ab6a51 100644 --- a/src/navigation/Navigator.tsx +++ b/src/navigation/Navigator.tsx @@ -156,9 +156,6 @@ import { AddMultipleXpubFiles } from 'src/screens/AddSigner/AddMultipleXpubFiles import { SignMessageScreen } from 'src/screens/WalletDetails/SignMessageScreen'; import UsdtDetails from 'src/screens/USDT/UsdtDetails'; import RecieveUsdt from 'src/screens/USDT/RecieveUsdt'; -import SendUsdt from 'src/screens/USDT/SendUsdt'; -import UsdtAmount from 'src/screens/USDT/UsdtAmount'; -import UsdtSendConfirmation from 'src/screens/USDT/UsdtSendConfirmation'; import UsdtTransactionDetail from 'src/screens/USDT/UsdtTransactionDetail'; import UsdtTransactionHistory from 'src/screens/USDT/UsdtTransactionHistory'; import Usdtsetting from 'src/screens/USDT/Usdtsetting'; @@ -293,9 +290,6 @@ function AppStack() { - - - diff --git a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx index 9d4683f5d..d658f6a45 100644 --- a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx +++ b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx @@ -8,7 +8,7 @@ import useToastMessage from 'src/hooks/useToastMessage'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import { useDispatch } from 'react-redux'; import { getTnxDetails } from 'src/store/sagaActions/swap'; -import { CoinLogo } from './Swaps'; +import { CoinLogo } from './component/CoinLogo'; import { StyleSheet } from 'react-native'; import CircleIconWrapper from 'src/components/CircleIconWrapper'; import { hp, wp } from 'src/constants/responsive'; diff --git a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx index 1b382f267..9bcc6d6ff 100644 --- a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx +++ b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx @@ -14,8 +14,6 @@ import { useAppSelector } from 'src/store/hooks'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Checked from 'src/assets/images/tick_icon.svg'; import { createSwapTnx, getSwapQuote, loadCoinDetails } from 'src/store/sagaActions/swap'; -import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; import Colors from 'src/theme/Colors'; import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; import useVault from 'src/hooks/useVault'; @@ -23,41 +21,11 @@ import useWallets from 'src/hooks/useWallets'; import KeeperModal from 'src/components/KeeperModal'; import BuyBtcModalContent from '../BuyBtcModalContent'; import { SwapHistory } from './SwapHistory'; -import CircleIconWrapper from 'src/components/CircleIconWrapper'; import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import { EntityKind } from 'src/services/wallets/enums'; +import { CoinLogo } from './component/CoinLogo'; -export const CoinLogo = ({ - code, - CircleWidth, - logoWidth, - logoHeight, -}: { - code: string; - isLarge?: boolean; - CircleWidth?: number; - logoWidth?: number; - logoHeight?: number; -}) => { - const isBtc = code === 'BTC'; - - return ( - - - ) : ( - - ) - } - backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal} - width={CircleWidth} - /> - - ); -}; export const SwitchButton = ({ onPress, coinData }) => { const { colorMode } = useColorMode(); diff --git a/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx new file mode 100644 index 000000000..a5f438363 --- /dev/null +++ b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx @@ -0,0 +1,36 @@ +import { Box } from '@gluestack-ui/themed-native-base'; +import React from 'react'; +import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; +import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; +import CircleIconWrapper from 'src/components/CircleIconWrapper'; +import Colors from 'src/theme/Colors'; + +export const CoinLogo = ({ + code, + CircleWidth, + logoWidth, + logoHeight, +}: { + code: string; + CircleWidth?: number; + logoWidth?: number; + logoHeight?: number; +}) => { + const isBtc = code === 'BTC'; + + return ( + + + ) : ( + + ) + } + backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal} + width={CircleWidth} + /> + + ); +}; diff --git a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx index 0cc07b923..ec600bec8 100644 --- a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx +++ b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx @@ -15,7 +15,7 @@ import SwapConfirmingIcon from '../../../../../../assets/images/swap-confirmint. import SwapProcessingIcon from '../../../../../../assets/images/swap-processing.svg'; import SwapSuccessIcon from '../../../../../../assets/images/swap-success.svg'; import SwapOverDueIcon from '../../../../../../assets/images/swap-overDue.svg'; -import { CoinLogo } from '../Swaps'; +import { CoinLogo } from './CoinLogo'; import SwapPriceArrow from 'src/assets/images/swap-price-arrow.svg'; import SwapPriceArrowWhite from 'src/assets/images/swap-price-arrow-white.svg'; diff --git a/src/screens/USDT/RecieveUsdt.tsx b/src/screens/USDT/RecieveUsdt.tsx index 68cdbd2c1..b7c0637aa 100644 --- a/src/screens/USDT/RecieveUsdt.tsx +++ b/src/screens/USDT/RecieveUsdt.tsx @@ -1,6 +1,6 @@ import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import React, { useContext } from 'react'; -import { StyleSheet } from 'react-native'; +import { ScrollView, StyleSheet } from 'react-native'; import KeeperQRCode from 'src/components/KeeperQRCode'; import Text from 'src/components/KeeperText'; import ScreenWrapper from 'src/components/ScreenWrapper'; @@ -19,9 +19,22 @@ const RecieveUsdt = ({ route }) => { return ( - + + + + {usdtWalletText.sendingPausedTitle} + + + {usdtWalletText.receivePausedWarning} + + + { {usdtWalletText.sendOnlyUsdt} - + ); }; @@ -54,6 +67,20 @@ const RecieveUsdt = ({ route }) => { export default RecieveUsdt; const styles = StyleSheet.create({ + scrollContent: { + flexGrow: 1, + }, + warning: { + borderWidth: 1, + borderRadius: 10, + marginHorizontal: 16, + marginTop: hp(12), + paddingHorizontal: 16, + paddingVertical: hp(12), + }, + warningBody: { + marginTop: hp(6), + }, container: { alignItems: 'center', marginTop: hp(20), diff --git a/src/screens/USDT/UsdtDetails.tsx b/src/screens/USDT/UsdtDetails.tsx index 1f0d03536..c8e751b50 100644 --- a/src/screens/USDT/UsdtDetails.tsx +++ b/src/screens/USDT/UsdtDetails.tsx @@ -14,6 +14,7 @@ import WalletDetailHeader from '../WalletDetails/components/WalletDetailHeader'; import DetailCards from '../WalletDetails/components/DetailCards'; import ThemedColor from 'src/components/ThemedColor/ThemedColor'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; +import KeeperModal from 'src/components/KeeperModal'; function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) { const [initialLoading, setInitialLoading] = useState(false); @@ -43,6 +44,7 @@ const UsdtDetails = ({ route }) => { const { getWalletById } = useUSDTWallets(); const usdtWallet = getWalletById(usdtWalletId); const viewAll_color = ThemedColor({ name: 'viewAll_color' }); + const [showSendPaused, setShowSendPaused] = useState(false); return ( @@ -60,9 +62,7 @@ const UsdtDetails = ({ route }) => { - navigation.dispatch(CommonActions.navigate('sendUsdt', { usdtWallet })) - } + sendCallback={() => setShowSendPaused(true)} receiveCallback={() => navigation.dispatch(CommonActions.navigate('usdtReceive', { usdtWallet })) } @@ -136,6 +136,17 @@ const UsdtDetails = ({ route }) => { )} + setShowSendPaused(false)} + title={usdtWalletText.sendingPausedTitle} + subTitle={usdtWalletText.sendingPausedBody} + modalBackground={`${colorMode}.modalWhiteBackground`} + textColor={`${colorMode}.textGreen`} + subTitleColor={`${colorMode}.modalSubtitleBlack`} + buttonText={common.ok} + buttonCallback={() => setShowSendPaused(false)} + /> ); }; diff --git a/src/services/rest/SwapClient.ts b/src/services/rest/SwapClient.ts deleted file mode 100644 index 405f6e460..000000000 --- a/src/services/rest/SwapClient.ts +++ /dev/null @@ -1,30 +0,0 @@ -import axios from 'axios'; -import config from 'src/utils/service-utilities/config'; - -export const swapApi = axios.create({ - baseURL: config.LETS_EXCHANGE_BASE_URL, -}); - -swapApi.interceptors.request.use( - (req) => { - req.headers.Authorization = `Bearer ${config.LETS_EXCHANGE_API_KEY}`; - if (req.method === 'post') { - req.data = { - ...req.data, - affiliate_id: config.LETS_EXCHANGE_AFFILIATE_ID, - }; - } - - return req; - }, - (error) => { - return Promise.reject(error); - } -); - -export const swapEndpoints = { - coins: 'v1/coins', - coinsInfo: 'v1/info/bulk', - quote: '/v1/info', - tnx: 'v1/transaction', -}; diff --git a/src/services/wallets/factories/USDTWalletFactory.ts b/src/services/wallets/factories/USDTWalletFactory.ts index 2b2744abf..9543d2b8e 100644 --- a/src/services/wallets/factories/USDTWalletFactory.ts +++ b/src/services/wallets/factories/USDTWalletFactory.ts @@ -187,22 +187,22 @@ export const checkUSDTWalletExists = (address: string, existingWallets: USDTWall }; /** - * Update USDT wallet specs with latest account status + * Preserve stored account information. The retired provider is no longer + * queried, and the saved GasFree address is needed for chain reads. */ export const updateUSDTWalletAccountStatus = async ( wallet: USDTWallet ): Promise => { - try { - return USDT.getAccountStatus(wallet.specs.address, wallet.networkType); - } catch (error) { - return wallet.accountStatus; - } + return wallet.accountStatus; }; /** * Syncs USDT wallet w/ latest balance */ export const syncUSDTWalletBalance = async (wallet: USDTWallet) => { + if (!wallet.accountStatus?.gasFreeAddress) { + throw new Error('Stored USDT address is unavailable'); + } const balance = await USDT.getUSDTBalance( wallet.accountStatus.gasFreeAddress, wallet.networkType @@ -215,7 +215,9 @@ export const syncUSDTWalletBalance = async (wallet: USDTWallet) => { * Evaluates USDT wallet's available balance */ export const getAvailableBalanceUSDTWallet = (wallet: USDTWallet): number => { - return wallet.specs.balance - wallet.accountStatus.frozen; // frozen amount is currently under process w/ the GasFree service provider(in-process permit transfers) + // Provider-reported frozen funds cannot be refreshed after retirement. + // The on-chain balance is the amount shown for the existing wallet. + return wallet.specs.balance; }; /** @@ -224,51 +226,20 @@ export const getAvailableBalanceUSDTWallet = (wallet: USDTWallet): number => { export const syncUSDTWalletTransactions = async (wallet: USDTWallet) => { const existingTransactions = wallet.specs.transactions || []; - // Step 1: Update existing transactions that have traceId but no txId - const updatedExistingTransactions = await Promise.all( - existingTransactions.map(async (existingTx) => { - // If transaction has traceId but no txId, try to fetch the txId - if (existingTx.traceId && !existingTx.txId) { - try { - const transferStatus = await USDT.getTransferStatus( - existingTx.traceId, - wallet.networkType - ); - // Update transaction with new information if available - if (transferStatus.transactionHash) { - const blockNumber = transferStatus.blockInfo?.blockNumber || existingTx.blockNumber; - const status = blockNumber - ? GasFreeTransferStatus.SUCCEED - : transferStatus.status || existingTx.status; - return { - ...existingTx, - txId: transferStatus.transactionHash || existingTx.txId, - status, - blockNumber: blockNumber, - // Update timestamp if we got block timestamp - timestamp: transferStatus.blockInfo?.blockTimestamp - ? transferStatus.blockInfo.blockTimestamp - : existingTx.timestamp, - }; - } - } catch (error) { - // If fetch fails, keep the original transaction - console.warn(`Failed to update transaction with traceId ${existingTx.traceId}:`, error); - } - } + if (!wallet.accountStatus?.gasFreeAddress) { + throw new Error('Stored USDT address is unavailable'); + } - // Return original transaction if no update needed or failed - return existingTx; - }) - ); + // Preserve trace-only entries without assigning a false failure status. + const updatedExistingTransactions = existingTransactions; - // Step 2: Fetch new transactions from USDT service + // Fetch new transactions directly from TRON. const { transactions: newTransactions } = await USDT.getUSDTTransactions( wallet.accountStatus.gasFreeAddress, wallet.networkType ); - // Step 3: Merge transactions using updated existing transactions + // Merge chain transactions with the stored history. const mergedTransactions = [...updatedExistingTransactions]; // Process each new transaction diff --git a/src/services/wallets/operations/dollars/GasFree.ts b/src/services/wallets/operations/dollars/GasFree.ts index ad41f62fa..3c9507a7a 100644 --- a/src/services/wallets/operations/dollars/GasFree.ts +++ b/src/services/wallets/operations/dollars/GasFree.ts @@ -1,83 +1,4 @@ -import { AxiosResponse } from 'axios'; -import { NetworkType } from 'src/services/wallets/enums'; -import RestClient from '../../../rest/RestClient'; -import * as crypto from 'crypto'; -import config from '../../../../utils/service-utilities/config'; -import { createTronWeb } from './Tron'; -import idx from 'idx'; - -// GasFree API endpoints -const GASFREE_ENDPOINTS = { - [NetworkType.MAINNET]: 'https://open.gasfree.io/tron/', - [NetworkType.TESTNET]: 'https://open-test.gasfree.io/nile/', -}; - -// Network parameters for signature -const NETWORK_PARAMS = { - [NetworkType.MAINNET]: { - chainId: 728126428, - verifyingContract: 'TFFAMQLZybALaLb4uxHA9RBE7pxhUAjF3U', - }, - [NetworkType.TESTNET]: { - chainId: 3448148188, - verifyingContract: 'THQGuFzL87ZqhxkgqYEryRAd7gqFqL5rdc', - }, -}; - -// GasFree Interfaces -export interface GasFreeToken { - tokenAddress: string; - createdAt: string; - updatedAt: string; - activateFee: number; - transferFee: number; - supported: boolean; - symbol: string; - decimal: number; -} - -export interface GasFreeProvider { - address: string; - name: string; - icon: string; - website: string; - config: { - maxPendingTransfer: number; - minDeadlineDuration: number; - maxDeadlineDuration: number; - defaultDeadlineDuration: number; - }; -} - -export interface GasFreeAccountInfo { - accountAddress: string; - gasFreeAddress: string; - active: boolean; - nonce: number; - allowSubmit: boolean; - assets: Array<{ - tokenAddress: string; - tokenSymbol: string; - activateFee: number; - transferFee: number; - decimal: number; - frozen: number; - }>; -} - -export interface GasFreeTransferRequest { - token: string; - serviceProvider: string; - user: string; - receiver: string; - value: string; - maxFee: string; - deadline: string; - version: number; - nonce: number; - sig: string; -} - +/** Historical transfer states remain in stored USDT transactions. */ export enum GasFreeTransferStatus { WAITING = 'WAITING', INPROGRESS = 'INPROGRESS', @@ -85,460 +6,3 @@ export enum GasFreeTransferStatus { SUCCEED = 'SUCCEED', FAILED = 'FAILED', } - -export interface GasFreeTransferResponse { - id: string; - createdAt: string; - updatedAt: string; - accountAddress: string; - gasFreeAddress: string; - providerAddress: string; - targetAddress: string; - tokenAddress: string; - amount: string; - maxFee: string; - signature: string; - version: number; - nonce: number; - expiredAt: string; - state: GasFreeTransferStatus; - estimatedActivateFee: number; - estimatedTransferFee: number; -} - -export interface GasFreeTransferDetails extends GasFreeTransferResponse { - estimatedTotalFee: number; - estimatedTotalCost: number; - txnHash?: string; - txnBlockNum?: number; - txnBlockTimestamp?: number; - txnState?: 'INIT' | 'NOT_ON_CHAIN' | 'ON_CHAIN' | 'SOLIDITY' | 'ON_CHAIN_FAILED'; - txnActivateFee?: number; - txnTransferFee?: number; - txnTotalFee?: number; - txnAmount?: string; - txnTotalCost?: number; -} - -export interface GasFreeSignaturePayload { - token: string; - serviceProvider: string; - user: string; - receiver: string; - value: string; - maxFee: string; - deadline: string; - version: number; - nonce: number; -} - -export interface GasFreeAPIResponse { - code: number; - reason: string | null; - message: string | null; - data: T; -} - -export interface GasFreeAPICredentials { - apiKey: string; - apiSecret: string; -} - -// TIP-712 Signing Types for GasFree -export interface TIP712Domain { - name: string; - version: string; - chainId: number; - verifyingContract: string; -} - -export interface TIP712TypeProperty { - name: string; - type: string; -} - -export interface TIP712MessageTypes { - PermitTransfer: TIP712TypeProperty[]; -} - -export interface Permit712MessageDomain extends TIP712Domain { - name: 'GasFreeController'; - version: 'V1.0.0'; - chainId: number; // Network specific chain ID in decimal - verifyingContract: string; // GasFreeController contract address -} - -export interface Permit712MessageTypes extends TIP712MessageTypes { - PermitTransfer: [ - { name: 'token'; type: 'address' }, - { name: 'serviceProvider'; type: 'address' }, - { name: 'user'; type: 'address' }, - { name: 'receiver'; type: 'address' }, - { name: 'value'; type: 'uint256' }, - { name: 'maxFee'; type: 'uint256' }, - { name: 'deadline'; type: 'uint256' }, - { name: 'version'; type: 'uint256' }, - { name: 'nonce'; type: 'uint256' } - ]; -} - -export default class GasFree { - private static credentials: GasFreeAPICredentials = { - // Mainnet ONLY – Testnet access is not available to end users - apiKey: config.GASFREE_API_KEY, - apiSecret: config.GASFREE_API_SECRET, - }; - - // TIP-712 Constants - private static readonly TIP712_MESSAGE_TYPES: Permit712MessageTypes = { - PermitTransfer: [ - { name: 'token', type: 'address' }, - { name: 'serviceProvider', type: 'address' }, - { name: 'user', type: 'address' }, - { name: 'receiver', type: 'address' }, - { name: 'value', type: 'uint256' }, - { name: 'maxFee', type: 'uint256' }, - { name: 'deadline', type: 'uint256' }, - { name: 'version', type: 'uint256' }, - { name: 'nonce', type: 'uint256' }, - ], - }; - - // Fixed values as per GasFree documentation - private static readonly TIP712_DOMAIN_NAME = 'GasFreeController'; - private static readonly TIP712_DOMAIN_VERSION = 'V1.0.0'; - private static readonly SIGNATURE_VERSION = 1; - - /** - * Get the appropriate endpoint URL based on network type - */ - private static getEndpointURL(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return GASFREE_ENDPOINTS[network]; - } - - /** - * Get network parameters for signing - */ - private static getNetworkParams(networkType?: NetworkType) { - const network = networkType || NetworkType.MAINNET; - return NETWORK_PARAMS[network]; - } - - /** - * Extract network path from baseURL - * e.g., 'https://open-test.gasfree.io/nile/' -> '/nile/' - * e.g., 'https://open.gasfree.io/tron/' -> '/tron/' - */ - private static extractNetworkPath(baseURL: string): string { - try { - // Remove protocol and domain: 'https://open-test.gasfree.io/nile/' -> '/nile/' - const pathStartIndex = baseURL.indexOf('/', baseURL.indexOf('://') + 3); - if (pathStartIndex === -1) return ''; - - let pathname = baseURL.substring(pathStartIndex); - return pathname; - } catch (error) { - throw new Error('Error extracting network path: ' + error?.message); - } - } - - /** - * Generate authentication headers for API requests - */ - private static generateAuthHeaders(method: string, path: string): Record { - if (!GasFree.credentials) { - throw new Error('GasFree API credentials not set. Call setCredentials() first.'); - } - - const timestamp = Math.floor(Date.now() / 1000); - const message = `${method}${path}${timestamp}`; - const signature = crypto - .createHmac('sha256', GasFree.credentials.apiSecret) - .update(message) - .digest('base64'); - - return { - Timestamp: timestamp.toString(), - Authorization: `ApiKey ${GasFree.credentials.apiKey}:${signature}`, - }; - } - - /** - * Make an authenticated API request - */ - private static async makeAuthenticatedRequest( - method: 'GET' | 'POST', - path: string, - body?: any, - networkType?: NetworkType - ): Promise> { - try { - const baseURL = GasFree.getEndpointURL(networkType); - const url = `${baseURL}${path}`; - const networkPrefix = GasFree.extractNetworkPath(baseURL); - const authHeaders = GasFree.generateAuthHeaders(method, networkPrefix + path); - - let response: AxiosResponse; - - if (method === 'GET') { - response = (await RestClient.get(url, { - ...authHeaders, - })) as AxiosResponse; - } else { - response = (await RestClient.post(url, body, { - ...authHeaders, - })) as AxiosResponse; - } - - return response.data; - } catch (err) { - const errorMessage = idx(err, (_) => _.response.data); - throw new Error(`GasFree API request failed: ${errorMessage || err.message || err}`); - } - } - - /** - * Get all supported tokens - */ - public static async getSupportedTokens(networkType?: NetworkType): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest<{ tokens: GasFreeToken[] }>( - 'GET', - 'api/v1/config/token/all', - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch supported tokens'); - } - - return response.data.tokens; - } catch (err) { - throw new Error(`Failed to fetch supported tokens: ${err.message || err}`); - } - } - - /** - * Get all available service providers - */ - public static async getServiceProviders(networkType?: NetworkType): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest<{ providers: GasFreeProvider[] }>( - 'GET', - 'api/v1/config/provider/all', - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch service providers'); - } - - return response.data.providers; - } catch (err) { - throw new Error(`Failed to fetch service providers: ${err.message || err}`); - } - } - - /** - * Get GasFree account information for a given address - */ - public static async getAccountInfo( - accountAddress: string, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'GET', - `api/v1/address/${accountAddress}`, - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch account information'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to fetch account info: ${err.message || err}`); - } - } - - /** - * Generate signature payload for TIP-712 compatible signing - */ - public static generateSignaturePayload( - transferRequest: Omit, - networkType?: NetworkType - ): { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - } { - const params = GasFree.getNetworkParams(networkType); - - const domain: Permit712MessageDomain = { - name: GasFree.TIP712_DOMAIN_NAME, - version: GasFree.TIP712_DOMAIN_VERSION, - chainId: params.chainId, - verifyingContract: params.verifyingContract, - }; - - const types: Permit712MessageTypes = GasFree.TIP712_MESSAGE_TYPES; - - const message: GasFreeSignaturePayload = { - ...transferRequest, - version: GasFree.SIGNATURE_VERSION, - }; - - return { domain, types, message }; - } - - /** - * Sign GasFree transfer payload using TIP-712 standard - * @param privateKey - Private key in hex format for signing - * @param signaturePayload - Signature payload containing domain, types, and message - * @param networkType - Network type (mainnet/testnet) - * @returns Promise - Signature without 0x prefix - */ - public static async signTransferPayload( - privateKey: string, - signaturePayload: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - }, - networkType: NetworkType - ): Promise { - try { - const tronWeb = createTronWeb(networkType); - tronWeb.setPrivateKey(privateKey); - - // Sign using TronWeb's TIP-712 implementation - const { domain, types, message } = signaturePayload; - const signature = await tronWeb.trx._signTypedData(domain, types, message); - - // Remove 0x prefix if present (as per GasFree documentation) - const cleanSignature = signature.startsWith('0x') ? signature.slice(2) : signature; - return cleanSignature; - } catch (error) { - throw new Error(`Failed to sign transfer payload: ${error.message}`); - } - } - - /** - * Submit a GasFree transfer authorization - */ - public static async submitTransfer( - transferRequest: GasFreeTransferRequest, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'POST', - 'api/v1/gasfree/submit', - transferRequest, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to submit transfer'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to submit transfer: ${err.message || err}`); - } - } - - /** - * Get transfer status by trace ID - */ - public static async getTransferStatus( - traceId: string, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'GET', - `api/v1/gasfree/${traceId}`, - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch transfer status'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to fetch transfer status: ${err.message || err}`); - } - } - - /** - * Calculate deadline timestamp - */ - public static calculateDeadline(durationInSeconds: number = 180): string { - const deadline = Math.floor(Date.now() / 1000) + durationInSeconds; - return deadline.toString(); - } - - /** - * Format token amount to smallest unit (e.g., USDT to 6 decimal places) - */ - public static formatTokenAmount(amount: number, decimals: number): string { - return Math.ceil(amount * Math.pow(10, decimals)).toString(); - } - - /** - * Parse token amount from smallest unit to readable format - */ - public static parseTokenAmount(amount: string, decimals: number): number { - return parseInt(amount) / Math.pow(10, decimals); - } - - /** - * Monitor transfer until completion or failure - */ - public static async monitorTransfer( - traceId: string, - onStatusUpdate?: (status: GasFreeTransferDetails) => void, - networkType?: NetworkType, - maxAttempts: number = 60, - intervalMs: number = 5000 - ): Promise { - let attempts = 0; - - const poll = async (): Promise => { - try { - const status = await GasFree.getTransferStatus(traceId, networkType); - - if (onStatusUpdate) { - onStatusUpdate(status); - } - - // Check if final state - if (status.state === 'SUCCEED' || status.state === 'FAILED') { - return status; - } - - attempts++; - if (attempts >= maxAttempts) { - throw new Error('Transfer monitoring timeout'); - } - - // Wait and poll again - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - return poll(); - } catch (err) { - throw err; - } - }; - - return poll(); - } -} diff --git a/src/services/wallets/operations/dollars/USDT.ts b/src/services/wallets/operations/dollars/USDT.ts index 85b5d4edd..6a6085c8b 100644 --- a/src/services/wallets/operations/dollars/USDT.ts +++ b/src/services/wallets/operations/dollars/USDT.ts @@ -1,28 +1,21 @@ -import GasFree, { - GasFreeProvider, - GasFreeTransferRequest, - GasFreeSignaturePayload, - GasFreeTransferStatus, - Permit712MessageTypes, - Permit712MessageDomain, -} from './GasFree'; +import { GasFreeTransferStatus } from './GasFree'; import { NetworkType } from 'src/services/wallets/enums'; import { isValidTronAddress, getTrc20Balance, getTrc20Transactions } from './Tron'; import { USDTWallet } from '../../factories/USDTWalletFactory'; -// USDT Token addresses +// Keep these addresses for existing wallets' balance and history reads. const USDT_ADDRESSES = { - [NetworkType.MAINNET]: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT TRC-20 on mainnet - [NetworkType.TESTNET]: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf', // USDT TRC-20 on Nile testnet + [NetworkType.MAINNET]: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', + [NetworkType.TESTNET]: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf', }; -// USDT GasFree Fee addresses export const USDT_GASFREE_FEE_ADDRESSES = { - [NetworkType.MAINNET]: 'TLntW9Z59LYY5KEi9cmwk3PKjQga828ird', // GasFree fee address for USDT on mainnet - [NetworkType.TESTNET]: 'TCETRh3aED4kdkaYQY7CcxeTJtrQvwBpNT', // GasFree fee address for USDT on testnet + [NetworkType.MAINNET]: 'TLntW9Z59LYY5KEi9cmwk3PKjQga828ird', + [NetworkType.TESTNET]: 'TCETRh3aED4kdkaYQY7CcxeTJtrQvwBpNT', }; -export const DEFAULT_DEADLINE_SECONDS = 300; // Default deadline for permit transactions (5 minutes) +export const DEFAULT_DEADLINE_SECONDS = 300; +export const USDT_ACTIVITY_PAUSED = 'USDT activity is paused'; export interface USDTTransferOptions { source: USDTWallet; @@ -42,27 +35,25 @@ export interface USDTTransferResult { transaction?: USDTTransaction; } +// Stored account fields are retained for Realm and encrypted backup compatibility. export interface USDTAccountStatus { address: string; gasFreeAddress: string; isActive: boolean; - frozen: number; // Frozen amount in pending transfers + frozen: number; canTransfer: boolean; nextNonce: number; - fees: { - transferFee: number; - activateFee: number; - }; + fees: { transferFee: number; activateFee: number }; } export interface USDTTransaction { - txId?: string; // available post processing - traceId?: string; // available via GasFree API + txId?: string; + traceId?: string; from: string; to: string; amount: string; - transferFee?: number; // Estimated transfer fee - activateFee?: number; // Estimated activation fee + transferFee?: number; + activateFee?: number; fee?: string; status: GasFreeTransferStatus; timestamp: number; @@ -71,392 +62,101 @@ export interface USDTTransaction { } export default class USDT { - /** - * Get USDT token address for the specified network - */ private static getUSDTAddress(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return USDT_ADDRESSES[network]; + return USDT_ADDRESSES[networkType || NetworkType.MAINNET]; } - /** - * Get USDT GasFree fee address for the specified network - */ public static getUSDTGasFreeFeeAddress(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return USDT_GASFREE_FEE_ADDRESSES[network]; + return USDT_GASFREE_FEE_ADDRESSES[networkType || NetworkType.MAINNET]; } - /** - * Check if GasFree supports USDT transfers on the specified network - */ - public static async isGasFreeSupported(networkType?: NetworkType): Promise { - try { - const tokens = await GasFree.getSupportedTokens(networkType); - const usdtAddress = USDT.getUSDTAddress(networkType); - - return tokens.some( - (token) => token.tokenAddress.toLowerCase() === usdtAddress.toLowerCase() && token.supported - ); - } catch (err) { - throw new Error('Failed to check GasFree support for USDT on the specified network'); - } + // Retired provider operations fail closed, including calls from stale routes. + public static async isGasFreeSupported(_networkType?: NetworkType): Promise { + return false; } - /** - * Get available service providers for USDT transfers - */ - public static async getServiceProviders(networkType?: NetworkType): Promise { - try { - return await GasFree.getServiceProviders(networkType); - } catch (err) { - throw new Error('Failed to fetch service providers'); - } + public static async getServiceProviders(_networkType?: NetworkType): Promise { + return []; } - /** - * Get USDT account status and balance information - */ public static async getAccountStatus( - address: string, - networkType?: NetworkType + _address: string, + _networkType?: NetworkType ): Promise { - try { - const accountInfo = await GasFree.getAccountInfo(address, networkType); - const usdtAddress = USDT.getUSDTAddress(networkType); - - // Find USDT asset in account - const usdtAsset = accountInfo.assets.find( - (asset) => asset.tokenAddress.toLowerCase() === usdtAddress.toLowerCase() - ); - - if (!usdtAsset) throw new Error('USDT asset not found in account'); - const frozen = GasFree.parseTokenAmount(usdtAsset.frozen.toString(), usdtAsset.decimal); - - return { - address: accountInfo.accountAddress, - gasFreeAddress: accountInfo.gasFreeAddress, - isActive: accountInfo.active, - frozen, - canTransfer: accountInfo.allowSubmit, - nextNonce: accountInfo.nonce, - fees: { - transferFee: GasFree.parseTokenAmount( - usdtAsset.transferFee.toString(), - usdtAsset.decimal - ), - activateFee: GasFree.parseTokenAmount( - usdtAsset.activateFee.toString(), - usdtAsset.decimal - ), - }, - }; - } catch (err) { - throw err; - } + throw new Error(USDT_ACTIVITY_PAUSED); } - /** - * Prepare USDT transfer parameters and validate - */ - public static async prepareTransfer(options: USDTTransferOptions): Promise<{ + public static async prepareTransfer(_options: USDTTransferOptions): Promise<{ isValid: boolean; error?: string; - signaturePayload?: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - }; - fees?: { - transferFee: number; - activateFee: number; - totalFee: number; - }; + signaturePayload?: unknown; + fees?: { transferFee: number; activateFee: number; totalFee: number }; }> { - try { - const usdtAddress = USDT.getUSDTAddress(options.networkType); - - // Get service providers if not specified - let serviceProviderAddress = options.serviceProviderAddress; - if (!serviceProviderAddress) { - const providers = await GasFree.getServiceProviders(options.networkType); - if (providers.length === 0) { - return { isValid: false, error: 'No service providers available' }; - } - serviceProviderAddress = providers[0].address; - } - - // Calculate fees - const { source } = options; - const fees = USDT.evaluateTransferFee(source.accountStatus); - const maxFee = GasFree.formatTokenAmount(options.maxFeeInUSDT || fees.totalFee, 6); - - // Format amount to smallest unit - const formattedAmount = GasFree.formatTokenAmount(options.amount, 6); - - // Check if account allows submission - if (!source.accountStatus.canTransfer) { - return { - isValid: false, - error: 'Account is not allowed to submit transfers at this time', - }; - } - - // Generate signature payload - const deadline = GasFree.calculateDeadline( - options.deadlineInSeconds || DEFAULT_DEADLINE_SECONDS - ); // Default to 5 minutes - - const transferData = { - token: usdtAddress, - serviceProvider: serviceProviderAddress, - user: options.source.specs.address, - receiver: options.toAddress, - value: formattedAmount, - maxFee, - deadline, - nonce: source.accountStatus.nextNonce, - }; - - const signaturePayload = GasFree.generateSignaturePayload(transferData, options.networkType); - return { - isValid: true, - signaturePayload, - fees: { - transferFee: GasFree.parseTokenAmount(fees.transferFee.toString(), 6), - activateFee: GasFree.parseTokenAmount(fees.activateFee.toString(), 6), - totalFee: GasFree.parseTokenAmount(fees.totalFee.toString(), 6), - }, - }; - } catch (err) { - return { isValid: false, error: err.message || 'Failed to prepare transfer' }; - } + return { isValid: false, error: USDT_ACTIVITY_PAUSED }; } - /** - * Submit USDT transfer with signature - */ public static async submitTransfer( - source: USDTWallet, - signaturePayload: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - } + _source: USDTWallet, + _signaturePayload: unknown ): Promise { - try { - // Create and Sign transfer request - const transferRequest: GasFreeTransferRequest = { - ...signaturePayload.message, - sig: await GasFree.signTransferPayload( - source.specs.privateKey, - signaturePayload, - source.networkType - ), - }; - - // Submit transfer - const response = await GasFree.submitTransfer(transferRequest, source.networkType); - const transferFee = GasFree.parseTokenAmount(response.estimatedTransferFee.toString(), 6); - const activateFee = GasFree.parseTokenAmount(response.estimatedActivateFee.toString(), 6); - const fee = transferFee + activateFee; - const amount = GasFree.parseTokenAmount(response.amount.toString(), 6); - const transaction: USDTTransaction = { - traceId: response.id, - from: transferRequest.user, - to: transferRequest.receiver, - amount: amount.toString(), - transferFee: transferFee, - activateFee: activateFee, - fee: fee.toString(), - status: response.state, - timestamp: Date.now(), - isGasFree: true, - }; - - return { - success: true, - traceId: response.id, - transaction, - }; - } catch (err) { - return { - success: false, - error: err || 'Failed to submit transfer', - }; - } + return { success: false, error: USDT_ACTIVITY_PAUSED }; } - /** - * Track USDT transfer status - */ public static async getTransferStatus( - traceId: string, - networkType?: NetworkType - ): Promise<{ - status: GasFreeTransferStatus; - transactionHash?: string; - amount?: number; - fees?: { - actualTransferFee?: number; - actualActivateFee?: number; - actualTotalFee?: number; - }; - blockInfo?: { - blockNumber?: number; - blockTimestamp?: number; - }; - error?: string; - }> { - try { - const details = await GasFree.getTransferStatus(traceId, networkType); - - return { - status: details.state, - transactionHash: details.txnHash, - amount: details.txnAmount ? GasFree.parseTokenAmount(details.txnAmount, 6) : undefined, - fees: { - actualTransferFee: details.txnTransferFee - ? GasFree.parseTokenAmount(details.txnTransferFee.toString(), 6) - : undefined, - actualActivateFee: details.txnActivateFee - ? GasFree.parseTokenAmount(details.txnActivateFee.toString(), 6) - : undefined, - actualTotalFee: details.txnTotalFee - ? GasFree.parseTokenAmount(details.txnTotalFee.toString(), 6) - : undefined, - }, - blockInfo: { - blockNumber: details.txnBlockNum, - blockTimestamp: details.txnBlockTimestamp, - }, - }; - } catch (err) { - return { - status: GasFreeTransferStatus.FAILED, - error: err.message || 'Failed to fetch transfer status', - }; - } + _traceId: string, + _networkType?: NetworkType + ): Promise { + throw new Error(USDT_ACTIVITY_PAUSED); } - /** - * Monitor USDT transfer until completion - */ public static async monitorTransfer( traceId: string, - onStatusUpdate?: (status: any) => void, - networkType?: NetworkType + _onStatusUpdate?: (status: any) => void, + _networkType?: NetworkType ): Promise { - try { - const pollIn = 15; // Poll every 15 seconds - const maxAttempts = DEFAULT_DEADLINE_SECONDS / 15; // default deadline: 5 mins -- poll every 15 seconds, max attempts is 20 - - const finalStatus = await GasFree.monitorTransfer( - traceId, - (details) => { - if (onStatusUpdate) { - onStatusUpdate({ - status: details.state, - transactionHash: details.txnHash, - amount: details.txnAmount - ? GasFree.parseTokenAmount(details.txnAmount, 6) - : undefined, - }); - } - }, - networkType, - maxAttempts, - pollIn * 1000 // Poll every 15 seconds, in milliseconds - ); - - if (finalStatus.state === GasFreeTransferStatus.SUCCEED) { - return { - success: true, - traceId, - transactionHash: finalStatus.txnHash, - }; - } else { - return { - success: false, - traceId, - error: 'Transfer failed or was rejected', - }; - } - } catch (err) { - return { - success: false, - traceId, - error: err.message || 'Transfer monitoring failed', - }; - } + return { success: false, traceId, error: USDT_ACTIVITY_PAUSED }; } - /** - * Evaluates transfer fees - */ + // Retain old fee information for historical transaction screens. public static evaluateTransferFee(accountStatus: USDTAccountStatus): { transferFee: number; activateFee: number; totalFee: number; } { - try { - const { activateFee, transferFee } = accountStatus.fees; - const activationFee = accountStatus.isActive ? 0 : activateFee; - const totalFee = activationFee + transferFee; - return { - transferFee, - activateFee, - totalFee: totalFee, - }; - } catch (err) { - throw new Error(`Failed to evaluate transfer fees: ${err.message || err}`); - } + const { activateFee, transferFee } = accountStatus.fees; + return { + transferFee, + activateFee, + totalFee: transferFee + (accountStatus.isActive ? 0 : activateFee), + }; } - /** - * Validate address format using TronWeb - */ public static isValidAddress(address: string, networkType: NetworkType): boolean { return isValidTronAddress(address, networkType); } - /** - * Format USDT amount for display - */ public static formatUSDTAmount(amount: number, decimals: number = 2): string { return amount.toFixed(decimals); } - /** - * Parse USDT amount from string input - */ public static parseUSDTAmount(amountString: string): number { const parsed = parseFloat(amountString); - if (isNaN(parsed) || parsed <= 0) { - throw new Error('Invalid USDT amount'); - } + if (isNaN(parsed) || parsed <= 0) throw new Error('Invalid USDT amount'); return parsed; } - /** - * Get USDT balance directly from TRON blockchain - */ public static async getUSDTBalance( address: string, networkType: NetworkType = NetworkType.MAINNET ): Promise { try { - const usdtAddress = USDT.getUSDTAddress(networkType); - const balanceResult = await getTrc20Balance(address, usdtAddress, networkType); - return balanceResult.balance; + const result = await getTrc20Balance(address, USDT.getUSDTAddress(networkType), networkType); + return result.balance; } catch (error) { throw new Error(`Failed to fetch USDT balance: ${error.message || error}`); } } - /** - * Get USDT transactions for a USDT wallet - */ public static async getUSDTTransactions( address: string, networkType: NetworkType, @@ -464,21 +164,11 @@ export default class USDT { fingerprint?: string ): Promise<{ transactions: USDTTransaction[]; - meta: { - fingerprint: string; - hasMore: boolean; - }; + meta: { fingerprint: string; hasMore: boolean }; }> { - const usdtContractAddress = USDT.getUSDTAddress(networkType); - const trc20Transactions = await getTrc20Transactions( - address, - usdtContractAddress, - networkType, - limit, - fingerprint - ); - - const updatedTransactions = trc20Transactions.transactions.map((txn) => ({ + const contract = USDT.getUSDTAddress(networkType); + const result = await getTrc20Transactions(address, contract, networkType, limit, fingerprint); + const transactions = result.transactions.map((txn) => ({ txId: txn.transactionId, from: txn.from, to: txn.to, @@ -486,12 +176,8 @@ export default class USDT { status: txn.blockNumber ? GasFreeTransferStatus.SUCCEED : GasFreeTransferStatus.CONFIRMING, timestamp: txn.blockTimestamp, blockNumber: txn.blockNumber, - isGasFree: txn.to === address ? false : true, // incoming transactions are not GasFree in the similar sense as outgoing + isGasFree: txn.to !== address, })); - - return { - transactions: updatedTransactions, - meta: trc20Transactions.meta, - }; + return { transactions, meta: result.meta }; } } diff --git a/src/utils/service-utilities/config.ts b/src/utils/service-utilities/config.ts index 999bbc3ae..f6191f3b3 100644 --- a/src/utils/service-utilities/config.ts +++ b/src/utils/service-utilities/config.ts @@ -84,15 +84,10 @@ class Configuration { ? config.CHANNEL_URL.trim() : DEFAULT_CONFIG.CHANNEL_URL.trim(); - public GASFREE_API_KEY: string = config.GASFREE_API_KEY?.trim(); - public GASFREE_API_SECRET: string = config.GASFREE_API_SECRET?.trim(); - public RENEWAL_WINDOW: number; public LETS_EXCHANGE_BASE_URL: string = config.LETS_EXCHANGE_BASE_URL?.trim(); - public LETS_EXCHANGE_API_KEY: string = config.LETS_EXCHANGE_API_KEY?.trim(); - public LETS_EXCHANGE_AFFILIATE_ID: string = DEFAULT_CONFIG.LETS_EXCHANGE_AFFILIATE_ID; public ADDRESS: Address; diff --git a/tests/recovery/usdtBackup.test.cjs b/tests/recovery/usdtBackup.test.cjs index aedac0159..f328e81cf 100644 --- a/tests/recovery/usdtBackup.test.cjs +++ b/tests/recovery/usdtBackup.test.cjs @@ -87,7 +87,15 @@ const usdtWallet = (type = 'DEFAULT') => ({ presentationData: { name: 'Before edit', description: 'Before', visibility: 'DEFAULT' }, specs: { address: 'disposable-tron-address', privateKey: 'fixture-only-private-key', balance: 10, transactions: [], hasNewUpdates: false, lastSynched: 1 }, - accountStatus: { isActive: true, nextNonce: 0 }, + accountStatus: { + address: 'disposable-tron-address', + gasFreeAddress: 'saved-fixture-receive-address', + isActive: true, + frozen: 0, + canTransfer: true, + nextNonce: 0, + fees: { transferFee: 1, activateFee: 2 }, + }, createdAt: 1, }); @@ -149,7 +157,7 @@ test('USDT balance, transaction and account sync avoids redundant backup uploads const synced = { ...original, specs: { ...original.specs, balance: 12, transactions: [{ txId: 'fixture-tx' }], hasNewUpdates: true, lastSynched: 2 }, - accountStatus: { isActive: true, nextNonce: 1 }, + accountStatus: { ...original.accountStatus, nextNonce: 1 }, }; assert.equal(await f.update(synced), true); assert.deepEqual(copy(f.collections.USDTWallet), [synced]); diff --git a/tests/services/usdtPause.test.cjs b/tests/services/usdtPause.test.cjs new file mode 100644 index 000000000..a5ddd3b9e --- /dev/null +++ b/tests/services/usdtPause.test.cjs @@ -0,0 +1,136 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const root = path.join(__dirname, '../..'); +function loadTypeScript(relativePath, imports = {}) { + const source = fs.readFileSync(path.join(root, relativePath), 'utf8'); + const code = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText; + const module = { exports: {} }; + const loadImport = (specifier) => { + if (!(specifier in imports)) throw new Error(`Unexpected import: ${specifier}`); + return imports[specifier]; + }; + const run = vm.runInNewContext( + `(function (require, module, exports) { ${code}\n})`, + { Date, Error, Promise } + ); + run(loadImport, module, module.exports); + return module.exports; +} + +const network = { MAINNET: 'MAINNET', TESTNET: 'TESTNET' }; +const historical = loadTypeScript('src/services/wallets/operations/dollars/GasFree.ts'); +const balanceCalls = []; +const historyCalls = []; +const tron = { + isValidTronAddress: () => true, + getTrc20Balance: async (...args) => { + balanceCalls.push(args); + return { balance: 42, decimals: 6 }; + }, + getTrc20Transactions: async (...args) => { + historyCalls.push(args); + return { + transactions: [{ + transactionId: 'chain-1', + from: 'TSender', + to: 'TStoredGasFreeAddress', + formattedValue: 5, + blockNumber: 1, + blockTimestamp: 100, + }], + meta: { fingerprint: '', hasMore: false }, + }; + }, +}; +const service = loadTypeScript('src/services/wallets/operations/dollars/USDT.ts', { + './GasFree': historical, + 'src/services/wallets/enums': { NetworkType: network }, + './Tron': tron, +}).default; + +const wallet = { + networkType: network.MAINNET, + accountStatus: { + address: 'TOwner', + gasFreeAddress: 'TStoredGasFreeAddress', + frozen: 3, + isActive: true, + canTransfer: true, + nextNonce: 2, + fees: { transferFee: 1, activateFee: 0 }, + }, + specs: { + address: 'TOwner', + privateKey: 'fixture-only', + balance: 10, + transactions: [{ + traceId: 'historical-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + status: historical.GasFreeTransferStatus.WAITING, + timestamp: 50, + isGasFree: true, + }], + hasNewUpdates: false, + lastSynched: 1, + }, +}; + +const factory = loadTypeScript('src/services/wallets/factories/USDTWalletFactory.ts', { + 'crypto-js': { SHA256: () => ({ toString: () => 'fixture-id' }) }, + '../enums': { + NetworkType: network, + EntityKind: { USDT_WALLET: 'USDT_WALLET' }, + VisibilityType: { DEFAULT: 'DEFAULT' }, + }, + '../operations/dollars/Tron': {}, + '../operations/dollars/USDT': { __esModule: true, default: service }, + '../operations/BIP85': { __esModule: true, default: {} }, + '../operations/dollars/GasFree': historical, + 'src/utils/service-utilities/config': { + __esModule: true, + default: { isDevMode: () => false }, + }, +}); + +test('retired provider operations fail closed without a provider import', async () => { + assert.equal(await service.isGasFreeSupported(network.MAINNET), false); + assert.equal((await service.getServiceProviders(network.MAINNET)).length, 0); + await assert.rejects(service.getAccountStatus('TOwner'), /USDT activity is paused/); + assert.equal((await service.prepareTransfer({ source: wallet })).isValid, false); + assert.equal((await service.submitTransfer(wallet, {})).success, false); + await assert.rejects(service.getTransferStatus('historical-trace'), /USDT activity is paused/); + assert.equal((await service.monitorTransfer('historical-trace')).success, false); +}); + +test('stored address, chain reads and historical trace survive the pause', async () => { + assert.equal(await factory.updateUSDTWalletAccountStatus(wallet), wallet.accountStatus); + assert.equal(await factory.syncUSDTWalletBalance(wallet), 42); + assert.equal(balanceCalls[0][0], wallet.accountStatus.gasFreeAddress); + assert.equal(factory.getAvailableBalanceUSDTWallet(wallet), 10); + + const transactions = await factory.syncUSDTWalletTransactions(wallet); + assert.equal(historyCalls[0][0], wallet.accountStatus.gasFreeAddress); + assert.equal(transactions.length, 2); + assert.equal(transactions[0].txId, 'chain-1'); + assert.equal(transactions[1].traceId, 'historical-trace'); + assert.equal(transactions[1].status, historical.GasFreeTransferStatus.WAITING); +}); + +test('missing saved address is never replaced by the owner address', async () => { + const missing = { ...wallet, accountStatus: { ...wallet.accountStatus, gasFreeAddress: '' } }; + await assert.rejects(factory.syncUSDTWalletBalance(missing), /Stored USDT address/); + await assert.rejects(factory.syncUSDTWalletTransactions(missing), /Stored USDT address/); +}); From 486594d866a7fe3afdbc006a58f198251bfd6724 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 09:46:50 +0530 Subject: [PATCH 3/6] Guard iOS config codegen against retired credentials --- ios/Podfile | 11 +++++ ios/scripts/verify-retired-env.rb | 17 ++++++++ ios/scripts/verify-retired-env.test.cjs | 58 +++++++++++++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 ios/scripts/verify-retired-env.rb create mode 100644 ios/scripts/verify-retired-env.test.cjs diff --git a/ios/Podfile b/ios/Podfile index b0e96375f..bbda6b409 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -86,6 +86,17 @@ post_install do |installer| # :ccache_enabled => true ) + # react-native-config logs and embeds every key from its selected .env file. + # Run the guard in that pod's own phase before its code generator starts. + config_target = installer.pods_project.targets.find { |target| target.name == 'react-native-config' } + config_codegen = config_target&.shell_script_build_phases&.find { |phase| phase.name == '[CP-User] Config codegen' } + raise 'react-native-config codegen phase not found; release credential guard cannot be installed' unless config_codegen + + config_codegen.shell_script = <<~SCRIPT + config_codegen.shell_script + set -e + ruby "${PODS_ROOT}/../scripts/verify-retired-env.rb" "${PODS_TARGET_SRCROOT}/ios/ReactNativeConfig" "${SRCROOT}/../.." + SCRIPT + # fixes release issue with xCode 16, bitcode is stripped by default. bitcode_strip_path = `xcrun --find bitcode_strip`.chop! def strip_bitcode_from_framework(bitcode_strip_path, framework_relative_path) diff --git a/ios/scripts/verify-retired-env.rb b/ios/scripts/verify-retired-env.rb new file mode 100644 index 000000000..413497ce6 --- /dev/null +++ b/ios/scripts/verify-retired-env.rb @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Use react-native-config's own reader so this checks the same ENVFILE, +# /tmp/envfile override, and .env fallback that its code generator will use. +reader_directory, environment_root = ARGV +abort('Missing react-native-config environment inputs') unless reader_directory && environment_root + +retired_names = %w[GASFREE_API_KEY GASFREE_API_SECRET LETS_EXCHANGE_API_KEY] +retired_names += retired_names.map { |name| "RN_#{name}" } +failure = 'Retired API credentials must not be included in an iOS build' + +abort(failure) if retired_names.any? { |name| ENV.key?(name) } + +require File.join(reader_directory, 'ReadDotEnv') +dotenv, = read_dot_env(environment_root) +abort(failure) if retired_names.any? { |name| dotenv.key?(name) } diff --git a/ios/scripts/verify-retired-env.test.cjs b/ios/scripts/verify-retired-env.test.cjs new file mode 100644 index 000000000..d25f96564 --- /dev/null +++ b/ios/scripts/verify-retired-env.test.cjs @@ -0,0 +1,58 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const verifier = path.join(__dirname, 'verify-retired-env.rb'); +const reader = process.env.KEEPER_TEST_RN_CONFIG_READER || + path.join(__dirname, '..', '..', 'node_modules', 'react-native-config', 'ios', 'ReactNativeConfig'); +const secret = 'synthetic-secret-not-for-output'; +const retiredNames = ['GASFREE_API_KEY', 'GASFREE_API_SECRET', 'LETS_EXCHANGE_API_KEY']; +retiredNames.push(...retiredNames.map(name => `RN_${name}`)); + +function verify(contents, additionalEnv = {}) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ios-env-')); + try { + const envFile = path.join(directory, '.env.test'); + fs.writeFileSync(envFile, contents); + return spawnSync('ruby', [verifier, reader, directory], { + cwd: directory, + env: { PATH: process.env.PATH, ENVFILE: envFile, ...additionalEnv }, + encoding: 'utf8', + }); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +test('iOS pod guard accepts config without retired credentials', () => { + assert.ok(fs.existsSync(reader), 'Install react-native-config before running this test'); + const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n'); + assert.equal(result.status, 0, result.stderr); +}); + +for (const name of retiredNames) { + test(`iOS pod guard rejects ${name} in selected ENVFILE before logging its value`, + () => { + const result = verify(`CHANNEL_URL=https://channel.bitcoinkeeper.app/\n${name}=${secret}\n`); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + }); +} + +test('iOS pod guard rejects exported retired credentials', () => { + const result = verify(`export GASFREE_API_KEY=${secret}\n`); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); +}); + +test('iOS pod guard rejects a retired process variable before logging its value', + () => { + const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n', { + RN_GASFREE_API_SECRET: secret, + }); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + }); From 627ba03a132069daa593ec430c421af2da719e2d Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 09:47:12 +0530 Subject: [PATCH 4/6] Clarify status of historical USDT requests --- src/components/TransactionElement.tsx | 25 +++++++- src/context/Localization/language/en.json | 4 ++ src/context/Localization/language/es.json | 4 ++ src/screens/USDT/UsdtTransactionDetail.tsx | 28 +++++---- src/screens/USDT/components/StatusContent.tsx | 41 ++++++++----- .../wallets/operations/dollars/USDT.ts | 4 ++ tests/services/usdtPause.test.cjs | 59 +++++++++++-------- 7 files changed, 112 insertions(+), 53 deletions(-) diff --git a/src/components/TransactionElement.tsx b/src/components/TransactionElement.tsx index a5adda3fa..411e9b2c4 100644 --- a/src/components/TransactionElement.tsx +++ b/src/components/TransactionElement.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useContext } from 'react'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { StyleSheet, TouchableOpacity } from 'react-native'; import moment from 'moment'; @@ -21,10 +21,14 @@ import Colors from 'src/theme/Colors'; import useLabelsNew from 'src/hooks/useLabelsNew'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; -import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT'; +import { + isHistoricalUnverifiedUSDTRequest, + USDTTransaction, +} from 'src/services/wallets/operations/dollars/USDT'; import { EntityKind } from 'src/services/wallets/enums'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; import ThemedColor from './ThemedColor/ThemedColor'; +import { LocalizationContext } from 'src/context/Localization/LocContext'; function TransactionElement({ transaction, @@ -44,6 +48,9 @@ function TransactionElement({ let amount: number; let confirmations: number; let transactionType: string; + const legacyUSDTRequest = + wallet.entityKind === EntityKind.USDT_WALLET && + isHistoricalUnverifiedUSDTRequest(transaction as USDTTransaction); if (wallet.entityKind === EntityKind.USDT_WALLET) { transactionId = (transaction as USDTTransaction).txId || (transaction as USDTTransaction).traceId; @@ -65,6 +72,7 @@ function TransactionElement({ const { labels } = useLabelsNew({ txid: transactionId }); const { colorMode } = useColorMode(); + const { translations } = useContext(LocalizationContext); const formattedDate = moment(date)?.format('DD MMM YY . HH:mm A'); const viewAll_color = ThemedColor({ name: 'viewAll_color' }); @@ -82,7 +90,7 @@ function TransactionElement({ > - {confirmations === 0 && !isCached && ( + {confirmations === 0 && !isCached && !legacyUSDTRequest && ( @@ -113,6 +121,11 @@ function TransactionElement({ {formattedDate} + {legacyUSDTRequest && ( + + {translations.usdtWalletText.statusUnavailable} + + )} {(transaction as Transaction).tags?.includes('potential-dust-spend') && ( @@ -167,6 +180,12 @@ const styles = StyleSheet.create({ marginHorizontal: 3, lineHeight: 17, }, + legacyStatus: { + fontSize: 10, + width: wp(125), + marginHorizontal: 3, + lineHeight: 13, + }, transactionIdText: { marginHorizontal: 4, fontSize: 14, diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index b93cb5be2..1f0aecf80 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -2158,6 +2158,10 @@ "sendingPausedTitle": "USDT sending is paused", "sendingPausedBody": "Keeper cannot send USDT from this wallet right now. Your wallet details, balance and transaction history remain available.", "receivePausedWarning": "This is your wallet's saved receive address. Keeper cannot send USDT from this wallet while sending is paused. Funds received here cannot be sent through Keeper during the pause. Do not deposit new USDT unless you understand this limitation.", + "statusUnavailable": "Status unavailable", + "legacyRequestTitle": "Earlier USDT request", + "legacyRequestNotice": "Keeper can no longer verify this earlier USDT request. If it completed, it may also appear as a separate on-chain transaction.", + "requestedAmount": "Requested Amount", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index 803c3e55d..1df00a4af 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -2139,6 +2139,10 @@ "sendingPausedTitle": "El envío de USDT está pausado", "sendingPausedBody": "Keeper no puede enviar USDT desde esta cartera ahora mismo. Los detalles, el saldo y el historial de transacciones de la cartera siguen disponibles.", "receivePausedWarning": "Esta es la dirección de recepción guardada de tu cartera. Keeper no puede enviar USDT desde esta cartera mientras el envío esté pausado. Los fondos recibidos aquí no se pueden enviar mediante Keeper durante la pausa. No deposites nuevos USDT a menos que comprendas esta limitación.", + "statusUnavailable": "Estado no disponible", + "legacyRequestTitle": "Solicitud anterior de USDT", + "legacyRequestNotice": "Keeper ya no puede verificar esta solicitud de USDT anterior. Si se completó, también puede aparecer como una transacción separada en la cadena.", + "requestedAmount": "Importe solicitado", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/screens/USDT/UsdtTransactionDetail.tsx b/src/screens/USDT/UsdtTransactionDetail.tsx index 521ac6f09..0b6371756 100644 --- a/src/screens/USDT/UsdtTransactionDetail.tsx +++ b/src/screens/USDT/UsdtTransactionDetail.tsx @@ -18,13 +18,14 @@ import Edit from 'src/assets/images/edit.svg'; import EditDark from 'src/assets/images/edit-white.svg'; import { current } from '@reduxjs/toolkit'; import StatusContent from './components/StatusContent'; -import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT'; +import { + isHistoricalUnverifiedUSDTRequest, + USDTTransaction, +} from 'src/services/wallets/operations/dollars/USDT'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; import Link from 'src/assets/images/link.svg'; import LinkDark from 'src/assets/images/link-white.svg'; import openLink from 'src/utils/OpenLink'; -import useToastMessage from 'src/hooks/useToastMessage'; -import ToastErrorIcon from 'src/assets/images/toast_error.svg'; export function EditNoteContent({ existingNote, noteRef }: { existingNote: string; noteRef }) { const updateNote = useCallback((text) => { @@ -52,6 +53,9 @@ const UsdtTransactionDetail = ({ route }) => { const transactionId = transaction.txId || transaction.traceId; const date = transaction.timestamp; const amount = parseFloat(transaction.amount); + // A trace without a chain transaction ID is a historical provider request. + // Its final result cannot be established after the provider was retired. + const legacyRequest = isHistoricalUnverifiedUSDTRequest(transaction); const status = transaction.status; let transactionType: string; if (transaction.to === wallet.accountStatus.gasFreeAddress) { @@ -66,7 +70,6 @@ const UsdtTransactionDetail = ({ route }) => { const [visible, setVisible] = useState(false); const [updatingLabel, setUpdatingLabel] = useState(false); const close = () => setVisible(false); - const { showToast } = useToastMessage(); function InfoCard({ title, @@ -182,14 +185,10 @@ const UsdtTransactionDetail = ({ route }) => { */} { if (transaction.txId) { redirectToBlockExplorer(transaction.txId); - } else if (transaction.traceId) { - showToast( - 'Transaction is being processed and does not have a Transaction ID yet.', - - ); } }} > @@ -213,8 +212,15 @@ const UsdtTransactionDetail = ({ route }) => { title={usdtWalletText.status} showIcon={false} letterSpacing={2.4} - Content={() => } + Content={() => } /> + {legacyRequest && ( + + )} {transactionType === 'Sent' && ( { title={ transactionType === 'Received' ? usdtWalletText.recievedAmount + : legacyRequest + ? usdtWalletText.requestedAmount : usdtWalletText.sendingAmount } describtion={`${amount} USDT`} diff --git a/src/screens/USDT/components/StatusContent.tsx b/src/screens/USDT/components/StatusContent.tsx index d20220cf6..26201e079 100644 --- a/src/screens/USDT/components/StatusContent.tsx +++ b/src/screens/USDT/components/StatusContent.tsx @@ -1,26 +1,30 @@ import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; -import React from 'react'; +import React, { useContext } from 'react'; import { StyleSheet } from 'react-native'; import Text from 'src/components/KeeperText'; import { hp, wp } from 'src/constants/responsive'; import { GasFreeTransferStatus } from 'src/services/wallets/operations/dollars/GasFree'; import Colors from 'src/theme/Colors'; +import { LocalizationContext } from 'src/context/Localization/LocContext'; -const StatusContent = ({ status }) => { +const StatusContent = ({ status, unavailable = false }) => { const { colorMode } = useColorMode(); - const containerbackgroundColor = - status === GasFreeTransferStatus.SUCCEED - ? Colors.PaleTropicalTeal - : status === GasFreeTransferStatus.CONFIRMING - ? Colors.lightOrange - : Colors.lightindigoblue; + const { translations } = useContext(LocalizationContext); + const containerbackgroundColor = unavailable + ? Colors.lightindigoblue + : status === GasFreeTransferStatus.SUCCEED + ? Colors.PaleTropicalTeal + : status === GasFreeTransferStatus.CONFIRMING + ? Colors.lightOrange + : Colors.lightindigoblue; - const textColor = - status === GasFreeTransferStatus.SUCCEED - ? Colors.TropicalTeal - : status === GasFreeTransferStatus.CONFIRMING - ? Colors.darkOrange - : Colors.indigoblue; + const textColor = unavailable + ? Colors.indigoblue + : status === GasFreeTransferStatus.SUCCEED + ? Colors.TropicalTeal + : status === GasFreeTransferStatus.CONFIRMING + ? Colors.darkOrange + : Colors.indigoblue; return ( { style={styles.container} > - {status === GasFreeTransferStatus.SUCCEED ? 'SUCCESS' : status} + {unavailable + ? translations.usdtWalletText.statusUnavailable + : status === GasFreeTransferStatus.SUCCEED + ? 'SUCCESS' + : status} ); @@ -40,7 +48,8 @@ const styles = StyleSheet.create({ container: { borderWidth: 1, borderRadius: 30, - width: wp(80), + minWidth: wp(80), + paddingHorizontal: wp(8), height: hp(20), justifyContent: 'center', alignItems: 'center', diff --git a/src/services/wallets/operations/dollars/USDT.ts b/src/services/wallets/operations/dollars/USDT.ts index 6a6085c8b..5b490c0a9 100644 --- a/src/services/wallets/operations/dollars/USDT.ts +++ b/src/services/wallets/operations/dollars/USDT.ts @@ -61,6 +61,10 @@ export interface USDTTransaction { isGasFree: boolean; } +export const isHistoricalUnverifiedUSDTRequest = ( + transaction: Pick +): boolean => Boolean(transaction.traceId && !transaction.txId); + export default class USDT { private static getUSDTAddress(networkType?: NetworkType): string { return USDT_ADDRESSES[networkType || NetworkType.MAINNET]; diff --git a/tests/services/usdtPause.test.cjs b/tests/services/usdtPause.test.cjs index a5ddd3b9e..133372ad7 100644 --- a/tests/services/usdtPause.test.cjs +++ b/tests/services/usdtPause.test.cjs @@ -20,10 +20,11 @@ function loadTypeScript(relativePath, imports = {}) { if (!(specifier in imports)) throw new Error(`Unexpected import: ${specifier}`); return imports[specifier]; }; - const run = vm.runInNewContext( - `(function (require, module, exports) { ${code}\n})`, - { Date, Error, Promise } - ); + const run = vm.runInNewContext(`(function (require, module, exports) { ${code}\n})`, { + Date, + Error, + Promise, + }); run(loadImport, module, module.exports); return module.exports; } @@ -41,23 +42,26 @@ const tron = { getTrc20Transactions: async (...args) => { historyCalls.push(args); return { - transactions: [{ - transactionId: 'chain-1', - from: 'TSender', - to: 'TStoredGasFreeAddress', - formattedValue: 5, - blockNumber: 1, - blockTimestamp: 100, - }], + transactions: [ + { + transactionId: 'chain-1', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + formattedValue: 2, + blockNumber: 1, + blockTimestamp: 100, + }, + ], meta: { fingerprint: '', hasMore: false }, }; }, }; -const service = loadTypeScript('src/services/wallets/operations/dollars/USDT.ts', { +const usdtModule = loadTypeScript('src/services/wallets/operations/dollars/USDT.ts', { './GasFree': historical, 'src/services/wallets/enums': { NetworkType: network }, './Tron': tron, -}).default; +}); +const service = usdtModule.default; const wallet = { networkType: network.MAINNET, @@ -74,15 +78,17 @@ const wallet = { address: 'TOwner', privateKey: 'fixture-only', balance: 10, - transactions: [{ - traceId: 'historical-trace', - from: 'TStoredGasFreeAddress', - to: 'TRecipient', - amount: '2', - status: historical.GasFreeTransferStatus.WAITING, - timestamp: 50, - isGasFree: true, - }], + transactions: [ + { + traceId: 'historical-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + status: historical.GasFreeTransferStatus.WAITING, + timestamp: 50, + isGasFree: true, + }, + ], hasNewUpdates: false, lastSynched: 1, }, @@ -115,7 +121,7 @@ test('retired provider operations fail closed without a provider import', async assert.equal((await service.monitorTransfer('historical-trace')).success, false); }); -test('stored address, chain reads and historical trace survive the pause', async () => { +test('stored address, chain reads and ambiguous historical request survive the pause', async () => { assert.equal(await factory.updateUSDTWalletAccountStatus(wallet), wallet.accountStatus); assert.equal(await factory.syncUSDTWalletBalance(wallet), 42); assert.equal(balanceCalls[0][0], wallet.accountStatus.gasFreeAddress); @@ -126,6 +132,11 @@ test('stored address, chain reads and historical trace survive the pause', async assert.equal(transactions.length, 2); assert.equal(transactions[0].txId, 'chain-1'); assert.equal(transactions[1].traceId, 'historical-trace'); + assert.equal(transactions[0].to, transactions[1].to); + assert.equal(transactions[0].amount, transactions[1].amount); + assert.equal(transactions[1].txId, undefined); + assert.equal(usdtModule.isHistoricalUnverifiedUSDTRequest(transactions[0]), false); + assert.equal(usdtModule.isHistoricalUnverifiedUSDTRequest(transactions[1]), true); assert.equal(transactions[1].status, historical.GasFreeTransferStatus.WAITING); }); From e6c518e4a4aaf065d291d2d83d70a1cff5370018 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 09:48:54 +0530 Subject: [PATCH 5/6] Run USDT pause checks in pull request CI --- .github/workflows/test.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dbff68d1a..7db798d56 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,5 +30,10 @@ jobs: - name: Install dependencies run: yarn install + - name: Check USDT pause and retired build inputs + run: | + node --test tests/services/usdtPause.test.cjs tests/recovery/usdtBackup.test.cjs \ + scripts/verify-channel-config.test.cjs ios/scripts/verify-retired-env.test.cjs + - name: Run tests run: npm run test From 0b5370d8cac2354a42c00179c265d87e66c72c68 Mon Sep 17 00:00:00 2001 From: Anant Date: Thu, 8 Oct 2026 13:07:55 +0530 Subject: [PATCH 6/6] ci: remove stale SonarCloud workflow from USDT draft --- .github/workflows/build.yml | 20 -------------------- sonar-project.properties | 8 -------- 2 files changed, 28 deletions(-) delete mode 100644 .github/workflows/build.yml delete mode 100644 sonar-project.properties diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index dd2225e91..000000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Build -on: - push: - branches: - - sprint - pull_request: - types: [opened, synchronize, reopened] -jobs: - sonarcloud: - name: SonarCloud - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: SonarCloud Scan - uses: SonarSource/sonarcloud-github-action@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index f7cea55e6..000000000 --- a/sonar-project.properties +++ /dev/null @@ -1,8 +0,0 @@ -sonar.projectKey=bithyve_bitcoin-keeper -sonar.organization=bithyve - -sonar.coverage.exclusions=**/android/**/*.*,**/ios/**/*.* -sonar.exclusions=**/android/**/*.*,**/ios/**/*.* - -sonar.javascript.file.suffixes=.js,.jsx -sonar.typescript.file.suffixes=.ts,.tsx \ No newline at end of file