-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathuseMetadataData.ts
More file actions
233 lines (195 loc) · 7.26 KB
/
Copy pathuseMetadataData.ts
File metadata and controls
233 lines (195 loc) · 7.26 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import { EventEmitter } from 'events';
import { type NFTInfo } from '@chia-network/api';
import debug from 'debug';
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import type Metadata from '../../../../@types/Metadata';
import type MetadataOnDemand from '../../../../@types/MetadataOnDemand';
import type MetadataState from '../../../../@types/MetadataState';
import useFetchAndProcessMetadata from '../../../../hooks/useFetchAndProcessMetadata';
import useIpfsGateway from '../../../../hooks/useIpfsGateway';
import getNFTId from '../../../../util/getNFTId';
const log = debug('chia-gui:NFTProvider:useMetadataData');
function getChangedEventName(nftId: string) {
return `metadataChanged:${nftId}`;
}
type UseMetadataDataProps = {
fetchNFT: (id: string) => Promise<NFTInfo>; // should be immutable
};
// warning: only used by NFTProvider
export default function useMetadataData(props: UseMetadataDataProps) {
const { fetchNFT } = props;
const [metadatasOnDemand] = useState(() => new Map<string, MetadataOnDemand>());
const fetchAndProcessMetadata = useFetchAndProcessMetadata();
const events = useMemo(() => {
const eventEmitter = new EventEmitter();
eventEmitter.setMaxListeners(Infinity);
return eventEmitter;
}, []);
// immutable function
const setMetadataOnDemand = useCallback(
(nftId: string, metadataOnDemand: MetadataOnDemand) => {
log(`Setting metadata on demand for ${nftId}`);
metadatasOnDemand.set(nftId, metadataOnDemand);
events.emit(getChangedEventName(nftId), {
metadata: metadataOnDemand.metadata,
error: metadataOnDemand.error,
isLoading: !!metadataOnDemand.promise,
});
},
[events /* immutable */, metadatasOnDemand /* immutable */],
);
// immutable function
const fetchMetadata = useCallback(
async (id: string): Promise<Metadata> => {
const nftId = getNFTId(id);
const metadataOnDemand = metadatasOnDemand.get(nftId);
if (metadataOnDemand) {
if (metadataOnDemand.error) {
throw metadataOnDemand.error;
}
if (metadataOnDemand.metadata) {
return metadataOnDemand.metadata;
}
if (metadataOnDemand.promise) {
return metadataOnDemand.promise;
}
}
async function limitedFetchMetadata() {
try {
log(`Fetching metadata for ${id} from API`);
const nft = await fetchNFT(nftId);
const { metadataUris = [], metadataHash } = nft;
const [firstUri] = metadataUris;
if (!firstUri) {
throw new Error('No metadata URI');
}
const metadata = await fetchAndProcessMetadata(firstUri, metadataHash);
setMetadataOnDemand(nftId, { metadata });
return metadata;
} catch (e) {
setMetadataOnDemand(nftId, { error: e as Error });
throw e;
}
}
const promise = limitedFetchMetadata();
setMetadataOnDemand(nftId, { promise });
return promise;
},
[
fetchAndProcessMetadata /* immutable */,
fetchNFT /* immutable */,
metadatasOnDemand /* immutable */,
setMetadataOnDemand /* immutable */,
],
);
// immutable function
const getMetadata = useCallback(
(id: string | undefined): MetadataState => {
if (!id) {
return {
metadata: undefined,
isLoading: false,
error: new Error('Invalid NFT id'),
};
}
const nftId = getNFTId(id);
const metadataOnDemand = metadatasOnDemand.get(nftId);
if (metadataOnDemand) {
return {
metadata: metadataOnDemand.metadata,
isLoading: !!metadataOnDemand.promise,
error: metadataOnDemand.error,
};
}
fetchMetadata(nftId).catch((e) => {
log(`Error fetching Metadata for nftId: ${nftId}`, e);
});
return {
metadata: undefined,
isLoading: true,
error: undefined,
};
},
[fetchMetadata /* immutable */, metadatasOnDemand /* immutable */],
);
// immutable function
const invalidate = useCallback(
async (id: string) => {
const nftId = getNFTId(id);
const metadataOnDemand = metadatasOnDemand.get(nftId);
if (metadataOnDemand) {
// wait for the promise to resolve and ignore error
if (metadataOnDemand.promise) {
await metadataOnDemand.promise.catch(() => {});
}
metadatasOnDemand.delete(nftId);
// reload metadata
getMetadata(id);
}
},
[getMetadata /* immutable */, metadatasOnDemand /* immutable */],
);
const [ipfsGateway] = useIpfsGateway();
const lastIpfsGatewayRef = useRef(ipfsGateway);
useEffect(() => {
if (lastIpfsGatewayRef.current === ipfsGateway) {
return;
}
lastIpfsGatewayRef.current = ipfsGateway;
// Flipping the gateway option changes which URIs the main process will
// fetch, so cached failures are stale — without this, a failed ipfs
// metadata fetch stayed cached here and its NFT kept looking broken
// after enabling the option, until a full app reload. Only failures are
// retried: successfully fetched metadata is hash-verified content and
// unaffected by how it was fetched. A fetch that is still in flight
// started under the old preference and may fail because of it — after
// this effect has run, nothing else would retry that failure — so it is
// retried on rejection; a result that arrives successfully is kept.
//
// Iterate a snapshot: retrying an errored entry re-inserts its key with a
// fresh in-flight promise synchronously, and Map.forEach revisits keys
// re-added during the pass — the live map would attach a rejection retry
// to the very fetch this effect just started, double-fetching a failure.
Array.from(metadatasOnDemand.entries()).forEach(([nftId, metadataOnDemand]) => {
const retry = () =>
invalidate(nftId).catch((e) => {
log(`Error retrying metadata for nftId: ${nftId}`, e);
});
if (metadataOnDemand.error) {
retry();
} else if (metadataOnDemand.promise) {
metadataOnDemand.promise.catch((e) => {
// Retry only the failure this handler saw. The fetch's own catch
// stores its rejection as the entry's error, so anything else here
// means the entry has moved on — a stacked handler from another
// toggle already retried it, or a newer fetch succeeded — and a
// retry would discard that state and fetch again for nothing.
if (metadatasOnDemand.get(nftId)?.error === e) {
retry();
}
});
}
});
}, [ipfsGateway, invalidate /* immutable */, metadatasOnDemand /* immutable */]);
// immutable function
const subscribeToMetadataChanges = useCallback(
(id: string | undefined, callback: (nftState: MetadataState) => void) => {
if (!id) {
return () => {};
}
const nftId = getNFTId(id);
const eventName = getChangedEventName(nftId);
events.on(eventName, callback);
return () => {
events.off(eventName, callback);
};
},
[events /* immutable */],
);
return {
getMetadata,
fetchMetadata,
subscribeToMetadataChanges,
invalidate,
} as const;
}