Upload assets and metadata (#4)

* Initial preview & upload logic

* Refactor image & metadata selection & preview logic

* Refactor image & metadata selection & preview logic - 2

* Establish metadata-modal connection

* Metadata attribute manipulation

* Successful metadata attribute removal & update

* Successful metadata attribute addition & update

* Update existing attributes success

* Display image uri among metadata following the upload

* Fix: buttons being displayed without an image overlay

* Separate upload logic & incorporate useRefs

* Clean up: removed unused imports and structures

* Add radio buttons for upload service selection

* Remove package-lock.json (duplicate .lock files)

* Refactor upload logic & metadata modal

* Utilize serviceType enum in upload logic

* Utilize serviceType enum in upload logic - 2

* Implement user input for NFT.Storage & Pinata API keys

* Update use an existing URI text

* Remove upload_old.tsx

* Fix: reset main metadata fields on metadata modal refresh

* Fix: reset main metadata fields on metadata modal refresh - 2

* Make linter happy

* Make linter happy - 2

* Move upload file under collections

* Post-review update - 1

* Source Pinata endpoint URL from environment variables

* Replace regular file arrays with states

Co-authored-by: findolor <anakisci@gmail.com>
This commit is contained in:
Serkan Reis 2022-07-28 16:38:43 +03:00 committed by GitHub
parent 4582f961ba
commit 7740841168
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 1014 additions and 8 deletions

View File

@ -2,6 +2,8 @@ APP_VERSION=0.1.0
NEXT_PUBLIC_SG721_CODE_ID=5
NEXT_PUBLIC_PINATA_ENDPOINT_URL=https://api.pinata.cloud/pinning/pinFileToIPFS
NEXT_PUBLIC_API_URL=https://
NEXT_PUBLIC_BLOCK_EXPLORER_URL=https://testnet-explorer.publicawesome.dev/stargaze
NEXT_PUBLIC_NETWORK=testnet

View File

@ -0,0 +1,131 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import { useMetadataAttributesState } from 'components/forms/MetadataAttributes.hooks'
import { useEffect, useState } from 'react'
import Button from './Button'
import { FormGroup } from './FormGroup'
import { TextInput } from './forms/FormInput'
import { useInputState } from './forms/FormInput.hooks'
import { MetadataAttributes } from './forms/MetadataAttributes'
export interface MetadataModalProps {
metadataFile: File
updateMetadata: (metadataFile: File) => void
updatedMetadataFile: File
refresher: boolean
}
export const MetadataModal = (props: MetadataModalProps) => {
const metadataFile: File = props.metadataFile
const updatedMetadataFile: File = props.updatedMetadataFile
const [metadata, setMetadata] = useState<any>(null)
const [imageURL, setImageURL] = useState<string>('')
let parsedMetadata: any
const parseMetadata = async () => {
if (metadataFile) {
attributesState.reset()
parsedMetadata = JSON.parse(await metadataFile.text())
for (let i = 0; i < parsedMetadata.attributes.length; i++) {
attributesState.add({
trait_type: parsedMetadata.attributes[i].trait_type,
value: parsedMetadata.attributes[i].value,
})
}
nameState.onChange(parsedMetadata.name)
descriptionState.onChange(parsedMetadata.description)
externalUrlState.onChange(parsedMetadata.external_url)
setMetadata(parsedMetadata)
}
if (updatedMetadataFile) {
const parsedUpdatedMetadata = JSON.parse(await updatedMetadataFile.text())
setImageURL(parsedUpdatedMetadata.image)
}
}
const nameState = useInputState({
id: 'name',
name: 'name',
title: 'Name',
placeholder: 'Token name',
defaultValue: metadata?.name,
})
const descriptionState = useInputState({
id: 'description',
name: 'description',
title: 'Description',
placeholder: 'Token description',
defaultValue: metadata?.description,
})
const externalUrlState = useInputState({
id: 'externalUrl',
name: 'externalUrl',
title: 'External URL',
placeholder: 'https://',
defaultValue: metadata?.external_url,
})
const imageState = useInputState({
id: 'image',
name: 'image',
title: 'Image',
placeholder: 'ipfs://',
defaultValue: imageURL,
})
const attributesState = useMetadataAttributesState()
const generateUpdatedMetadata = () => {
console.log(`Current parsed data: ${parsedMetadata}`)
console.log('Updating...')
metadata.attributes = Object.values(attributesState)[1]
metadata.attributes = metadata.attributes.filter((attribute: { trait_type: string }) => attribute.trait_type !== '')
metadata.name = nameState.value
metadata.description = descriptionState.value
metadata.external_url = externalUrlState.value
const metadataFileBlob = new Blob([JSON.stringify(metadata)], {
type: 'application/json',
})
const editedMetadataFile = new File([metadataFileBlob], metadataFile.name, { type: 'application/json' })
props.updateMetadata(editedMetadataFile)
}
useEffect(() => {
void parseMetadata()
}, [props.metadataFile, props.refresher])
return (
<div>
<input className="modal-toggle" id="my-modal-4" type="checkbox" />
<label className="cursor-pointer modal" htmlFor="my-modal-4">
<label className="absolute top-5 bottom-5 w-full max-w-5xl max-h-full modal-box" htmlFor="my-modal-4">
<FormGroup subtitle="" title="Metadata">
<TextInput {...nameState} onChange={(e) => nameState.onChange(e.target.value)} />
<TextInput {...descriptionState} onChange={(e) => descriptionState.onChange(e.target.value)} />
<TextInput {...externalUrlState} onChange={(e) => externalUrlState.onChange(e.target.value)} />
<TextInput {...imageState} disabled value={imageURL} />
<MetadataAttributes
attributes={attributesState.entries}
onAdd={attributesState.add}
onChange={attributesState.update}
onRemove={attributesState.remove}
subtitle="Enter trait types and values"
title="Attributes"
/>
<Button onClick={generateUpdatedMetadata}>Update Metadata</Button>
</FormGroup>
</label>
</label>
</div>
)
}

View File

@ -75,3 +75,31 @@ export const UrlInput = forwardRef<HTMLInputElement, FormInputProps>(
},
//
)
export const TraitTypeInput = forwardRef<HTMLInputElement, FormInputProps>(
function TraitTypeInput(props, ref) {
return (
<FormInput
{...props}
placeholder={props.placeholder || 'Trait Type'}
ref={ref}
type="text"
/>
)
},
//
)
export const TraitValueInput = forwardRef<HTMLInputElement, FormInputProps>(
function TraitValueInput(props, ref) {
return (
<FormInput
{...props}
placeholder={props.placeholder || 'Trait Value'}
ref={ref}
type="text"
/>
)
},
//
)

