Skip to content

Commit

Permalink
Fix iOS errors
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeljscript committed Sep 30, 2024
1 parent 4fd931d commit 89a741b
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 67 deletions.
8 changes: 4 additions & 4 deletions apps/wallet-mobile/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ PODS:
- ReactCommon/turbomodule/core
- ExpoSystemUI (2.2.1):
- ExpoModulesCore
- EXTaskManager (11.8.2):
- EXTaskManager (11.7.3):
- ExpoModulesCore
- UMAppLoader
- FBLazyVector (0.71.14)
Expand Down Expand Up @@ -545,7 +545,7 @@ PODS:
- libwebp (~> 1.0)
- SDWebImage/Core (~> 5.15)
- Sentry/HybridSDK (8.36.0)
- UMAppLoader (4.6.0)
- UMAppLoader (4.5.1)
- Yoga (1.14.0)
- ZXingObjC/Core (3.6.9)
- ZXingObjC/OneD (3.6.9):
Expand Down Expand Up @@ -867,7 +867,7 @@ SPEC CHECKSUMS:
ExpoKeepAwake: 69f5f627670d62318410392d03e0b5db0f85759a
ExpoModulesCore: 653958063a301098b541ae4dfed1ac0b98db607b
ExpoSystemUI: 0be5173ee2a7c01e9abc44f56d879a1eaaa16527
EXTaskManager: 9c3520305c3aa1b4a12a7c6d1e3f85f2779c06e9
EXTaskManager: 07d427a5213dd275c13b6b6c07bba35a672e6698
FBLazyVector: 12ea01e587c9594e7b144e1bfc86ac4d9ac28fde
FBReactNativeSpec: faca7d16c37626ca5780a87adef703817722fe61
fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9
Expand Down Expand Up @@ -950,7 +950,7 @@ SPEC CHECKSUMS:
SDWebImageSVGCoder: 15a300a97ec1c8ac958f009c02220ac0402e936c
SDWebImageWebPCoder: 295a6573c512f54ad2dd58098e64e17dcf008499
Sentry: f8374b5415bc38dfb5645941b3ae31230fbeae57
UMAppLoader: f17a5ee8e85b536ace0fc254b447a37ed198d57e
UMAppLoader: 79d3ee6aa2447a1fe2e8b0d07acf2de106e55b58
Yoga: e71803b4c1fff832ccf9b92541e00f9b873119b9
ZXingObjC: 8898711ab495761b2dbbdec76d90164a6d7e14c5

Expand Down
2 changes: 1 addition & 1 deletion apps/wallet-mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@
"expo-image": "1.3.0",
"expo-status-bar": "~1.4.4",
"expo-system-ui": "~2.2.1",
"expo-task-manager": "^11.8.2",
"expo-task-manager": "11.7.3",
"immer": "^10.0.2",
"jsc-android": "241213.1.0",
"lodash": "^4.17.21",
Expand Down
2 changes: 1 addition & 1 deletion apps/wallet-mobile/src/AppNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
useShowDarkThemeAnnouncementScreen,
} from './features/Initialization/DarkThemeAnnouncement/DarkThemeAnnouncement'
import {useDeepLinkWatcher} from './features/Links/common/useDeepLinkWatcher'
import {useNotifications} from './features/Notifications/useCases/common/hooks'
import {NotificationsDevScreen} from './features/Notifications/useCases/NotificationsDevScreen'
import {PortfolioScreen} from './features/Portfolio/useCases/PortfolioScreen'
import {SearchProvider} from './features/Search/SearchContext'
Expand All @@ -40,7 +41,6 @@ import {useStatusBar} from './hooks/useStatusBar'
import {agreementDate} from './kernel/config'
import {AppRoutes, defaultStackNavigationOptions} from './kernel/navigation'
import {WalletNavigator} from './WalletNavigator'
import {useNotifications} from './features/Notifications/useCases/common/hooks'

