From aba25199ea96f0a557696e65343a268ffed3a6b9 Mon Sep 17 00:00:00 2001 From: Serkan Reis Date: Mon, 3 Jul 2023 16:05:06 +0300 Subject: [PATCH] Add helper to validate token URI --- utils/isValidTokenUri.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 utils/isValidTokenUri.ts diff --git a/utils/isValidTokenUri.ts b/utils/isValidTokenUri.ts new file mode 100644 index 0000000..0ca2d44 --- /dev/null +++ b/utils/isValidTokenUri.ts @@ -0,0 +1,21 @@ +/* eslint-disable eslint-comments/disable-enable-pair */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +export const checkTokenUri = async (tokenUri: string) => { + const file = await fetch(tokenUri.replace('ipfs://', 'https://ipfs.io/ipfs/')) + .then((res) => + res.json().catch((err: any) => { + throw Error(`Metadata file could not be parsed. Please check that it is valid JSON.`) + }), + ) + .catch((err: any) => { + throw Error(`Unable to fetch metadata from ${tokenUri}`) + }) + + if (!file.image) { + throw Error('Token URI must contain an image URL.') + } + if (file.image && !file.image.startsWith('ipfs://')) { + throw Error('Metadata file: The corresponding value for image must be an IPFS URL.') + } +}