View File

@ -0,0 +1,33 @@
import { useMemo, useState } from 'react'
import { uid } from 'utils/random'
import type { Attribute } from './MetadataAttributes'
export function useMetadataAttributesState() {
const [record, setRecord] = useState<Record<string, Attribute>>(() => ({}))
const entries = useMemo(() => Object.entries(record), [record])
const values = useMemo(() => Object.values(record), [record])
function add(attribute: Attribute = { trait_type: '', value: '' }) {
setRecord((prev) => ({ ...prev, [uid()]: attribute }))
}
function update(key: string, attribute = record[key]) {
setRecord((prev) => ({ ...prev, [key]: attribute }))
}
function remove(key: string) {
return setRecord((prev) => {
const latest = { ...prev }
delete latest[key]
return latest
})
}
function reset() {
setRecord({})
}
return { entries, values, add, update, remove, reset }
}

View File

@ -0,0 +1,93 @@
import { FormControl } from 'components/FormControl'
import { TraitTypeInput, TraitValueInput } from 'components/forms/FormInput'
import { useEffect, useId, useMemo } from 'react'
import { FaMinus, FaPlus } from 'react-icons/fa'
import { useInputState } from './FormInput.hooks'
export interface Attribute {
trait_type: string
value: string
}
export interface MetadataAttributesProps {
title: string
subtitle?: string
isRequired?: boolean
attributes: [string, Attribute][]
onAdd: () => void
onChange: (key: string, attribute: Attribute) => void
onRemove: (key: string) => void
}
export function MetadataAttributes(props: MetadataAttributesProps) {
const { title, subtitle, isRequired, attributes, onAdd, onChange, onRemove } = props
return (
<FormControl isRequired={isRequired} subtitle={subtitle} title={title}>
{attributes.map(([id], i) => (
<MetadataAttribute
key={`ma-${id}`}
defaultAttribute={attributes[i][1]}
id={id}
isLast={i === attributes.length - 1}
onAdd={onAdd}
onChange={onChange}
onRemove={onRemove}
/>
))}
</FormControl>
)
}
export interface MetadataAttributeProps {
id: string
isLast: boolean
onAdd: MetadataAttributesProps['onAdd']
onChange: MetadataAttributesProps['onChange']
onRemove: MetadataAttributesProps['onRemove']
defaultAttribute: Attribute
}
export function MetadataAttribute({ id, isLast, onAdd, onChange, onRemove, defaultAttribute }: MetadataAttributeProps) {
const Icon = useMemo(() => (isLast ? FaPlus : FaMinus), [isLast])
const htmlId = useId()
const traitTypeState = useInputState({
id: `ma-trait_type-${htmlId}`,
name: `ma-trait_type-${htmlId}`,
title: `Trait Type`,
defaultValue: defaultAttribute.trait_type,
})
const traitValueState = useInputState({
id: `ma-trait_value-${htmlId}`,
name: `ma-trait_value-${htmlId}`,
title: `Trait Value`,
defaultValue: defaultAttribute.value,
})
useEffect(() => {
onChange(id, { trait_type: traitTypeState.value, value: traitValueState.value })
}, [traitTypeState.value, traitValueState.value, id])
return (
<div className="grid relative grid-cols-[1fr_1fr_auto] space-x-2">
<TraitTypeInput {...traitTypeState} />
<TraitValueInput {...traitValueState} />
<div className="flex justify-end items-end pb-2 w-8">
<button
className="flex justify-center items-center p-2 bg-plumbus-80 hover:bg-plumbus-60 rounded-full"
onClick={(e) => {
e.preventDefault()
isLast ? onAdd() : onRemove(id)
}}
type="button"
>
<Icon className="w-3 h-3" />
</button>
</div>
</div>
)
}

View File