const Stack = createStackNavigator<AppRoutes>()
const navRef = React.createRef<NavigationContainerRef<ReactNavigation.RootParamList>>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const NotificationsDevScreen = () => {
<Text style={{fontSize: 24}}>Notifications Playground</Text>

<Button
title={`Trigger Transacrion Received Notification`}
title="Trigger Transacrion Received Notification"
shelleyTheme
onPress={handleOnTriggerTransactionReceived}
/>
Expand Down Expand Up @@ -82,7 +82,9 @@ const ReceivedNotification = ({notification}: {notification: NotificationTypes.E
return (
<View>
<Text>{title}</Text>

<Text>{notification.metadata.txId}</Text>

<Text>{readStatus}</Text>
</View>
)
Expand All @@ -91,7 +93,9 @@ const ReceivedNotification = ({notification}: {notification: NotificationTypes.E
return (
<View>
<Text>{notification.trigger}</Text>

<Text>{notification.date}</Text>

<Text>{readStatus}</Text>
</View>
)
Expand Down
114 changes: 69 additions & 45 deletions apps/wallet-mobile/src/features/Notifications/useCases/common/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import * as React from 'react'
import {Notification, Notifications} from '@jamsinclair/react-native-notifications'
import {UseMutationOptions, useQuery, UseQueryOptions} from 'react-query'
import {Notifications as NotificationTypes} from '@yoroi/types'
import {isNonNullable, useAsyncStorage, useMutationWithInvalidations} from '@yoroi/common'
import {useAsyncStorage, useMutationWithInvalidations} from '@yoroi/common'
import {mountAsyncStorage} from '@yoroi/common/src'
import {notificationManagerMaker} from '@yoroi/notifications'
import {merge, Subject, switchMap} from 'rxjs'
import uuid from 'uuid'
import {useWalletManager} from '../../../WalletManager/context/WalletManagerProvider'
import {useEffect} from 'react'
import {YoroiWallet} from '../../../../yoroi-wallets/cardano/types'
import {Notifications as NotificationTypes} from '@yoroi/types'
import * as BackgroundFetch from 'expo-background-fetch'
import * as TaskManager from 'expo-task-manager'
import * as React from 'react'
import {UseMutationOptions, useQuery, UseQueryOptions} from 'react-query'
import {Subject} from 'rxjs'
import uuid from 'uuid'

import {YoroiWallet} from '../../../../yoroi-wallets/cardano/types'
import {useWalletManager} from '../../../WalletManager/context/WalletManagerProvider'
import {walletManager} from '../../../WalletManager/wallet-manager'

export const useRequestPermissions = () => {
React.useEffect(() => {
Expand All @@ -27,12 +29,9 @@ export const useHandleNotification = () => {
},
)

const s2 = Notifications.events().registerNotificationReceivedBackground(
(notification: Notification, completion) => {
console.log(`Notification received in background: ${notification.title} : ${notification.body}`)
// completion({alert: true, sound: true, badge: true})
},
)
const s2 = Notifications.events().registerNotificationReceivedBackground((notification: Notification) => {
console.log(`Notification received in background: ${notification.title} : ${notification.body}`)
})

return () => {
s.remove()
Expand Down Expand Up @@ -161,13 +160,10 @@ export const useNotifications = () => {
useHandleNotification()
const {send} = useSendNotification()
const transactionReceivedSubject = useTransactionReceivedNotificationSubject()
const rewardsUpdatedSubject = useRewardsUpdatedNotificationSubject()
const primaryTokenPriceChangedSubject = usePrimaryTokenPriceChangedNotificationSubject()

const manager = useNotificationsManager({
subscriptions: {
[NotificationTypes.Trigger.TransactionReceived]: transactionReceivedSubject,
[NotificationTypes.Trigger.RewardsUpdated]: rewardsUpdatedSubject,
[NotificationTypes.Trigger.PrimaryTokenPriceChanged]: primaryTokenPriceChangedSubject,
},
})
React.useEffect(() => {
Expand All @@ -184,31 +180,71 @@ export const useNotifications = () => {
}

const BACKGROUND_FETCH_TASK = 'yoroi-notifications-background-fetch'
const appStorage = mountAsyncStorage({path: '/'})
const notificationsAsyncStorage = appStorage.join('notifications-transacrion-received-subject/')
const eventsStorage = appStorage.join('events/')
const configStorage = appStorage.join('settings/')

const notificationManager = notificationManagerMaker({
eventsStorage,
configStorage,
})

TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
const now = Date.now()
if (!TaskManager.isTaskDefined(BACKGROUND_FETCH_TASK)) {
TaskManager.defineTask(BACKGROUND_FETCH_TASK, () => {
const now = Date.now()
console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`)

const ids = [...walletManager.walletMetas.keys()]
ids.forEach((id) => {
const wallet = walletManager.getWalletById(id)
if (!wallet) return
wallet.sync({isForced: true}).then(async () => {
console.log(`Wallet ${id} synced at date: ${new Date(now).toISOString()}`)
const processed = (await notificationsAsyncStorage.getItem<string[]>(id)) || []
const txIds = getTxIds(wallet)

console.log(`Got background fetch call at date: ${new Date(now).toISOString()}`)
if (processed.length === 0) {
console.log(`Wallet ${id} has no processed tx ids`)
await notificationsAsyncStorage.setItem(id, txIds)
return
}
const newTxIds = txIds.filter((txId) => !processed.includes(txId))
if (newTxIds.length === 0) {
console.log(`Wallet ${id} has no new tx ids on network ${wallet.networkManager.network}`)
return
}
console.log('new tx ids', newTxIds)
await notificationsAsyncStorage.setItem(id, [...processed, ...newTxIds])
newTxIds.forEach((id) => {
const metadata: NotificationTypes.TransactionReceivedEvent['metadata'] = {
txId: id,
isSentByUser: false,
nextTxsCounter: 1,
previousTxsCounter: 0,
}
const notification = createTransactionReceivedNotification(metadata)
notificationManager.events.save(notification)
postNotification('Transaction received from background', 'You have received a new transaction')
})
})
})

postNotification('Background fetch', 'Background fetch call received')
// Be sure to return the successful result type!
return BackgroundFetch.BackgroundFetchResult.NewData
})
postNotification('Background fetch', 'Background fetch call received')
// TODO: Be sure to return the correct result type!
return BackgroundFetch.BackgroundFetchResult.NewData
})
}

// 2. Register the task at some point in your app by providing the same name,
// and some configuration options for how the background fetch should behave
// Note: This does NOT need to be in the global scope and CAN be used in your React components!
async function registerBackgroundFetchAsync() {
console.log('registering background fetch')
const s = await BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
return BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: 60 * 10, // 10 minutes
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
})
const isRegistered = BackgroundFetch.getStatusAsync().then((status) => {
console.log('BackgroundFetch status:', status)
})
return s
}

// 3. (Optional) Unregister tasks by specifying the task name
Expand Down Expand Up @@ -279,7 +315,7 @@ const useTransactionReceivedNotificationSubject = () => {
return () => {
s1.unsubscribe()
}
}, [])
}, [walletManager, notificationsAsyncStorage, transactionReceivedSubject])
return transactionReceivedSubject
}

Expand All @@ -293,18 +329,6 @@ const createTransactionReceivedNotification = (metadata: NotificationTypes.Trans
} as const
}

const useRewardsUpdatedNotificationSubject = () => {
const [rewardsUpdatedSubject] = React.useState(new Subject<NotificationTypes.RewardsUpdatedEvent>())
return rewardsUpdatedSubject
}

const usePrimaryTokenPriceChangedNotificationSubject = () => {
const [primaryTokenPriceChangedSubject] = React.useState(
new Subject<NotificationTypes.PrimaryTokenPriceChangedEvent>(),
)
return primaryTokenPriceChangedSubject
}

const getTxIds = (wallet: YoroiWallet) => {
const ids = wallet.allUtxos.map((utxo) => utxo.tx_hash)
return [...new Set(ids)]
Expand Down
2 changes: 1 addition & 1 deletion apps/wallet-mobile/src/yoroi-wallets/cardano/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from '@emurgo/yoroi-lib'
import {App, HW, Network, Portfolio, Wallet} from '@yoroi/types'
import {BigNumber} from 'bignumber.js'
import {Subject} from 'rxjs'

import {WalletEncryptedStorage} from '../../kernel/storage/EncryptedStorage'
import type {
Expand All @@ -31,7 +32,6 @@ import {
} from '../types/staking'
import {YoroiEntry, YoroiSignedTx, YoroiUnsignedTx} from '../types/yoroi'
import type {Addresses} from './account-manager/account-manager'
import {Subject} from 'rxjs'

export type WalletEvent =
| {type: 'initialize'}
Expand Down
5 changes: 4 additions & 1 deletion packages/notifications/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@ The `@yoroi/notifications` package handles local notifications within the Yoroi

**Version 1.0**

Initial version includes local notifications only.
Initial version includes local notifications only.

**Debug**
- To debug notifications in the background, you can force a background sync by following instructions from https://docs.expo.dev/versions/latest/sdk/background-fetch/
14 changes: 1 addition & 13 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11581,14 +11581,7 @@ expo-system-ui@~2.2.1:
"@react-native/normalize-color" "^2.0.0"
debug "^4.3.2"

expo-task-manager@^11.8.2:
version "11.8.2"
resolved "https://registry.yarnpkg.com/expo-task-manager/-/expo-task-manager-11.8.2.tgz#1090a445565ca65ed99991166ddda38575b3dc8c"
integrity sha512-Uhy3ol5gYeZOyeRFddYjLI1B2DGRH1gjp/YC8Hpn5p5MVENviySoKNF+wd98rRvOAokzrzElyDBHSTfX+C3tpg==
dependencies:
unimodules-app-loader "~4.6.0"

expo-task-manager@~11.7.2:
[email protected], expo-task-manager@~11.7.2:
version "11.7.3"
resolved "https://registry.yarnpkg.com/expo-task-manager/-/expo-task-manager-11.7.3.tgz#2d8b0d983e2a73fba4f1f4d65f36ef0db9356ebd"
integrity sha512-ueIOi638o+gRYeCIb9GHVEbdIIvAKqAmm4AllcjDJIrmqB240uA+5a5YwfHm7WUrSthIqHlIzLMFcnMTFxf/9w==
Expand Down Expand Up @@ -22545,11 +22538,6 @@ unimodules-app-loader@~4.5.0:
resolved "https://registry.yarnpkg.com/unimodules-app-loader/-/unimodules-app-loader-4.5.1.tgz#6c8cf83617b6556e99b102fac8a6bbf011abe605"
integrity sha512-yQAsoL0jsCjld1C/iWS4tB5a6LZTb8+enZ9mpt9t9zHYw7YZgeInmW7yz5QZAgVE93ZMPN3SudZHWiXGuD4Wfg==

unimodules-app-loader@~4.6.0:
version "4.6.0"
resolved "https://registry.yarnpkg.com/unimodules-app-loader/-/unimodules-app-loader-4.6.0.tgz#8836040b3acbf605fc4c2c6f6feb6dd9084ea0d4"
integrity sha512-FRNIlx7sLBDVPG117JnEBhnzZkTIgZTEwYW2rzrY9HdvLBTpRN+k0dxY50U/CAhFHW3zMD0OP5JAlnSQRhx5HA==

union-value@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847"
Expand Down

0 comments on commit 89a741b

Please sign in to comment.