Skip to content

Commit

Permalink
fix: use DI for OCA resolver (#1140)
Browse files Browse the repository at this point in the history
Signed-off-by: Jason C. Leach <[email protected]>
  • Loading branch information
jleach authored May 14, 2024
1 parent e96a7c3 commit cbb8465
Show file tree
Hide file tree
Showing 27 changed files with 94 additions and 80 deletions.
20 changes: 20 additions & 0 deletions packages/legacy/core/App/__mocks__/container-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { BrandingOverlayType, DefaultOCABundleResolver } from '@hyperledger/aries-oca/build/legacy'

const { TOKENS: T } = jest.requireActual('../../App/container-api')

export { T as TOKENS }

const resolver = new DefaultOCABundleResolver(require('../../App/assets/oca-bundles.json'), {
brandingOverlayType: BrandingOverlayType.Branding10,
})

export const useContainer = jest.fn().mockReturnValue({
resolve: jest.fn().mockReturnValue(resolver),
})

// export const useContainer = jest.fn().mockReturnValue({
// resolve: jest.fn().mockReturnValue({
// resolve: jest.fn().mockImplementation(() => Promise.resolve({})),
// resolveAllBundles: jest.fn().mockImplementation(() => Promise.resolve({})),
// }),
// })
9 changes: 5 additions & 4 deletions packages/legacy/core/App/components/misc/CredentialCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Attribute, BrandingOverlayType, Predicate } from '@hyperledger/aries-oc
import React from 'react'
import { ViewStyle } from 'react-native'

import { useConfiguration } from '../../contexts/configuration'
import { TOKENS, useContainer } from '../../container-api'
import { useTheme } from '../../contexts/theme'
import { GenericFn } from '../../types/fn'

