-
Notifications
You must be signed in to change notification settings - Fork 9
/
TokenMetadataAnalyzer.ts
353 lines (315 loc) · 14 KB
/
TokenMetadataAnalyzer.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*-
*
* Hedera Mirror Node Explorer
*
* Copyright (C) 2021 - 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {computed, ref, Ref, watch, WatchStopHandle} from "vue";
import {TopicMessagesResponse} from "@/schemas/HederaSchemas";
import {EntityID} from "@/utils/EntityID";
import axios from "axios";
import {Timestamp} from "@/utils/Timestamp";
import {TopicMessageCache} from "@/utils/cache/TopicMessageCache";
import {CID} from "multiformats";
const ipfsGatewayPrefix = import.meta.env.VITE_APP_IPFS_GATEWAY_URL_PREFIX
export interface NftAttribute {
trait_type: string
display_type: string | undefined
value: string | number | boolean
max_value: string | number | undefined
}
export interface NftFile {
uri: string // "uri to file - REQUIRED",
url: string // we compute this
checksum: string | undefined // "cryptographic hash of the representation of the resource the author expects to load - OPTIONAL",
type: string // "mime type - REQUIRED",
is_default_file: boolean | undefined
metadata: string | undefined // "metadata object - OPTIONAL",
metadata_uri: string | undefined // "uri to metadata - OPTIONAL"
}
export class TokenMetadataAnalyzer {
private watchHandle: WatchStopHandle | null = null
private privateAxios = axios.create({timeout: 10000});
private metadataContentRef = ref<any>(null)
//
// Public
//
public readonly rawMetadata: Ref<string>
public constructor(rawMetadata: Ref<string>) {
this.rawMetadata = rawMetadata
}
public mount(): void {
this.watchHandle = watch(
this.rawMetadata,
(value) => this.metadataDidChange(value),
{
immediate: true
}
)
}
public unmount() {
if (this.watchHandle !== null) {
this.watchHandle()
this.watchHandle = null
}
}
public loadSuccess = computed(() => this.loadSuccessRef.value)
public loadError = computed(() => this.loadErrorRef.value)
public readonly metadata = computed(() => {
let result
try {
result = Buffer.from(this.rawMetadata.value ?? '', 'base64').toString()
} catch {
result = this.rawMetadata.value
}
return result
})
public metadataInfo = computed(() => {
let result: string | null
if (!this.loadSuccess.value && !this.loadError.value) {
result = 'The NFT metadata property is not usable.'
} else if (this.loadSuccess.value && !this.isHIP412.value) {
result = 'The metadata content does not follow the schema defined in HIP 412.'
} else {
result = null
}
return result
})
public metadataWarning = computed(() => {
let result: string | null
if (this.loadError.value) {
result = 'The metadata content could not be loaded. '
if (this.metadata.value.startsWith('ipfs://')) {
result += 'This might be transient due to the nature of the IPFS network. ' +
'Try to reload the page in a few moments.'
}
} else {
result = null
}
return result
})
public isHIP412 = computed<boolean>(
() => (this.format.value && this.format.value?.startsWith('HIP412@2'))
|| (this.name.value != null && this.image.value != null && this.type.value != null)
)
public metadataContent = computed<any>(() => this.metadataContentRef.value)
public metadataString = computed<string | null>(
() => this.metadataContent.value !== null
? JSON.stringify(this.metadataContent.value)
: null
)
public metadataKeys = computed(
() => this.metadataContent.value !== null
? Object.keys(this.metadataContent.value)
: []
)
public name = computed<string | null>(() => this.getProperty('name'))
public creator = computed<string | null>(() => this.getProperty('creator'))
public creatorDID = computed<string | null>(() => this.getProperty('creatordid'))
public description = computed<string | null>(() => this.getProperty('description'))
public image = computed<string | null>(() => this.getProperty('image'))
public checksum = computed<string | null>(() => this.getProperty('checksum'))
public type = computed<string | null>(() => this.getProperty('type'))
public format = computed<string | null>(() => this.getProperty('format'))
public properties = computed<string | null>(() => {
let result = this.getProperty('properties')
if (result != null) {
result = JSON.stringify(result)
if (result === '{}') {
result = null
}
}
return result
})
public files = computed<NftFile[]>(() => {
const result: NftFile[] = []
const files = this.getProperty('files')
if (Array.isArray(files)) {
for (const file of files) {
if (file.uri != undefined && file.type != undefined) {
let url
if (file.uri.startsWith("ipfs://") && file.uri.length > 7) {
url = `${ipfsGatewayPrefix}${file.uri.substring(7)}`
} else {
url = file.uri
}
result.push({
uri: file.uri,
url: url,
checksum: file.checksum,
type: file.type,
is_default_file: file.is_default_file,
metadata: file.rawMetadata,
metadata_uri: file.metadata_uri
})
}
}
}
return result
})
public attributes = computed<NftAttribute[]>(() => {
const result: NftAttribute[] = []
const attributes = this.getProperty('attributes')
if (Array.isArray(attributes)) {
for (const attr of attributes) {
if (attr.trait_type != undefined && attr.value != undefined) {
result.push({
trait_type: attr.trait_type,
display_type: attr.display_type,
value: attr.value,
max_value: attr.max_value
})
}
}
}
return result
})
public imageUrl = computed<string | null>(
() => {
let result = this.getProperty('image') ?? this.getProperty(('picture'))
if (result != null && result.startsWith("ipfs://") && result.length > 7) {
result = `${ipfsGatewayPrefix}${result.substring(7)}`
}
return result
})
//
// Private
//
private loadSuccessRef = ref(false)
private loadErrorRef = ref(false)
/*
Content type | Example syntax | See token example
===================+======================================================================+================================================
IPFS URL | "ipfs://QmSoJYWXvds2qcPeRGJdirP7YTCYvZv4fo43TadwmbvV8H" | https://hashscan.io/mainnet/token/0.0.5679552/1
-------------------+----------------------------------------------------------------------+------------------------------------------------
IPFS CID | "QmSoJYWXvds2qcPeRGJdirP7YTCYvZv4fo43TadwmbvV8H" | https://hashscan.io/mainnet/token/0.0.5844106/1
-------------------+----------------------------------------------------------------------+------------------------------------------------
HCS URL | "hcs://6/0.0.5671138" | https://hashscan.io/mainnet/token/0.0.5671193/1
-------------------+----------------------------------------------------------------------+------------------------------------------------
Plain Topic ID | "0.0.5679050" | https://hashscan.io/mainnet/token/0.0.5679054/1
-------------------+----------------------------------------------------------------------+------------------------------------------------
HCS SUBMIT MESSAGE | "1713509435.878762003" | https://hashscan.io/mainnet/token/0.0.5488525/1
tx timestamp | |
-------------------+----------------------------------------------------------------------+------------------------------------------------
Plain HTTPS URL | "https://fliggs-nfts-metadata.s3.us-east-2.amazonaws.com/degen.json" | https://hashscan.io/mainnet/token/0.0.6029502/1
| (Note this one causes a CORS error) |
-------------------+----------------------------------------------------------------------+------------------------------------------------
*/
private async metadataDidChange(value: string | null): Promise<void> {
const content = this.metadataContentRef
let metadata
try {
metadata = Buffer.from(value ?? '', 'base64').toString()
} catch {
metadata = value
}
if (metadata !== null) {
if (metadata.startsWith('ipfs://')) {
content.value = await this.readMetadataFromUrl(`${ipfsGatewayPrefix}${metadata.substring(7)}`)
} else if (metadata.startsWith('hcs://')) {
const i = metadata.lastIndexOf('/');
const id = metadata.substring(i + 1);
if (EntityID.parse(id) !== null) {
content.value = await this.readMetadataFromTopic(id)
} else {
content.value = null
}
} else if (metadata.startsWith('https://')) {
content.value = await this.readMetadataFromUrl(metadata)
} else if (EntityID.parse(metadata) !== null) {
content.value = await this.readMetadataFromTopic(metadata)
} else if (Timestamp.parse(metadata) !== null) {
content.value = await this.readMetadataFromTimestamp(metadata)
} else {
try {
CID.parse(metadata)
content.value = await this.readMetadataFromUrl(`${ipfsGatewayPrefix}${metadata}`)
} catch {
content.value = null
}
}
} else {
content.value = null
}
}
private async readMetadataFromUrl(url: string): Promise<any> {
// console.log(`readMetadataFromUrl: ${url}`)
let result: any
try {
const response = await this.privateAxios.get(url)
this.loadSuccessRef.value = true
result = response.data ?? null
} catch (reason) {
console.warn(`Failed to read metadata from URL ${url} - error: ${reason}`)
if (axios.isAxiosError(reason)) {
console.warn(`status: ${reason.response?.status}`)
}
this.loadErrorRef.value = true
result = null
}
// console.log(`readMetadataFromUrl - result: ${JSON.stringify(result)}`)
return Promise.resolve(result)
}
private async readMetadataFromTopic(id: string): Promise<any> {
// console.log(`readMetadataFromTopic: ${id}`)
let result: any
const url = "api/v1/topics/" + id + "/messages?limit=1&order=desc"
try {
const response = await this.privateAxios.get<TopicMessagesResponse>(url)
this.loadSuccessRef.value = true
if (response.data.messages && response.data.messages.length >= 0) {
result = JSON.parse(Buffer.from(response.data.messages[0].message, 'base64').toString())
} else {
result = null
}
} catch (reason) {
console.warn(`Failed to read metadata from topic ${id} - reason: ${reason}`)
this.loadErrorRef.value = true
result = null
}
// console.log(`readMetadataFromTopic - result: ${JSON.stringify(result)}`)
return Promise.resolve(result)
}
private async readMetadataFromTimestamp(timestamp: string): Promise<any> {
// console.log(`readMetadataFromTimestamp: ${timestamp}`)
let result: any
try {
const topicMessage = await TopicMessageCache.instance.lookup(timestamp)
this.loadSuccessRef.value = true
if (topicMessage) {
result = JSON.parse(Buffer.from(topicMessage.message, 'base64').toString())
} else {
result = null
}
} catch (reason) {
console.warn(`Failed to read metadata from timestamp ${timestamp} - reason: ${reason}`)
this.loadErrorRef.value = true
result = null
}
// console.log(`readMetadataFromTimestamp - result: ${JSON.stringify(result)}`)
return Promise.resolve(result)
}
private getProperty(name: string): any | null {
let result: string | null = null
for (const key of this.metadataKeys.value) {
if (key.toLowerCase() === name) {
result = this.metadataContent.value[key]
break
}
}
return result
}
}