@ -19,10 +19,10 @@ export const mainnetConfig: AppConfig = {
}
export const testnetConfig: AppConfig = {
chainId: 'elgafar-1',
chainName: 'elgarfar-1',
chainId: 'stargaze',
chainName: 'elgafar-1',
addressPrefix: 'stars',
rpcUrl: 'https://rpc.elgafar-1.stargaze-apis.com/',
rpcUrl: "https://rpc.elgafar-1.stargaze-apis.com/",
feeToken: 'ustars',
stakingToken: 'ustars',
coinMap: {

View File

@ -2,7 +2,7 @@ import create from 'zustand'
export const useCollectionStore = create(() => ({
name: 'Example',
base_token_uri: 'ipfs://bafkreiei4e437w3hqf5vy4yqroukx22fag7akbajygettvylzqg6shvkfq',
base_token_uri: '',
description: 'Lorem',
image: 'ipfs://bafybeigi3bwpvyvsmnbj46ra4hyffcxdeaj6ntfk5jpic5mx27x6ih2qvq/images/1.png',
external_image: '',

1
env.d.ts vendored
View File

@ -18,6 +18,7 @@ declare namespace NodeJS {
readonly NEXT_PUBLIC_MINTER_CODE_ID: string
readonly NEXT_PUBLIC_WHITELIST_CODE_ID: string
readonly NEXT_PUBLIC_PINATA_ENDPOINT_URL: string
readonly NEXT_PUBLIC_API_URL: string
readonly NEXT_PUBLIC_BLOCK_EXPLORER_URL: string
readonly NEXT_PUBLIC_NETWORK: string

View File

@ -34,6 +34,7 @@
"next": "^12",
"next-seo": "^4",
"nft.storage": "^6.3.0",
"@pinata/sdk": "^1.1.26",
"react": "^18",
"react-datetime-picker": "^3",
"react-dom": "^18",

View File

@ -0,0 +1,511 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable func-names */
import clsx from 'clsx'
import { Alert } from 'components/Alert'
import Anchor from 'components/Anchor'
import Button from 'components/Button'
import { Conditional } from 'components/Conditional'
import { StyledInput } from 'components/forms/StyledInput'
import { MetadataModal } from 'components/MetadataModal'
import { setBaseTokenUri, setImage, useCollectionStore } from 'contexts/collection'
import type { NextPage } from 'next'
import { NextSeo } from 'next-seo'
import type { ChangeEvent } from 'react'
import { useRef, useState } from 'react'
import toast from 'react-hot-toast'
import type { UploadServiceType } from 'services/upload'
import { upload } from 'services/upload'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
import { naturalCompare } from 'utils/sort'
type UploadMethod = 'new' | 'existing'
const UploadPage: NextPage = () => {
const baseTokenURI = useCollectionStore().base_token_uri
const [imageFilesArray, setImageFilesArray] = useState<File[]>([])
const [metadataFilesArray, setMetadataFilesArray] = useState<File[]>([])
const [updatedMetadataFilesArray, setUpdatedMetadataFilesArray] = useState<File[]>([])
const [uploadMethod, setUploadMethod] = useState<UploadMethod>('new')
const [uploadService, setUploadService] = useState<UploadServiceType>('nft-storage')
const [metadataFileArrayIndex, setMetadataFileArrayIndex] = useState(0)
const [refreshMetadata, setRefreshMetadata] = useState(false)
const [nftStorageApiKey, setNftStorageApiKey] = useState(
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDJBODk5OGI4ZkE2YTM1NzMyYmMxQTRDQzNhOUU2M0Y2NUM3ZjA1RWIiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTY1NTE5MTcwNDQ2MiwibmFtZSI6IlRlc3QifQ.IbdV_26bkPHSdd81sxox5AoG-5a4CCEY4aCrdbCXwAE',
)
const [pinataApiKey, setPinataApiKey] = useState('c8c2ea440c09ee8fa639')
const [pinataSecretKey, setPinataSecretKey] = useState(
'9d6f42dc01eaab15f52eac8f36cc4f0ee4184944cb3cdbcda229d06ecf877ee7',
)
const imageFilesRef = useRef<HTMLInputElement>(null)
const metadataFilesRef = useRef<HTMLInputElement>(null)
const handleChangeBaseTokenUri = (event: { target: { value: React.SetStateAction<string> } }) => {
setBaseTokenUri(event.target.value.toString())
}
const handleChangeImage = (event: { target: { value: React.SetStateAction<string> } }) => {
setImage(event.target.value.toString())
}
const selectImages = (event: ChangeEvent<HTMLInputElement>) => {
setImageFilesArray([])
console.log(event.target.files)
let reader: FileReader
if (event.target.files === null) return
for (let i = 0; i < event.target.files.length; i++) {
reader = new FileReader()
reader.onload = function (e) {
if (!e.target?.result) return toast.error('Error parsing file.')
if (!event.target.files) return toast.error('No files selected.')
const imageFile = new File([e.target.result], event.target.files[i].name, { type: 'image/jpg' })
setImageFilesArray((prev) => [...prev, imageFile])
}
if (!event.target.files) return toast.error('No file selected.')
reader.readAsArrayBuffer(event.target.files[i])
reader.onloadend = function (e) {
setImageFilesArray((prev) => prev.sort((a, b) => naturalCompare(a.name, b.name)))
}
}
}
const selectMetadata = (event: ChangeEvent<HTMLInputElement>) => {
setMetadataFilesArray([])
setUpdatedMetadataFilesArray([])
console.log(imageFilesArray)
console.log(event.target.files)
let reader: FileReader
if (event.target.files === null) return toast.error('No files selected.')
for (let i = 0; i < event.target.files.length; i++) {
reader = new FileReader()
reader.onload = function (e) {
if (!e.target?.result) return toast.error('Error parsing file.')
if (!event.target.files) return toast.error('No files selected.')
const metadataFile = new File([e.target.result], event.target.files[i].name, { type: 'image/jpg' })
setMetadataFilesArray((prev) => [...prev, metadataFile])
}
if (!event.target.files) return toast.error('No file selected.')
reader.readAsText(event.target.files[i], 'utf8')
reader.onloadend = function (e) {
setMetadataFilesArray((prev) => prev.sort((a, b) => naturalCompare(a.name, b.name)))
console.log(metadataFilesArray)
}
}
}
const updateMetadata = async () => {
console.log(imageFilesArray)
const imageURI = await upload(
imageFilesArray,
uploadService,
'images',
nftStorageApiKey,
pinataApiKey,
pinataSecretKey,
)
console.log(imageURI)
setUpdatedMetadataFilesArray([])
let reader: FileReader
for (let i = 0; i < metadataFilesArray.length; i++) {
reader = new FileReader()
reader.onload = function (e) {
const metadataJSON = JSON.parse(e.target?.result as string)
metadataJSON.image = `ipfs://${imageURI}/${imageFilesArray[i].name}`
const metadataFileBlob = new Blob([JSON.stringify(metadataJSON)], {
type: 'application/json',
})
const updatedMetadataFile = new File([metadataFileBlob], metadataFilesArray[i].name, {
type: 'application/json',
})
updatedMetadataFilesArray.push(updatedMetadataFile)
console.log(`${updatedMetadataFile.name} => ${metadataJSON.image}`)
if (i === metadataFilesArray.length - 1) {
void uploadUpdatedMetadata()
}
}
reader.readAsText(metadataFilesArray[i], 'utf8')
}
}
const uploadUpdatedMetadata = async () => {
const result = await upload(
updatedMetadataFilesArray,
uploadService,
'metadata',
nftStorageApiKey,
pinataApiKey,
pinataSecretKey,
)
setBaseTokenUri(`ipfs://${result}`)
console.log(`ipfs://${result}`)
}
const updateMetadataFileIndex = (index: number) => {
setMetadataFileArrayIndex(index)
setRefreshMetadata((prev) => !prev)
}
const updateMetadataFileArray = async (updatedMetadataFile: File) => {
metadataFilesArray[metadataFileArrayIndex] = updatedMetadataFile
console.log('Updated Metadata File:')
console.log(JSON.parse(await metadataFilesArray[metadataFileArrayIndex]?.text()))
}
return (
<div>
<NextSeo title="Create Collection" />
<div className="mt-5 space-y-8 text-center">
<h1 className="font-heading text-4xl font-bold">Upload Assets & Metadata</h1>
<p>
Make sure you check our{' '}
<Anchor className="font-bold text-plumbus hover:underline" href={links['Docs']}>
documentation
</Anchor>{' '}
on how to create your collection
</p>
</div>
<hr className="border-white/20" />
<div className="justify-items-start mt-5 mb-3 ml-3 flex-column">
<div className="mt-3 ml-4 form-check form-check-inline">
<input
checked={uploadMethod === 'existing'}
className="float-none mr-2 mb-1 w-4 h-4 align-middle bg-white checked:bg-stargaze bg-center bg-no-repeat bg-contain rounded-full border border-gray-300 checked:border-white focus:outline-none transition duration-200 appearance-none cursor-pointer form-check-input"
id="inlineRadio1"
name="inlineRadioOptions1"
onClick={() => {
setUploadMethod('existing')
}}
type="radio"
value="Existing"
/>
<label className="inline-block text-white cursor-pointer form-check-label" htmlFor="inlineRadio1">
Use an existing URI
</label>
</div>
<div className="mt-3 ml-4 form-check form-check-inline">
<input
checked={uploadMethod === 'new'}
className="float-none mr-2 mb-1 w-4 h-4 align-middle bg-white checked:bg-stargaze bg-center bg-no-repeat bg-contain rounded-full border border-gray-300 checked:border-white focus:outline-none transition duration-200 appearance-none cursor-pointer form-check-input"
id="inlineRadio2"
name="inlineRadioOptions2"
onClick={() => {
setUploadMethod('new')
}}
type="radio"
value="New"
/>
<label className="inline-block text-white cursor-pointer form-check-label" htmlFor="inlineRadio2">
Upload assets & metadata
</label>
</div>
{baseTokenURI && (
<Alert className="mt-5" type="info">
<a href={baseTokenURI} rel="noreferrer" target="_blank">
Base Token URI: {baseTokenURI}
</a>
</Alert>
)}
</div>
<hr className="border-white/20" />
{uploadMethod === 'existing' && (
<div className="ml-3 flex-column">
<p className="my-3 ml-5">
Though Stargaze&apos;s sg721 contract allows for off-chain metadata storage, it is recommended to use a
decentralized storage solution, such as IPFS. <br /> You may head over to{' '}
<Anchor className="font-bold text-plumbus hover:underline" href="https://nft.storage">
NFT Storage
</Anchor>{' '}
or{' '}
<Anchor className="font-bold text-plumbus hover:underline" href="https://www.pinata.cloud/">
Pinata
</Anchor>{' '}
and upload your assets & metadata manually to get a base URI for your collection.
</p>
<div>
<label className="block mr-1 mb-1 ml-5 font-bold text-white dark:text-gray-300" htmlFor="coverImage">
Collection Cover Image
</label>
<input
className="py-2 px-1 mx-5 mt-2 mb-2 w-1/2 bg-white/10 rounded border-2 border-white/20 focus:ring
focus:ring-plumbus-20
form-input, placeholder:text-white/50,"
id="coverImage"
onChange={handleChangeImage}
placeholder="ipfs://bafybeigi3bwpvyvsmnbj46ra4hyffcxdeaj6ntfk5jpic5mx27x6ih2qvq/images/1.png"
/>
</div>
<div>
<label className="block mt-3 mr-1 mb-1 ml-5 font-bold text-white dark:text-gray-300" htmlFor="baseTokenURI">
Base Token URI
</label>
<input
className="py-2 px-1 mx-5 mt-2 mb-2 w-1/2 bg-white/10 rounded border-2 border-white/20 focus:ring
focus:ring-plumbus-20
form-input, placeholder:text-white/50,"
id="baseTokenURI"
onChange={handleChangeBaseTokenUri}
placeholder="ipfs://..."
/>
</div>
</div>
)}
{uploadMethod === 'new' && (
<div>
<div className="justify-items-start mt-5 mb-3 ml-3 flex-column">
<div className="mt-3 ml-4 form-check form-check-inline">
<input
checked={uploadService === 'nft-storage'}
className="float-none mr-2 mb-1 w-4 h-4 align-middle bg-white checked:bg-stargaze bg-center bg-no-repeat bg-contain rounded-full border border-gray-300 checked:border-white focus:outline-none transition duration-200 appearance-none cursor-pointer form-check-input"
id="inlineRadio3"
name="inlineRadioOptions3"
onClick={() => {
setUploadService('nft-storage')
}}
type="radio"
value="nft-storage"
/>
<label className="inline-block text-white cursor-pointer form-check-label" htmlFor="inlineRadio3">
Upload using NFT.Storage
</label>
</div>
<div className="mt-3 ml-4 form-check form-check-inline">
<input
checked={uploadService === 'pinata'}
className="float-none mr-2 mb-1 w-4 h-4 align-middle bg-white checked:bg-stargaze bg-center bg-no-repeat bg-contain rounded-full border border-gray-300 checked:border-white focus:outline-none transition duration-200 appearance-none cursor-pointer form-check-input"
id="inlineRadio4"
name="inlineRadioOptions4"
onClick={() => {
setUploadService('pinata')
}}
type="radio"
value="pinata"
/>
<label className="inline-block text-white cursor-pointer form-check-label" htmlFor="inlineRadio4">
Upload using Pinata
</label>
</div>
</div>
<div className="flex flex-col ml-8 w-1/2">
<Conditional test={uploadService === 'nft-storage'}>
<label htmlFor="nft_storage_api_key">NFT.Storage API Key</label>
<StyledInput
id="nft_storage_api_key"
onChange={(e) => setNftStorageApiKey(e.target.value)}
value={nftStorageApiKey}
/>
</Conditional>
</div>
<div className="flex flex-col ml-8 w-1/2">
<Conditional test={uploadService === 'pinata'}>
<label htmlFor="pinata-api_key">Pinata API Key</label>
<StyledInput
className="flex mb-2 w-1/2"
id="pinata_api_key"
onChange={(e) => setPinataApiKey(e.target.value)}
value={pinataApiKey}
/>
<label htmlFor="pinata_secret_key">Pinata Secret Key</label>
<StyledInput
className="flex"
id="pinata_secret_key"
onChange={(e) => setPinataSecretKey(e.target.value)}
value={pinataSecretKey}
/>
</Conditional>
</div>
<div>
<div className="grid grid-cols-2">
<div className="w-full">
<label
className="block mt-5 mr-1 mb-1 ml-8 w-full font-bold text-white dark:text-gray-300"
htmlFor="imageFiles"
>
Image File Selection
</label>
<div
className={clsx(
'flex relative justify-center items-center mx-8 mt-2 space-y-4 w-full h-32',
'rounded border-2 border-white/20 border-dashed',
)}
>
<input
accept="image/*"
className={clsx(
'file:py-2 file:px-4 file:mr-4 file:bg-plumbus-light file:rounded file:border-0 cursor-pointer',
'before:absolute before:inset-0 before:hover:bg-white/5 before:transition',
)}
id="imageFiles"
multiple
onChange={selectImages}
ref={imageFilesRef}
type="file"
/>
</div>
<label
className="block mt-5 mr-1 mb-1 ml-8 w-full font-bold text-white dark:text-gray-300"
htmlFor="metadataFiles"
>
Metadata Selection
</label>
<div
className={clsx(
'flex relative justify-center items-center mx-8 mt-2 space-y-4 w-full h-32',
'rounded border-2 border-white/20 border-dashed',
)}
>
<input
accept=""
className={clsx(
'file:py-2 file:px-4 file:mr-4 file:bg-plumbus-light file:rounded file:border-0 cursor-pointer',
'before:absolute before:inset-0 before:hover:bg-white/5 before:transition',
)}
id="metadataFiles"
multiple
onChange={selectMetadata}
ref={metadataFilesRef}
type="file"
/>
</div>
<div className="mt-5 ml-8">
<Button className="w-[120px]" isWide onClick={updateMetadata} variant="solid">
Upload
</Button>
</div>
<MetadataModal
metadataFile={metadataFilesArray[metadataFileArrayIndex]}
refresher={refreshMetadata}
updateMetadata={updateMetadataFileArray}
updatedMetadataFile={updatedMetadataFilesArray[metadataFileArrayIndex]}
/>
</div>
<div className="mt-2 mr-10 ml-20 w-4/5 h-96 border-2 border-dashed carousel carousel-vertical rounded-box">
{imageFilesArray.length > 0 &&
imageFilesArray.map((imageSource, index) => (
<div key={`carousel-item-${index}`} className="w-full carousel-item h-1/8">
<div className="grid grid-cols-4 col-auto">
<Conditional test={imageFilesArray.length > 4 * index}>
<button
key={4 * index}
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
onClick={() => {
updateMetadataFileIndex(4 * index)
}}
type="button"
>
<label
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
htmlFor="my-modal-4"
>
<img
key={`image-${4 * index}`}
alt="asset"
className="px-1 my-1 thumbnail"
src={imageFilesArray[4 * index] ? URL.createObjectURL(imageFilesArray[4 * index]) : ''}
/>
</label>
</button>
</Conditional>
<Conditional test={imageFilesArray.length > 4 * index + 1}>
<button
key={4 * index + 1}
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
onClick={() => {
updateMetadataFileIndex(4 * index + 1)
}}
type="button"
>
<label
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
htmlFor="my-modal-4"
>
<img
key={`image-${4 * index + 1}`}
alt="asset"
className="px-1 my-1 thumbnail"
src={
imageFilesArray[4 * index + 1]
? URL.createObjectURL(imageFilesArray[4 * index + 1])
: ''
}
/>
</label>
</button>
</Conditional>
<Conditional test={imageFilesArray.length > 4 * index + 2}>
<button
key={4 * index + 2}
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
onClick={() => {
updateMetadataFileIndex(4 * index + 2)
}}
type="button"
>
<label
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
htmlFor="my-modal-4"
>
<img
key={`image-${4 * index + 2}`}
alt="asset"
className="px-1 my-1 thumbnail"
src={
imageFilesArray[4 * index + 2]
? URL.createObjectURL(imageFilesArray[4 * index + 2])
: ''
}
/>
</label>
</button>
</Conditional>
<Conditional test={imageFilesArray.length > 4 * index + 3}>
<button
key={4 * index + 3}
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
onClick={() => {
updateMetadataFileIndex(4 * index + 3)
}}
type="button"
>
<label
className="relative p-0 w-full h-full bg-transparent hover:bg-transparent border-0 btn modal-button"
htmlFor="my-modal-4"
>
<img
key={`image-${4 * index + 3}`}
alt={' '}
className="px-1 my-1 thumbnail"
src={
imageFilesArray[4 * index + 3]
? URL.createObjectURL(imageFilesArray[4 * index + 3])
: ''
}
/>
</label>
</button>
</Conditional>
</div>
</div>
))}
</div>
</div>
</div>
</div>
)}
</div>
)
}
export default withMetadata(UploadPage, { center: false })

17
services/upload/index.ts Normal file
View File

@ -0,0 +1,17 @@
import { uploadToNftStorage } from './nft-storage'
import type { UploadFileType } from './pinata'
import { uploadToPinata } from './pinata'
export type UploadServiceType = 'nft-storage' | 'pinata'
export const upload = async (
fileArray: File[],
uploadService: UploadServiceType,
fileType: UploadFileType,
nftStorageApiKey: string,
pinataApiKey: string,
pinataSecretKey: string,
): Promise<string> => {
if (uploadService === 'nft-storage') return uploadToNftStorage(fileArray, nftStorageApiKey)
return uploadToPinata(fileArray, pinataApiKey, pinataSecretKey, fileType)
}

View File

@ -0,0 +1,8 @@
import type { CIDString } from 'nft.storage'
import { NFTStorage } from 'nft.storage'
export const uploadToNftStorage = async (fileArray: File[], nftStorageApiKey: string): Promise<CIDString> => {
console.log('Uploading to NFT Storage...')
const client = new NFTStorage({ token: nftStorageApiKey })
return client.storeDirectory(fileArray)
}

29
services/upload/pinata.ts Normal file
View File

@ -0,0 +1,29 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-return */
import axios from 'axios'
import { PINATA_ENDPOINT_URL } from 'utils/constants'
export type UploadFileType = 'images' | 'metadata'
export const uploadToPinata = async (
fileArray: File[],
pinataApiKey: string,
pinataSecretKey: string,
fileType: UploadFileType,
): Promise<string> => {
console.log('Uploading to Pinata...')
const data = new FormData()
fileArray.forEach((file) => {
data.append('file', file, `${fileType}/${file.name}`)
})
const res = await axios.post(PINATA_ENDPOINT_URL, data, {
withCredentials: true,
headers: {
pinata_api_key: pinataApiKey,
pinata_secret_api_key: pinataSecretKey,
},
})
return res.data.IpfsHash
}

View File

@ -2,6 +2,7 @@ export const SG721_CODE_ID = parseInt(process.env.NEXT_PUBLIC_SG721_CODE_ID, 10)
export const MINTER_CODE_ID = parseInt(process.env.NEXT_PUBLIC_MINTER_CODE_ID, 10)
export const WHITELIST_CODE_ID = parseInt(process.env.NEXT_PUBLIC_WHITELIST_CODE_ID, 10)
export const PINATA_ENDPOINT_URL = process.env.NEXT_PUBLIC_PINATA_ENDPOINT_URL
export const NETWORK = process.env.NEXT_PUBLIC_NETWORK
export const BLOCK_EXPLORER_URL = process.env.NEXT_PUBLIC_BLOCK_EXPLORER_URL

159
yarn.lock
View File

@ -2500,6 +2500,17 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
"@pinata/sdk@^1.1.26":
version "1.1.26"
resolved "https://registry.yarnpkg.com/@pinata/sdk/-/sdk-1.1.26.tgz#ff8caa62a36460eeb2266c85df649e2451313ca7"
integrity sha512-surJDg6aBRMnx3TAzBeBH/rNnlsTsykkBe1Fr7VMZgw3Ub4Q0RO2y5mAXtO4AmBqFtqLTbMW/2ItAQ6rVfKGPw==
dependencies:
axios "^0.21.1"
base-path-converter "^1.0.2"
form-data "^2.3.3"
is-ipfs "^0.6.0"
recursive-fs "^1.1.2"
"@popperjs/core@^2":
version "2.11.5"
resolved "https://registry.npmjs.org/@popperjs/core/-/core-2.11.5.tgz"
@ -3296,7 +3307,12 @@ balanced-match@^1.0.0:
resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
base-x@^3.0.2:
base-path-converter@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/base-path-converter/-/base-path-converter-1.0.2.tgz#e80b4b4f31c7b1561e632158e00774b6f2f27978"
integrity sha512-51R8JiuXadknn6ouVUteOhDpmI3G5u5GqjruL7bPJpfxUHVgosaO5uPAvRP4FeR4VyyH4sSvsN78Ci6ouoRYqQ==
base-x@^3.0.2, base-x@^3.0.8:
version "3.0.9"
resolved "https://registry.npmjs.org/base-x/-/base-x-3.0.9.tgz"
integrity sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ==
@ -3453,7 +3469,7 @@ browserslist@^4.17.5, browserslist@^4.20.2:
node-releases "^2.0.3"
picocolors "^1.0.0"
bs58@^4.0.0:
bs58@^4.0.0, bs58@^4.0.1:
version "4.0.1"
resolved "https://registry.npmjs.org/bs58/-/bs58-4.0.1.tgz"
integrity sha1-vhYedsNU9veIrkBx9j806MTwpCo=
@ -3477,6 +3493,14 @@ buffer@6.0.3, buffer@^6.0.1, buffer@^6.0.3:
base64-js "^1.3.1"
ieee754 "^1.2.1"
buffer@^5.5.0, buffer@^5.6.0:
version "5.7.1"
resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0"
integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==
dependencies:
base64-js "^1.3.1"
ieee754 "^1.1.13"
buffer@~5.4.3:
version "5.4.3"
resolved "https://registry.npmjs.org/buffer/-/buffer-5.4.3.tgz"
@ -3594,6 +3618,28 @@ ci-info@^3.3.0:
resolved "https://registry.npmjs.org/ci-info/-/ci-info-3.3.0.tgz"
integrity sha512-riT/3vI5YpVH6/qomlDnJow6TBee2PBKSEpx3O32EGPYbWGIRsIlGRms3Sm74wYE1JMo8RnO04Hb12+v1J5ICw==
cids@~0.7.0:
version "0.7.5"
resolved "https://registry.yarnpkg.com/cids/-/cids-0.7.5.tgz#60a08138a99bfb69b6be4ceb63bfef7a396b28b2"
integrity sha512-zT7mPeghoWAu+ppn8+BS1tQ5qGmbMfB4AregnQjA/qHY3GC1m1ptI9GkWNlgeu38r7CuRdXB47uY2XgAYt6QVA==
dependencies:
buffer "^5.5.0"
class-is "^1.1.0"
multibase "~0.6.0"
multicodec "^1.0.0"
multihashes "~0.4.15"
cids@~0.8.0:
version "0.8.3"
resolved "https://registry.yarnpkg.com/cids/-/cids-0.8.3.tgz#aaf48ac8ed857c3d37dad94d8db1d8c9407b92db"
integrity sha512-yoXTbV3llpm+EBGWKeL9xKtksPE/s6DPoDSY4fn8I8TEW1zehWXPSB0pwAXVDlLaOlrw+sNynj995uD9abmPhA==
dependencies:
buffer "^5.6.0"
class-is "^1.1.0"
multibase "^1.0.0"
multicodec "^1.0.1"
multihashes "^1.0.1"
cipher-base@^1.0.1, cipher-base@^1.0.3:
version "1.0.4"
resolved "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz"
@ -3602,6 +3648,11 @@ cipher-base@^1.0.1, cipher-base@^1.0.3:
inherits "^2.0.1"
safe-buffer "^5.0.1"
class-is@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/class-is/-/class-is-1.1.0.tgz#9d3c0fba0440d211d843cec3dedfa48055005825"
integrity sha512-rhjH9AG1fvabIDoGRVH587413LPjTZgmDF9fOFCbFJQV4yuocX1mHxxvXI4g3cGwbVY9wAYIoKlg1N79frJKQw==
clean-regexp@^1.0.0:
version "1.0.0"
resolved "https://registry.npmjs.org/clean-regexp/-/clean-regexp-1.0.0.tgz"
@ -3698,7 +3749,7 @@ colorette@^2.0.16:
resolved "https://registry.npmjs.org/colorette/-/colorette-2.0.16.tgz"
integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g==
combined-stream@^1.0.8:
combined-stream@^1.0.6, combined-stream@^1.0.8:
version "1.0.8"
resolved "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz"
integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==
@ -4681,6 +4732,15 @@ for-each@^0.3.3:
dependencies:
is-callable "^1.1.3"
form-data@^2.3.3:
version "2.5.1"
resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.5.1.tgz#f2cbec57b5e59e23716e128fe44d4e5dd23895f4"
integrity sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.6"
mime-types "^2.1.12"
form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz"
@ -4983,7 +5043,7 @@ idb-keyval@^6.0.3:
dependencies:
safari-14-idb-fix "^3.0.0"
ieee754@^1.1.4, ieee754@^1.2.1:
ieee754@^1.1.13, ieee754@^1.1.4, ieee754@^1.2.1:
version "1.2.1"
resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz"
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==
@ -5299,6 +5359,18 @@ is-ip@^3.1.0:
dependencies:
ip-regex "^4.0.0"
is-ipfs@^0.6.0:
version "0.6.3"
resolved "https://registry.yarnpkg.com/is-ipfs/-/is-ipfs-0.6.3.tgz#82a5350e0a42d01441c40b369f8791e91404c497"
integrity sha512-HyRot1dvLcxImtDqPxAaY1miO6WsiP/z7Yxpg2qpaLWv5UdhAPtLvHJ4kMLM0w8GSl8AFsVF23PHe1LzuWrUlQ==
dependencies:
bs58 "^4.0.1"
cids "~0.7.0"
mafmt "^7.0.0"
multiaddr "^7.2.1"
multibase "~0.6.0"
multihashes "~0.4.13"
is-negative-zero@^2.0.2:
version "2.0.2"
resolved "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz"
@ -5778,6 +5850,13 @@ lru-queue@^0.1.0:
dependencies:
es5-ext "~0.10.2"
mafmt@^7.0.0:
version "7.1.0"
resolved "https://registry.yarnpkg.com/mafmt/-/mafmt-7.1.0.tgz#4126f6d0eded070ace7dbbb6fb04977412d380b5"
integrity sha512-vpeo9S+hepT3k2h5iFxzEHvvR0GPBx9uKaErmnRzYNcaKb03DgOArjEMlgG4a9LcuZZ89a3I8xbeto487n26eA==
dependencies:
multiaddr "^7.3.0"
make-event-props@^1.1.0:
version "1.3.0"
resolved "https://registry.npmjs.org/make-event-props/-/make-event-props-1.3.0.tgz"
@ -6005,11 +6084,73 @@ multiaddr@^10.0.0:
uint8arrays "^3.0.0"
varint "^6.0.0"
multiaddr@^7.2.1, multiaddr@^7.3.0:
version "7.5.0"
resolved "https://registry.yarnpkg.com/multiaddr/-/multiaddr-7.5.0.tgz#976c88e256e512263445ab03b3b68c003d5f485e"
integrity sha512-GvhHsIGDULh06jyb6ev+VfREH9evJCFIRnh3jUt9iEZ6XDbyoisZRFEI9bMvK/AiR6y66y6P+eoBw9mBYMhMvw==
dependencies:
buffer "^5.5.0"
cids "~0.8.0"
class-is "^1.1.0"
is-ip "^3.1.0"
multibase "^0.7.0"
varint "^5.0.0"
multibase@^0.7.0:
version "0.7.0"
resolved "https://registry.yarnpkg.com/multibase/-/multibase-0.7.0.tgz#1adfc1c50abe05eefeb5091ac0c2728d6b84581b"
integrity sha512-TW8q03O0f6PNFTQDvh3xxH03c8CjGaaYrjkl9UQPG6rz53TQzzxJVCIWVjzcbN/Q5Y53Zd0IBQBMVktVgNx4Fg==
dependencies:
base-x "^3.0.8"
buffer "^5.5.0"
multibase@^1.0.0, multibase@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/multibase/-/multibase-1.0.1.tgz#4adbe1de0be8a1ab0274328b653c3f1903476724"
integrity sha512-KcCxpBVY8fdVKu4dJMAahq4F/2Z/9xqEjIiR7PiMe7LRGeorFn2NLmicN6nLBCqQvft6MG2Lc9X5P0IdyvnxEw==
dependencies:
base-x "^3.0.8"
buffer "^5.5.0"
multibase@~0.6.0:
version "0.6.1"
resolved "https://registry.yarnpkg.com/multibase/-/multibase-0.6.1.tgz#b76df6298536cc17b9f6a6db53ec88f85f8cc12b"
integrity sha512-pFfAwyTjbbQgNc3G7D48JkJxWtoJoBMaR4xQUOuB8RnCgRqaYmWNFeJTTvrJ2w51bjLq2zTby6Rqj9TQ9elSUw==
dependencies:
base-x "^3.0.8"
buffer "^5.5.0"
multicodec@^1.0.0, multicodec@^1.0.1:
version "1.0.4"
resolved "https://registry.yarnpkg.com/multicodec/-/multicodec-1.0.4.tgz#46ac064657c40380c28367c90304d8ed175a714f"
integrity sha512-NDd7FeS3QamVtbgfvu5h7fd1IlbaC4EQ0/pgU4zqE2vdHCmBGsUa0TiM8/TdSeG6BMPC92OOCf8F1ocE/Wkrrg==
dependencies:
buffer "^5.6.0"
varint "^5.0.0"
multiformats@^9.0.4, multiformats@^9.4.13, multiformats@^9.4.2, multiformats@^9.4.5, multiformats@^9.4.7, multiformats@^9.5.4, multiformats@^9.6.3, multiformats@^9.6.4:
version "9.7.0"
resolved "https://registry.npmjs.org/multiformats/-/multiformats-9.7.0.tgz"
integrity sha512-uv/tcgwk0yN4DStopnBN4GTgvaAlYdy6KnZpuzEPFOYQd71DYFJjs0MN1ERElAflrZaYyGBWXyGxL5GgrxIx0Q==
multihashes@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/multihashes/-/multihashes-1.0.1.tgz#a89415d68283cf6287c6e219e304e75ce7fb73fe"
integrity sha512-S27Tepg4i8atNiFaU5ZOm3+gl3KQlUanLs/jWcBxQHFttgq+5x1OgbQmf2d8axJ/48zYGBd/wT9d723USMFduw==
dependencies:
buffer "^5.6.0"
multibase "^1.0.1"
varint "^5.0.0"
multihashes@~0.4.13, multihashes@~0.4.15:
version "0.4.21"
resolved "https://registry.yarnpkg.com/multihashes/-/multihashes-0.4.21.tgz#dc02d525579f334a7909ade8a122dabb58ccfcb5"
integrity sha512-uVSvmeCWf36pU2nB4/1kzYZjsXD9vofZKpgudqkceYY5g2aZZXJ5r9lxuzoRLl1OAp28XljXsEJ/X/85ZsKmKw==
dependencies:
buffer "^5.5.0"
multibase "^0.7.0"
varint "^5.0.0"
murmurhash3js-revisited@^3.0.0:
version "3.0.0"
resolved "https://registry.npmjs.org/murmurhash3js-revisited/-/murmurhash3js-revisited-3.0.0.tgz"
@ -6803,6 +6944,11 @@ receptacle@^1.3.2:
dependencies:
ms "^2.1.1"
recursive-fs@^1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/recursive-fs/-/recursive-fs-1.1.2.tgz#1d752e2f1a65d25fb6964109a9dbf83a335f90f0"
integrity sha512-QPFEt5EwzwlHoqYsZc+NkUSyDTQf1Hvq7c/kpQJHi77OSCAiDXI3wfB0J04ZG+ekGHmv37mdR8MDPEshD3/RlQ==
redent@^3.0.0:
version "3.0.0"
resolved "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz"
@ -7655,6 +7801,11 @@ validate-npm-package-license@^3.0.1:
spdx-correct "^3.0.0"
spdx-expression-parse "^3.0.0"
varint@^5.0.0:
version "5.0.2"
resolved "https://registry.yarnpkg.com/varint/-/varint-5.0.2.tgz#5b47f8a947eb668b848e034dcfa87d0ff8a7f7a4"
integrity sha512-lKxKYG6H03yCZUpAGOPOsMcGxd1RHCu1iKvEHYDPmTyq2HueGhD73ssNBqqQWfvYs04G9iUFRvmAVLW20Jw6ow==
varint@^6.0.0:
version "6.0.0"
resolved "https://registry.npmjs.org/varint/-/varint-6.0.0.tgz"