Implement open edition minter contract dashboard

This commit is contained in:
Serkan Reis 2023-06-17 12:00:41 +03:00
parent a9688f0314
commit fa30f47be7
12 changed files with 637 additions and 5 deletions

View File

@ -41,6 +41,24 @@ export const vendingMinterLinkTabs: LinkTabProps[] = [
},
]
export const openEditionMinterLinkTabs: LinkTabProps[] = [
{
title: 'Query',
description: `Dispatch queries for your Open Edition Minter contract`,
href: '/contracts/openEditionMinter/query',
},
{
title: 'Execute',
description: `Execute Open Edition Minter contract actions`,
href: '/contracts/openEditionMinter/execute',
},
{
title: 'Migrate',
description: `Migrate Open Edition Minter contract`,
href: '/contracts/openEditionMinter/migrate',
},
]
export const baseMinterLinkTabs: LinkTabProps[] = [
{
title: 'Instantiate',

View File

@ -0,0 +1,7 @@
import type { ExecuteListItem } from 'contracts/openEditionMinter/messages/execute'
import { useState } from 'react'
export const useExecuteComboboxState = () => {
const [value, setValue] = useState<ExecuteListItem | null>(null)
return { value, onChange: (item: ExecuteListItem) => setValue(item) }
}

View File

@ -0,0 +1,92 @@
import { Combobox, Transition } from '@headlessui/react'
import clsx from 'clsx'
import { FormControl } from 'components/FormControl'
import type { ExecuteListItem } from 'contracts/openEditionMinter/messages/execute'
import { EXECUTE_LIST } from 'contracts/openEditionMinter/messages/execute'
import { matchSorter } from 'match-sorter'
import { Fragment, useState } from 'react'
import { FaChevronDown, FaInfoCircle } from 'react-icons/fa'
export interface ExecuteComboboxProps {
value: ExecuteListItem | null
onChange: (item: ExecuteListItem) => void
}
export const ExecuteCombobox = ({ value, onChange }: ExecuteComboboxProps) => {
const [search, setSearch] = useState('')
const filtered =
search === '' ? EXECUTE_LIST : matchSorter(EXECUTE_LIST, search, { keys: ['id', 'name', 'description'] })
return (
<Combobox
as={FormControl}
htmlId="message-type"
labelAs={Combobox.Label}
onChange={onChange}
subtitle="Contract execute message type"
title="Message Type"
value={value}
>
<div className="relative">
<Combobox.Input
className={clsx(
'w-full bg-white/10 rounded border-2 border-white/20 form-input',
'placeholder:text-white/50',
'focus:ring focus:ring-plumbus-20',
)}
displayValue={(val?: ExecuteListItem) => val?.name ?? ''}
id="message-type"
onChange={(event) => setSearch(event.target.value)}
placeholder="Select message type"
/>
<Combobox.Button
className={clsx(
'flex absolute inset-y-0 right-0 items-center p-4',
'opacity-50 hover:opacity-100 active:opacity-100',
)}
>
{({ open }) => <FaChevronDown aria-hidden="true" className={clsx('w-4 h-4', { 'rotate-180': open })} />}
</Combobox.Button>
<Transition afterLeave={() => setSearch('')} as={Fragment}>
<Combobox.Options
className={clsx(
'overflow-auto absolute z-10 mt-2 w-full max-h-[30vh]',
'bg-stone-800/80 rounded shadow-lg backdrop-blur-sm',
'divide-y divide-stone-500/50',
)}
>
{filtered.length < 1 && (
<span className="flex flex-col justify-center items-center p-4 text-sm text-center text-white/50">
Message type not found.
</span>
)}
{filtered.map((entry) => (
<Combobox.Option
key={entry.id}
className={({ active }) =>
clsx('flex relative flex-col py-2 px-4 space-y-1 cursor-pointer', { 'bg-stargaze-80': active })
}
value={entry}
>
<span className="font-bold">{entry.name}</span>
<span className="max-w-md text-sm">{entry.description}</span>
</Combobox.Option>
))}
</Combobox.Options>
</Transition>
</div>
{value && (
<div className="flex space-x-2 text-white/50">
<div className="mt-1">
<FaInfoCircle className="w-3 h-3" />
</div>
<span className="text-sm">{value.description}</span>
</div>
)}
</Combobox>
)
}

View File

@ -25,7 +25,7 @@ export const QUERY_LIST: QueryListItem[] = [
{ id: 'mint_price', name: 'Mint Price', description: 'View the mint price' },
{
id: 'mint_count',
name: 'Total Minted Count',
name: 'Mint Count for Address',
description: 'View the total amount of minted tokens for an address',
},
{

View File

@ -100,7 +100,7 @@ const BaseMinterQueryPage: NextPage = () => {
onChange={(e) => setType(e.target.value as QueryType)}
>
{QUERY_LIST.map(({ id, name }) => (
<option key={`query-${id}`} value={id}>
<option key={`query-${id}`} className="mt-2 text-lg bg-[#1A1A1A]" value={id}>
{name}
</option>
))}

View File

@ -4,7 +4,7 @@ import type { NextPage } from 'next'
// import Brand from 'public/brand/brand.svg'
import { withMetadata } from 'utils/layout'
import { BADGE_HUB_ADDRESS, BASE_FACTORY_ADDRESS } from '../../utils/constants'
import { BADGE_HUB_ADDRESS, BASE_FACTORY_ADDRESS, OPEN_EDITION_FACTORY_ADDRESS } from '../../utils/constants'
const HomePage: NextPage = () => {
return (
@ -42,6 +42,15 @@ const HomePage: NextPage = () => {
<HomeCard className="p-4 -m-4 hover:bg-gray-500/10 rounded" link="/contracts/sg721" title="Sg721 Contract">
Execute messages and run queries on Stargaze&apos;s SG721 contract.
</HomeCard>
<Conditional test={OPEN_EDITION_FACTORY_ADDRESS !== undefined}>
<HomeCard
className="p-4 -m-4 hover:bg-gray-500/10 rounded"
link="/contracts/openEditionMinter"
title="Open Edition Minter Contract"
>
Execute messages and run queries on Stargaze&apos;s Open Edition Minter contract.
</HomeCard>
</Conditional>
<HomeCard
className="p-4 -m-4 hover:bg-gray-500/10 rounded"
link="/contracts/whitelist"

View File

@ -0,0 +1,249 @@
import { Button } from 'components/Button'
import { Conditional } from 'components/Conditional'
import { ContractPageHeader } from 'components/ContractPageHeader'
import { ExecuteCombobox } from 'components/contracts/openEditionMinter/ExecuteCombobox'
import { useExecuteComboboxState } from 'components/contracts/openEditionMinter/ExecuteCombobox.hooks'
import { FormControl } from 'components/FormControl'
import { AddressInput, NumberInput } from 'components/forms/FormInput'
import { useInputState, useNumberInputState } from 'components/forms/FormInput.hooks'
import { InputDateTime } from 'components/InputDateTime'
import { JsonPreview } from 'components/JsonPreview'
import { LinkTabs } from 'components/LinkTabs'
import { openEditionMinterLinkTabs } from 'components/LinkTabs.data'
import { TransactionHash } from 'components/TransactionHash'
import { useContracts } from 'contexts/contracts'
import { useWallet } from 'contexts/wallet'
import type { DispatchExecuteArgs } from 'contracts/openEditionMinter/messages/execute'
import { dispatchExecute, isEitherType, previewExecutePayload } from 'contracts/openEditionMinter/messages/execute'
import type { NextPage } from 'next'
import { useRouter } from 'next/router'
import { NextSeo } from 'next-seo'
import type { FormEvent } from 'react'
import { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-hot-toast'
import { FaArrowRight } from 'react-icons/fa'
import { useMutation } from 'react-query'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
import { resolveAddress } from 'utils/resolveAddress'
const OpenEditionMinterExecutePage: NextPage = () => {
const { openEditionMinter: contract } = useContracts()
const wallet = useWallet()
const [lastTx, setLastTx] = useState('')
const [timestamp, setTimestamp] = useState<Date | undefined>(undefined)
const [endTimestamp, setEndTimestamp] = useState<Date | undefined>(undefined)
const [resolvedRecipientAddress, setResolvedRecipientAddress] = useState<string>('')
const comboboxState = useExecuteComboboxState()
const type = comboboxState.value?.id
const limitState = useNumberInputState({
id: 'per-address-limit',
name: 'perAddressLimit',
title: 'Per Address Limit',
subtitle: 'Enter the per address limit',
})
const tokenIdState = useNumberInputState({
id: 'token-id',
name: 'tokenId',
title: 'Token ID',
subtitle: 'Enter the token ID',
})
const priceState = useNumberInputState({
id: 'price',
name: 'price',
title: 'Price',
subtitle: 'Enter the price for each token',
})
const contractState = useInputState({
id: 'contract-address',
name: 'contract-address',
title: 'Open Edition Minter Address',
subtitle: 'Address of the Open Edition Minter contract',
})
const contractAddress = contractState.value
const recipientState = useInputState({
id: 'recipient-address',
name: 'recipient',
title: 'Recipient Address',
subtitle: 'Address of the recipient',
})
const showDateField = isEitherType(type, ['update_start_time', 'update_start_trading_time'])
const showEndDateField = type === 'update_end_time'
const showLimitField = type === 'update_per_address_limit'
const showRecipientField = isEitherType(type, ['mint_to'])
const showPriceField = isEitherType(type, ['update_mint_price'])
const messages = useMemo(() => contract?.use(contractState.value), [contract, wallet.address, contractState.value])
const payload: DispatchExecuteArgs = {
startTime: timestamp ? (timestamp.getTime() * 1_000_000).toString() : '',
endTime: endTimestamp ? (endTimestamp.getTime() * 1_000_000).toString() : '',
limit: limitState.value,
contract: contractState.value,
messages,
recipient: resolvedRecipientAddress,
txSigner: wallet.address,
price: priceState.value ? priceState.value.toString() : '0',
type,
}
const { isLoading, mutate } = useMutation(
async (event: FormEvent) => {
event.preventDefault()
if (!type) {
throw new Error('Please select message type!')
}
if (!wallet.initialized) {
throw new Error('Please connect your wallet.')
}
if (contractState.value === '') {
throw new Error('Please enter the contract address.')
}
if (wallet.client && type === 'update_mint_price') {
const contractConfig = wallet.client.queryContractSmart(contractState.value, {
config: {},
})
await toast
.promise(
wallet.client.queryContractSmart(contractState.value, {
mint_price: {},
}),
{
error: `Querying mint price failed!`,
loading: 'Querying current mint price...',
success: (price) => {
console.log(price)
return `Current mint price is ${Number(price.public_price.amount) / 1000000} STARS`
},
},
)
.then(async (price) => {
if (Number(price.public_price.amount) / 1000000 <= priceState.value) {
await contractConfig
.then((config) => {
console.log(config.start_time, Date.now() * 1000000)
if (Number(config.start_time) < Date.now() * 1000000) {
throw new Error(
`Minting has already started on ${new Date(
Number(config.start_time) / 1000000,
).toLocaleString()}. Updated mint price cannot be higher than the current price of ${
Number(price.public_price.amount) / 1000000
} STARS`,
)
}
})
.catch((error) => {
throw new Error(String(error).substring(String(error).lastIndexOf('Error:') + 7))
})
} else {
await contractConfig.then(async (config) => {
const factoryParameters = await wallet.client?.queryContractSmart(config.factory, {
params: {},
})
if (
factoryParameters.params.min_mint_price.amount &&
priceState.value < Number(factoryParameters.params.min_mint_price.amount) / 1000000
) {
throw new Error(
`Updated mint price cannot be lower than the minimum mint price of ${
Number(factoryParameters.params.min_mint_price.amount) / 1000000
} STARS`,
)
}
})
}
})
}
const txHash = await toast.promise(dispatchExecute(payload), {
error: `${type.charAt(0).toUpperCase() + type.slice(1)} execute failed!`,
loading: 'Executing message...',
success: (tx) => `Transaction ${tx} success!`,
})
if (txHash) {
setLastTx(txHash)
}
},
{
onError: (error) => {
toast.error(String(error), { style: { maxWidth: 'none' } })
},
},
)
const router = useRouter()
useEffect(() => {
if (contractAddress.length > 0) {
void router.replace({ query: { contractAddress } })
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contractAddress])
useEffect(() => {
const initial = new URL(document.URL).searchParams.get('contractAddress')
if (initial && initial.length > 0) contractState.onChange(initial)
}, [])
const resolveRecipientAddress = async () => {
await resolveAddress(recipientState.value.trim(), wallet).then((resolvedAddress) => {
setResolvedRecipientAddress(resolvedAddress)
})
}
useEffect(() => {
void resolveRecipientAddress()
}, [recipientState.value])
return (
<section className="py-6 px-12 space-y-4">
<NextSeo title="Execute Open Edition Minter Contract" />
<ContractPageHeader
description="Open Edition Minter contract allows multiple copies of a single NFT to be minted in a specified time interval."
link={links.Documentation}
title="Open Edition Minter Contract"
/>
<LinkTabs activeIndex={1} data={openEditionMinterLinkTabs} />
<form className="grid grid-cols-2 p-4 space-x-8" onSubmit={mutate}>
<div className="space-y-8">
<AddressInput {...contractState} />
<ExecuteCombobox {...comboboxState} />
{showRecipientField && <AddressInput {...recipientState} />}
{showLimitField && <NumberInput {...limitState} />}
{showPriceField && <NumberInput {...priceState} />}
{/* TODO: Fix address execute message */}
<Conditional test={showDateField}>
<FormControl htmlId="start-date" subtitle="Start time for the minting" title="Start Time">
<InputDateTime minDate={new Date()} onChange={(date) => setTimestamp(date)} value={timestamp} />
</FormControl>
</Conditional>
<Conditional test={showEndDateField}>
<FormControl htmlId="end-date" subtitle="End time for the minting" title="End Time">
<InputDateTime minDate={new Date()} onChange={(date) => setEndTimestamp(date)} value={endTimestamp} />
</FormControl>
</Conditional>
</div>
<div className="space-y-8">
<div className="relative">
<Button className="absolute top-0 right-0" isLoading={isLoading} rightIcon={<FaArrowRight />} type="submit">
Execute
</Button>
<FormControl subtitle="View execution transaction hash" title="Transaction Hash">
<TransactionHash hash={lastTx} />
</FormControl>
</div>
<FormControl subtitle="View current message to be sent" title="Payload Preview">
<JsonPreview content={previewExecutePayload(payload)} isCopyable />
</FormControl>
</div>
</form>
</section>
)
}
export default withMetadata(OpenEditionMinterExecutePage, { center: false })

View File

@ -0,0 +1 @@
export { default } from './execute'

View File

@ -0,0 +1,132 @@
import { Button } from 'components/Button'
import { ContractPageHeader } from 'components/ContractPageHeader'
import { useExecuteComboboxState } from 'components/contracts/openEditionMinter/ExecuteCombobox.hooks'
import { FormControl } from 'components/FormControl'
import { AddressInput, NumberInput } from 'components/forms/FormInput'
import { useInputState, useNumberInputState } from 'components/forms/FormInput.hooks'
import { JsonPreview } from 'components/JsonPreview'
import { LinkTabs } from 'components/LinkTabs'
import { openEditionMinterLinkTabs } from 'components/LinkTabs.data'
import { TransactionHash } from 'components/TransactionHash'
import { useContracts } from 'contexts/contracts'
import { useWallet } from 'contexts/wallet'
import type { MigrateResponse } from 'contracts/openEditionMinter'
import type { NextPage } from 'next'
import { useRouter } from 'next/router'
import { NextSeo } from 'next-seo'
import type { FormEvent } from 'react'
import { useEffect, useState } from 'react'
import { toast } from 'react-hot-toast'
import { FaArrowRight } from 'react-icons/fa'
import { useMutation } from 'react-query'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
const OpenEditionMinterMigratePage: NextPage = () => {
const { openEditionMinter: contract } = useContracts()
const wallet = useWallet()
const [lastTx, setLastTx] = useState('')
const comboboxState = useExecuteComboboxState()
const type = comboboxState.value?.id
const codeIdState = useNumberInputState({
id: 'code-id',
name: 'code-id',
title: 'Code ID',
subtitle: 'Code ID of the New Open Edition Minter',
placeholder: '1',
})
const contractState = useInputState({
id: 'contract-address',
name: 'contract-address',
title: 'Open Edition Minter Address',
subtitle: 'Address of the Open Edition Minter contract',
})
const contractAddress = contractState.value
const { data, isLoading, mutate } = useMutation(
async (event: FormEvent): Promise<MigrateResponse | null> => {
event.preventDefault()
if (!contract) {
throw new Error('Smart contract connection failed')
}
if (!wallet.initialized) {
throw new Error('Please connect your wallet.')
}
const migrateMsg = {}
return toast.promise(contract.migrate(contractAddress, codeIdState.value, migrateMsg), {
error: `Migration failed!`,
loading: 'Executing message...',
success: (tx) => {
if (tx) {
setLastTx(tx.transactionHash)
}
return `Transaction success!`
},
})
},
{
onError: (error) => {
toast.error(String(error), { style: { maxWidth: 'none' } })
},
},
)
const router = useRouter()
useEffect(() => {
if (contractAddress.length > 0) {
void router.replace({ query: { contractAddress } })
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contractAddress])
useEffect(() => {
const initial = new URL(document.URL).searchParams.get('contractAddress')
if (initial && initial.length > 0) contractState.onChange(initial)
}, [])
return (
<section className="py-6 px-12 space-y-4">
<NextSeo title="Migrate Open Edition Minter Contract" />
<ContractPageHeader
description="Open Edition Minter contract allows multiple copies of a single NFT to be minted in a specified time interval."
link={links.Documentation}
title="Open Edition Minter Contract"
/>
<LinkTabs activeIndex={2} data={openEditionMinterLinkTabs} />
<form className="grid grid-cols-2 p-4 space-x-8" onSubmit={mutate}>
<div className="space-y-8">
<AddressInput {...contractState} />
<NumberInput isRequired {...codeIdState} />
</div>
<div className="space-y-8">
<div className="relative">
<Button className="absolute top-0 right-0" isLoading={isLoading} rightIcon={<FaArrowRight />} type="submit">
Execute
</Button>
<FormControl subtitle="View execution transaction hash" title="Transaction Hash">
<TransactionHash hash={lastTx} />
</FormControl>
</div>
<FormControl subtitle="View current message to be sent" title="Payload Preview">
<JsonPreview
content={{
sender: wallet.address,
contract: contractAddress,
code_id: codeIdState.value,
msg: {},
}}
isCopyable
/>
</FormControl>
</div>
</form>
</section>
)
}
export default withMetadata(OpenEditionMinterMigratePage, { center: false })

View File

@ -0,0 +1,124 @@
import clsx from 'clsx'
import { Conditional } from 'components/Conditional'
import { ContractPageHeader } from 'components/ContractPageHeader'
import { FormControl } from 'components/FormControl'
import { AddressInput } from 'components/forms/FormInput'
import { useInputState } from 'components/forms/FormInput.hooks'
import { JsonPreview } from 'components/JsonPreview'
import { LinkTabs } from 'components/LinkTabs'
import { openEditionMinterLinkTabs } from 'components/LinkTabs.data'
import { useContracts } from 'contexts/contracts'
import { useWallet } from 'contexts/wallet'
import type { QueryType } from 'contracts/openEditionMinter/messages/query'
import { dispatchQuery, QUERY_LIST } from 'contracts/openEditionMinter/messages/query'
import type { NextPage } from 'next'
import { useRouter } from 'next/router'
import { NextSeo } from 'next-seo'
import { useEffect, useState } from 'react'
import { toast } from 'react-hot-toast'
import { useQuery } from 'react-query'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
import { resolveAddress } from 'utils/resolveAddress'
const OpenEditionMinterQueryPage: NextPage = () => {
const { openEditionMinter: contract } = useContracts()
const wallet = useWallet()
const contractState = useInputState({
id: 'contract-address',
name: 'contract-address',
title: 'Open Edition Minter Address',
subtitle: 'Address of the Open Edition Minter contract',
})
const contractAddress = contractState.value
const addressState = useInputState({
id: 'address',
name: 'address',
title: 'Address',
subtitle: 'Address of the user - defaults to current address',
})
const address = addressState.value
const [type, setType] = useState<QueryType>('config')
const { data: response } = useQuery(
[contractAddress, type, contract, wallet, address] as const,
async ({ queryKey }) => {
const [_contractAddress, _type, _contract, _wallet] = queryKey
const messages = contract?.use(_contractAddress)
const res = await resolveAddress(address, wallet).then(async (resolvedAddress) => {
const result = await dispatchQuery({
address: resolvedAddress,
messages,
type,
})
return result
})
return res
},
{
placeholderData: null,
onError: (error: any) => {
toast.error(error.message, { style: { maxWidth: 'none' } })
},
enabled: Boolean(contractAddress && contract && wallet),
},
)
const router = useRouter()
useEffect(() => {
if (contractAddress.length > 0) {
void router.replace({ query: { contractAddress } })
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contractAddress])
useEffect(() => {
const initial = new URL(document.URL).searchParams.get('contractAddress')
if (initial && initial.length > 0) contractState.onChange(initial)
}, [])
return (
<section className="py-6 px-12 space-y-4">
<NextSeo title="Query Open Edition Minter Contract" />
<ContractPageHeader
description="Open Edition Minter contract allows multiple copies of a single NFT to be minted in a specified time interval."
link={links.Documentation}
title="Open Edition Minter Contract"
/>
<LinkTabs activeIndex={0} data={openEditionMinterLinkTabs} />
<div className="grid grid-cols-2 p-4 space-x-8">
<div className="space-y-8">
<AddressInput {...contractState} />
<FormControl htmlId="contract-query-type" subtitle="Type of query to be dispatched" title="Query Type">
<select
className={clsx(
'bg-white/10 rounded border-2 border-white/20 form-select',
'placeholder:text-white/50',
'focus:ring focus:ring-plumbus-20',
)}
id="contract-query-type"
name="query-type"
onChange={(e) => setType(e.target.value as QueryType)}
>
{QUERY_LIST.map(({ id, name }) => (
<option key={`query-${id}`} className="mt-2 text-lg bg-[#1A1A1A]" value={id}>
{name}
</option>
))}
</select>
</FormControl>
<Conditional test={type === 'mint_count'}>
<AddressInput {...addressState} />
</Conditional>
</div>
<JsonPreview content={contractAddress ? { type, response } : null} title="Query Response" />
</div>
</section>
)
}
export default withMetadata(OpenEditionMinterQueryPage, { center: false })

View File

@ -118,7 +118,7 @@ const Sg721QueryPage: NextPage = () => {
onChange={(e) => setType(e.target.value as QueryType)}
>
{QUERY_LIST.map(({ id, name }) => (
<option key={`query-${id}`} value={id}>
<option key={`query-${id}`} className="mt-2 text-lg bg-[#1A1A1A]" value={id}>
{name}
</option>
))}

View File

@ -105,7 +105,7 @@ const VendingMinterQueryPage: NextPage = () => {
onChange={(e) => setType(e.target.value as QueryType)}
>
{QUERY_LIST.map(({ id, name }) => (
<option key={`query-${id}`} value={id}>
<option key={`query-${id}`} className="mt-2 text-lg bg-[#1A1A1A]" value={id}>
{name}
</option>
))}