|
| 1 | +import { Address } from 'viem'; |
| 2 | + |
| 3 | +import LabelService, { Label } from '@/services/labels'; |
| 4 | +import useStore from '@/stores/labels.js'; |
| 5 | +import { Chain } from '@/utils/chains'; |
| 6 | + |
| 7 | +interface UseLabels { |
| 8 | + requestLabels: (chain: Chain, addresses: Address[]) => Promise<void>; |
| 9 | + getLabel: (chain: Chain, address: Address) => Label | null; |
| 10 | + getLabelText: (chain: Chain, address: Address) => string | null; |
| 11 | +} |
| 12 | + |
| 13 | +function useLabels(): UseLabels { |
| 14 | + const store = useStore(); |
| 15 | + |
| 16 | + async function requestLabels( |
| 17 | + chain: Chain, |
| 18 | + addresses: Address[], |
| 19 | + ): Promise<void> { |
| 20 | + // Fetch a label for every address only once |
| 21 | + const addressSet = new Set<Address>(); |
| 22 | + for (const address of addresses) { |
| 23 | + const existingLabel = store.getLabel(chain, address); |
| 24 | + if (!existingLabel) { |
| 25 | + addressSet.add(address); |
| 26 | + } |
| 27 | + } |
| 28 | + const uniqueAddresses = Array.from(addressSet); |
| 29 | + if (uniqueAddresses.length === 0) { |
| 30 | + return; |
| 31 | + } |
| 32 | + const labelService = new LabelService(chain); |
| 33 | + const labels = await labelService.getLabels(uniqueAddresses); |
| 34 | + if (Object.keys(labels).length === 0) { |
| 35 | + return; |
| 36 | + } |
| 37 | + store.addLabels(chain, labels); |
| 38 | + } |
| 39 | + |
| 40 | + function getLabel(chain: Chain, address: Address): Label | null { |
| 41 | + return store.getLabel(chain, address); |
| 42 | + } |
| 43 | + |
| 44 | + function getLabelText(chain: Chain, address: Address): string | null { |
| 45 | + const label = getLabel(chain, address); |
| 46 | + return label |
| 47 | + ? label.namespace |
| 48 | + ? `${label.namespace.value} ${label.value}` |
| 49 | + : label.value |
| 50 | + : null; |
| 51 | + } |
| 52 | + |
| 53 | + return { |
| 54 | + requestLabels, |
| 55 | + getLabel, |
| 56 | + getLabelText, |
| 57 | + }; |
| 58 | +} |
| 59 | + |
| 60 | +export default useLabels; |
0 commit comments