From 5b694d698b83b78eacb036bd54d334d3f2ce9e86 Mon Sep 17 00:00:00 2001 From: Salief Date: Wed, 28 Jun 2023 10:37:26 -0400 Subject: [PATCH] include token metadata call --- packages/builder-utils/src/hooks/index.ts | 1 + .../src/hooks/useTokenMetadata.ts | 35 +++++++++++++++++++ packages/builder-utils/src/lib/index.ts | 1 + .../src/lib/parseBase64String.ts | 7 ++++ 4 files changed, 44 insertions(+) create mode 100644 packages/builder-utils/src/hooks/useTokenMetadata.ts create mode 100644 packages/builder-utils/src/lib/parseBase64String.ts diff --git a/packages/builder-utils/src/hooks/index.ts b/packages/builder-utils/src/hooks/index.ts index 0816241..6fb06f3 100644 --- a/packages/builder-utils/src/hooks/index.ts +++ b/packages/builder-utils/src/hooks/index.ts @@ -8,4 +8,5 @@ export * from './useInterval' export * from './useMinBidAmount' export * from './useSettle' export * from './useTokenExplorer' +export * from './useTokenMetadata' export * from './useVote' diff --git a/packages/builder-utils/src/hooks/useTokenMetadata.ts b/packages/builder-utils/src/hooks/useTokenMetadata.ts new file mode 100644 index 0000000..2dc84ae --- /dev/null +++ b/packages/builder-utils/src/hooks/useTokenMetadata.ts @@ -0,0 +1,35 @@ +import parseBase64String from '../lib/parseBase64String' +import { tokenAbi } from '../abi' +import { useTokenContext } from '../context' +import { useEffect, useState } from 'react' +import { useContractRead } from 'wagmi' + +type TokenMetadata = { + description: string + image: string + name: string + properties?: string +} + +export function useTokenMetadata({ tokenId }: { tokenId: number }) { + const [json, setJson] = useState() + + const { tokenAddress } = useTokenContext() + + const { data: tokenUri } = useContractRead({ + address: tokenAddress, + abi: tokenAbi, + functionName: 'tokenURI', + args: [BigInt(tokenId)], + }) + + useEffect(() => { + if (tokenUri) { + setJson(parseBase64String(tokenUri)) + } + }, [tokenId]) + + return { + json: json as TokenMetadata, + } +} diff --git a/packages/builder-utils/src/lib/index.ts b/packages/builder-utils/src/lib/index.ts index afb4d7c..fd569fa 100644 --- a/packages/builder-utils/src/lib/index.ts +++ b/packages/builder-utils/src/lib/index.ts @@ -1,3 +1,4 @@ export * from './etherscanLink' export * from './formatFromUnix' +export * from './parseBase64String' export * from './shortenAddress' diff --git a/packages/builder-utils/src/lib/parseBase64String.ts b/packages/builder-utils/src/lib/parseBase64String.ts new file mode 100644 index 0000000..ea81f2d --- /dev/null +++ b/packages/builder-utils/src/lib/parseBase64String.ts @@ -0,0 +1,7 @@ +const parseBase64String = (val: string) => { + const clean: string = val?.substring(29) + const json = Buffer.from(clean, 'base64').toString() + return JSON.parse(json) +} + +export default parseBase64String