Expand Down Expand Up @@ -44,7 +44,7 @@ const CredentialCard: React.FC<CredentialCardProps> = ({
onPress = undefined,
}) => {
// add ability to reference credential by ID, allows us to get past react hook restrictions
const { OCABundleResolver } = useConfiguration()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const { ColorPallet } = useTheme()
const getCredOverlayType = (type: BrandingOverlayType) => {
if (proof) {
Expand All @@ -64,7 +64,7 @@ const CredentialCard: React.FC<CredentialCardProps> = ({
hasAltCredentials={hasAltCredentials}
proof
elevated
></CredentialCard11>
/>
)
}

Expand All @@ -87,7 +87,8 @@ const CredentialCard: React.FC<CredentialCardProps> = ({
)
}
}
return getCredOverlayType(OCABundleResolver.getBrandingOverlayType())

return getCredOverlayType(bundleResolver.getBrandingOverlayType())
}

export default CredentialCard
6 changes: 3 additions & 3 deletions packages/legacy/core/App/components/misc/CredentialCard10.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next'
import { Image, ImageBackground, StyleSheet, Text, View, ViewStyle, useWindowDimensions } from 'react-native'
import { TouchableOpacity } from 'react-native-gesture-handler'

import { useConfiguration } from '../../contexts/configuration'
import { TOKENS, useContainer } from '../../container-api'
import { useTheme } from '../../contexts/theme'
import { GenericFn } from '../../types/fn'
import {
Expand Down Expand Up @@ -72,10 +72,10 @@ const CredentialCard10: React.FC<CredentialCard10Props> = ({ credential, style =
const cardHeaderHeight = cardHeight / 4 // a card has a total of 4 rows, and the header occupy 1 row
const { t, i18n } = useTranslation()
const { ColorPallet, TextTheme } = useTheme()
const { OCABundleResolver } = useConfiguration()
const [overlay, setOverlay] = useState<CredentialOverlay<LegacyBrandingOverlay>>({})
const [isRevoked, setIsRevoked] = useState<boolean>(false)
const credentialConnectionLabel = getCredentialConnectionLabel(credential)
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)

const styles = StyleSheet.create({
container: {
Expand Down Expand Up @@ -144,7 +144,7 @@ const CredentialCard10: React.FC<CredentialCard10Props> = ({ credential, style =
},
language: i18n.language,
}
OCABundleResolver.resolveAllBundles(params).then((bundle) => {
bundleResolver.resolveAllBundles(params).then((bundle) => {
setOverlay({
...overlay,
...bundle,
Expand Down
6 changes: 4 additions & 2 deletions packages/legacy/core/App/components/misc/CredentialCard11.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { FlatList, Image, ImageBackground, StyleSheet, Text, View, ViewStyle, us
import { TouchableOpacity } from 'react-native-gesture-handler'
import Icon from 'react-native-vector-icons/MaterialIcons'

import { TOKENS, useContainer } from '../../container-api'
import { useConfiguration } from '../../contexts/configuration'
import { useTheme } from '../../contexts/theme'
import { GenericFn } from '../../types/fn'
Expand Down Expand Up @@ -94,14 +95,15 @@ const CredentialCard11: React.FC<CredentialCard11Props> = ({
const [dimensions, setDimensions] = useState({ cardWidth: 0, cardHeight: 0 })
const { i18n, t } = useTranslation()
const { ColorPallet, TextTheme, ListItems } = useTheme()
const { OCABundleResolver, getCredentialHelpDictionary } = useConfiguration()
const [isRevoked, setIsRevoked] = useState<boolean>(credential?.revocationNotification !== undefined)
const [flaggedAttributes, setFlaggedAttributes] = useState<string[]>()
const [allPI, setAllPI] = useState<boolean>()
const credentialConnectionLabel = getCredentialConnectionLabel(credential)
const [isProofRevoked, setIsProofRevoked] = useState<boolean>(
credential?.revocationNotification !== undefined && !!proof
)
const { getCredentialHelpDictionary } = useConfiguration()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const [helpAction, setHelpAction] = useState<GenericFn>()
const [overlay, setOverlay] = useState<CredentialOverlay<BrandingOverlay>>({})
// below navigation only to be used from proof request screen
Expand Down Expand Up @@ -282,7 +284,7 @@ const CredentialCard11: React.FC<CredentialCard11Props> = ({
},
language: i18n.language,
}
OCABundleResolver.resolveAllBundles(params).then((bundle) => {
bundleResolver.resolveAllBundles(params).then((bundle) => {
if (proof) {
setFlaggedAttributes((bundle as any).bundle.bundle.flaggedAttributes.map((attr: any) => attr.name))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
} from 'react-native'

import ImageModal from '../../components/modals/ImageModal'
import { useConfiguration } from '../../contexts/configuration'
import { TOKENS, useContainer } from '../../container-api'
import { useTheme } from '../../contexts/theme'
import { toImageSource } from '../../utils/credential'
import { formatIfDate, isDataUrl, pTypeToText } from '../../utils/helpers'
Expand Down Expand Up @@ -56,7 +56,7 @@ const VerifierCredentialCard: React.FC<VerifierCredentialCardProps> = ({
const [dimensions, setDimensions] = useState({ cardWidth: 0, cardHeight: 0 })
const { i18n, t } = useTranslation()
const { ColorPallet, TextTheme } = useTheme()
const { OCABundleResolver } = useConfiguration()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const [overlay, setOverlay] = useState<CredentialOverlay<BrandingOverlay>>({})

const attributeTypes = overlay.bundle?.captureBase.attributes
Expand Down Expand Up @@ -137,7 +137,7 @@ const VerifierCredentialCard: React.FC<VerifierCredentialCardProps> = ({
attributes: displayItems,
language: i18n.language,
}
OCABundleResolver.resolveAllBundles(params).then((bundle) => {
bundleResolver.resolveAllBundles(params).then((bundle) => {
setOverlay({
...overlay,
...bundle,
Expand Down
3 changes: 3 additions & 0 deletions packages/legacy/core/App/container-api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BaseLogger } from '@credo-ts/core'
import { OCABundleResolverType } from '@hyperledger/aries-oca/build/legacy'
import { StackNavigationProp } from '@react-navigation/stack'
import React, { createContext, useContext } from 'react'
import { DependencyContainer } from 'tsyringe'
Expand Down Expand Up @@ -45,6 +46,7 @@ export enum OBJECT_TOKENS {

export enum UTILITY_TOKENS {
UTIL_LOGGER = 'utility.logger',
UTIL_OCA_RESOLVER = 'utility.oca-resolver',
}

export const TOKENS = {
Expand Down Expand Up @@ -78,6 +80,7 @@ export interface TokenMapping {
[TOKENS.COMP_BUTTON]: Button
[TOKENS.OBJECT_ONBOARDINGCONFIG]: ScreenOptionsType
[TOKENS.UTIL_LOGGER]: BaseLogger
[TOKENS.UTIL_OCA_RESOLVER]: OCABundleResolverType
}

export interface Container {
Expand Down
5 changes: 4 additions & 1 deletion packages/legacy/core/App/container-impl.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { DefaultOCABundleResolver } from '@hyperledger/aries-oca/build/legacy'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { StackNavigationProp } from '@react-navigation/stack'
import { createContext, useContext } from 'react'
import { DependencyContainer } from 'tsyringe'

import * as bundle from './assets/oca-bundles.json'
import Button from './components/buttons/Button'
import { LocalStorageKeys } from './constants'
import { TOKENS, Container, TokenMapping } from './container-api'
Expand All @@ -24,6 +26,7 @@ import {
Onboarding as StoreOnboardingState,
Tours as ToursState,
} from './types/state'

export class MainContainer implements Container {
public static readonly TOKENS = TOKENS
private container: DependencyContainer
Expand All @@ -42,7 +45,7 @@ export class MainContainer implements Container {
this.container.registerInstance(TOKENS.GROUP_BY_REFERENT, false)
this.container.registerInstance(TOKENS.OBJECT_ONBOARDINGCONFIG, DefaultScreenOptionsDictionary)
this.container.registerInstance(TOKENS.UTIL_LOGGER, new ConsoleLogger())

this.container.registerInstance(TOKENS.UTIL_OCA_RESOLVER, new DefaultOCABundleResolver(bundle))
this.container.registerInstance(
TOKENS.FN_ONBOARDING_DONE,
(dispatch: React.Dispatch<ReducerAction<unknown>>, navigation: StackNavigationProp<AuthenticateStackParams>) => {
Expand Down
2 changes: 0 additions & 2 deletions packages/legacy/core/App/contexts/configuration.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Agent } from '@credo-ts/core'
import { IndyVdrPoolConfig } from '@credo-ts/indy-vdr'
import { ProofRequestTemplate } from '@hyperledger/aries-bifold-verifier'
import { OCABundleResolverType } from '@hyperledger/aries-oca/build/legacy'
import { StackNavigationOptions, StackScreenProps } from '@react-navigation/stack'
import { ReducerAction, createContext, useContext } from 'react'

Expand Down Expand Up @@ -43,7 +42,6 @@ export interface ConfigurationContext {
credentialListOptions: React.FC
credentialEmptyList: React.FC<EmptyListProps>
developer: React.FC
OCABundleResolver: OCABundleResolverType
proofTemplateBaseUrl?: string
scan: React.FC<StackScreenProps<ConnectStackParams>>
record: React.FC<RecordProps>
Expand Down
6 changes: 0 additions & 6 deletions packages/legacy/core/App/defaultConfiguration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { useProofRequestTemplates } from '@hyperledger/aries-bifold-verifier'
import { IOverlayBundleData } from '@hyperledger/aries-oca'
import { BrandingOverlayType, DefaultOCABundleResolver } from '@hyperledger/aries-oca/build/legacy'

import * as bundle from './assets/oca-bundles.json'
import EmptyList from './components/misc/EmptyList'
import Record from './components/record/Record'
import HomeFooterView from './components/views/HomeFooterView'
Expand Down Expand Up @@ -31,9 +28,6 @@ export const defaultConfiguration: ConfigurationContext = {
credentialListHeaderRight: () => null,
credentialListOptions: () => null,
credentialEmptyList: EmptyList,
OCABundleResolver: new DefaultOCABundleResolver(bundle as unknown as Record<string, IOverlayBundleData>, {
brandingOverlayType: BrandingOverlayType.Branding10,
}),
scan: Scan,
record: Record,
PINSecurity: { rules: PINRules, displayHelper: false },
Expand Down
8 changes: 4 additions & 4 deletions packages/legacy/core/App/screens/CredentialDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import Record from '../components/record/Record'
import RecordRemove from '../components/record/RecordRemove'
import { ToastType } from '../components/toast/BaseToast'
import { EventTypes } from '../constants'
import { useConfiguration } from '../contexts/configuration'
import { TOKENS, useContainer } from '../container-api'
import { useTheme } from '../contexts/theme'
import { BifoldError } from '../types/error'
import { CredentialMetadata, credentialCustomMetadata } from '../types/metadata'
Expand Down Expand Up @@ -49,7 +49,7 @@ const CredentialDetails: React.FC<CredentialDetailsProps> = ({ navigation, route
const { agent } = useAgent()
const { t, i18n } = useTranslation()
const { TextTheme, ColorPallet } = useTheme()
const { OCABundleResolver } = useConfiguration()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const [isRevoked, setIsRevoked] = useState<boolean>(false)
const [revocationDate, setRevocationDate] = useState<string>('')
const [preciseRevocationDate, setPreciseRevocationDate] = useState<string>('')
Expand Down Expand Up @@ -146,7 +146,7 @@ const CredentialDetails: React.FC<CredentialDetailsProps> = ({ navigation, route
language: i18n.language,
}

OCABundleResolver.resolveAllBundles(params).then((bundle) => {
bundleResolver.resolveAllBundles(params).then((bundle) => {
setOverlay({
...overlay,
...(bundle as CredentialOverlay<BrandingOverlay>),
Expand Down Expand Up @@ -307,7 +307,7 @@ const CredentialDetails: React.FC<CredentialDetailsProps> = ({ navigation, route
}

const header = () => {
return OCABundleResolver.getBrandingOverlayType() === BrandingOverlayType.Branding01 ? (
return bundleResolver.getBrandingOverlayType() === BrandingOverlayType.Branding01 ? (
<View>
{isRevoked && !isRevokedMessageHidden ? (
<View style={{ padding: paddingVertical, paddingBottom: 0 }}>
Expand Down
8 changes: 5 additions & 3 deletions packages/legacy/core/App/screens/CredentialOffer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import CredentialCard from '../components/misc/CredentialCard'
import CommonRemoveModal from '../components/modals/CommonRemoveModal'
import Record from '../components/record/Record'
import { EventTypes } from '../constants'
import { TOKENS, useContainer } from '../container-api'
import { useAnimatedComponents } from '../contexts/animated-components'
import { useConfiguration } from '../contexts/configuration'
import { useNetwork } from '../contexts/network'
Expand Down Expand Up @@ -45,13 +46,12 @@ const CredentialOffer: React.FC<CredentialOfferProps> = ({ navigation, route })
}

const { credentialId } = route.params

const { agent } = useAppAgent()
const { t, i18n } = useTranslation()
const { TextTheme, ColorPallet } = useTheme()
const { RecordLoading } = useAnimatedComponents()
const { assertConnectedNetwork } = useNetwork()
const { OCABundleResolver, enableTours: enableToursConfig } = useConfiguration()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const [loading, setLoading] = useState<boolean>(true)
const [buttonsVisible, setButtonsVisible] = useState(true)
const [acceptModalVisible, setAcceptModalVisible] = useState(false)
Expand All @@ -63,6 +63,7 @@ const CredentialOffer: React.FC<CredentialOfferProps> = ({ navigation, route })
const { start } = useTour()
const screenIsFocused = useIsFocused()
const goalCode = useOutOfBandByConnectionId(credential?.connectionId ?? '')?.outOfBandInvitation.goalCode
const { enableTours: enableToursConfig } = useConfiguration()

const styles = StyleSheet.create({
headerTextContainer: {
Expand Down Expand Up @@ -132,7 +133,8 @@ const CredentialOffer: React.FC<CredentialOfferProps> = ({ navigation, route })
const resolvePresentationFields = async () => {
const identifiers = getCredentialIdentifiers(credential)
const attributes = buildFieldsFromAnonCredsCredential(credential)
const fields = await OCABundleResolver.presentationFields({ identifiers, attributes, language: i18n.language })
const fields = await bundleResolver.presentationFields({ identifiers, attributes, language: i18n.language })

return { fields }
}

Expand Down
7 changes: 3 additions & 4 deletions packages/legacy/core/App/screens/ListProofRequests.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { SafeAreaView } from 'react-native-safe-area-context'
import Icon from 'react-native-vector-icons/MaterialIcons'

import EmptyList from '../components/misc/EmptyList'
import { useConfiguration } from '../contexts/configuration'
import { TOKENS, useContainer } from '../container-api'
import { useStore } from '../contexts/store'
import { useTheme } from '../contexts/theme'
import { useTemplates } from '../hooks/proof-request-templates'
Expand All @@ -25,8 +25,7 @@ const ProofRequestsCard: React.FC<ProofRequestsCardProps> = ({ navigation, templ
const { t } = useTranslation()
const { i18n } = useTranslation()
const { ListItems } = useTheme()
const { OCABundleResolver } = useConfiguration()

const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)
const style = StyleSheet.create({
card: {
...ListItems.requestTemplateBackground,
Expand Down Expand Up @@ -64,7 +63,7 @@ const ProofRequestsCard: React.FC<ProofRequestsCardProps> = ({ navigation, templ
const [meta, setMeta] = useState<MetaOverlay | undefined>(undefined)

useEffect(() => {
OCABundleResolver.resolve({ identifiers: { templateId: template.id }, language: i18n.language }).then((bundle) => {
bundleResolver.resolve({ identifiers: { templateId: template.id }, language: i18n.language }).then((bundle) => {
const metaOverlay =
bundle?.metaOverlay ||
new MetaOverlay({
Expand Down
6 changes: 4 additions & 2 deletions packages/legacy/core/App/screens/ProofRequest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import CommonRemoveModal from '../components/modals/CommonRemoveModal'
import ProofCancelModal from '../components/modals/ProofCancelModal'
import InfoTextBox from '../components/texts/InfoTextBox'
import { EventTypes } from '../constants'
import { TOKENS, useContainer } from '../container-api'
import { useAnimatedComponents } from '../contexts/animated-components'
import { useConfiguration } from '../contexts/configuration'
import { useNetwork } from '../contexts/network'
Expand Down Expand Up @@ -68,7 +69,7 @@ const ProofRequest: React.FC<ProofRequestProps> = ({ navigation, route }) => {
const { ColorPallet, ListItems, TextTheme } = useTheme()
const { RecordLoading } = useAnimatedComponents()
const goalCode = useOutOfBandByConnectionId(proof?.connectionId ?? '')?.outOfBandInvitation.goalCode
const { enableTours: enableToursConfig, OCABundleResolver, useAttestation } = useConfiguration()
const { enableTours: enableToursConfig, useAttestation } = useConfiguration()
const [containsPI, setContainsPI] = useState(false)
const [activeCreds, setActiveCreds] = useState<ProofCredentialItems[]>([])
const [selectedCredentials, setSelectedCredentials] = useState<string[]>([])
Expand All @@ -81,6 +82,7 @@ const ProofRequest: React.FC<ProofRequestProps> = ({ navigation, route }) => {
const { loading: attestationLoading } = useAttestation ? useAttestation() : { loading: false }
const { start } = useTour()
const screenIsFocused = useIsFocused()
const bundleResolver = useContainer().resolve(TOKENS.UTIL_OCA_RESOLVER)

const hasMatchingCredDef = useMemo(() => activeCreds.some((cred) => cred.credDefId !== undefined), [activeCreds])

Expand Down Expand Up @@ -297,7 +299,7 @@ const ProofRequest: React.FC<ProofRequestProps> = ({ navigation, route }) => {
return false
}
const labels = (item.attributes ?? []).map((field) => field.label ?? field.name ?? '')
const bundle = await OCABundleResolver.resolveAllBundles({
const bundle = await bundleResolver.resolveAllBundles({
identifiers: { credentialDefinitionId: item.credDefId, schemaId: item.schemaId },
})
const flaggedAttributes: string[] = (bundle as any).bundle.bundle.flaggedAttributes.map((attr: any) => attr.name)
Expand Down
Loading

0 comments on commit cbb8465

Please sign in to comment.