-
Notifications
You must be signed in to change notification settings - Fork 22
/
useEntity.ts
82 lines (73 loc) · 2.13 KB
/
useEntity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { fromBech32 } from '@cosmjs/encoding'
import { useQueryClient } from '@tanstack/react-query'
import { useMemo } from 'react'
import { useChain } from '@dao-dao/stateless'
import { Entity, EntityType, LoadingData } from '@dao-dao/types'
import {
getConfiguredChains,
getFallbackImage,
makeEmptyUnifiedProfile,
} from '@dao-dao/utils'
import { entityQueries } from '../queries/entity'
import { useQueryLoadingData } from './query/useQueryLoadingData'
export type UseEntityReturn = {
/**
* The chain ID detected for the address based on its prefix.
*/
chainId: string
/**
* The entity for the address on the detected chain.
*/
entity: LoadingData<Entity>
}
/**
* Fetch entity for the given address. Attempts to autodetect the chain based on
* the address prefix, which means it should load entities for wallets and DAOs
* from any chain. It should even correctly load a DAO given a cross-chain
* (polytone) account address.
*/
export const useEntity = (address: string): UseEntityReturn => {
const { chainId: currentChainId, bech32Prefix: currentBech32Prefix } =
useChain()
const chainId = useMemo(() => {
try {
const prefix = fromBech32(address).prefix
if (prefix === currentBech32Prefix) {
return currentChainId
}
// If prefix mismatch, try to find matching chain for prefix and use that
// one instead.
const matchingChainId = getConfiguredChains().find(
({ chain }) => chain.bech32Prefix === prefix
)?.chainId
if (matchingChainId) {
return matchingChainId
}
} catch {}
return currentChainId
}, [address, currentBech32Prefix, currentChainId])
const entity = useQueryLoadingData(
entityQueries.info(
useQueryClient(),
address
? {
chainId,
address,
}
: undefined
),
// Should never error but just in case...
{
type: EntityType.Wallet,
chainId,
address,
name: null,
imageUrl: getFallbackImage(address),
profile: makeEmptyUnifiedProfile(chainId, address),
} as Entity
)
return {
chainId,
entity,
}
}