Add collection queries page (#5)

This commit is contained in:
Arda Nakışçı 2022-07-26 11:42:45 +03:00 committed by GitHub
parent 708da8a58a
commit 7b58c9e8ac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 320 additions and 1 deletions

View File

@ -61,7 +61,7 @@ export const ActionsCombobox = ({ value, onChange }: ActionsComboboxProps) => {
>
{filtered.length < 1 && (
<span className="flex flex-col justify-center items-center p-4 text-sm text-center text-white/50">
Action found.
Action not found
</span>
)}
{filtered.map((entry) => (

View File

@ -0,0 +1,8 @@
import { useState } from 'react'
import type { QueryListItem } from './query'
export const useQueryComboboxState = () => {
const [value, setValue] = useState<QueryListItem | null>(null)
return { value, onChange: (item: QueryListItem) => setValue(item) }
}

View File

@ -0,0 +1,92 @@
import { Combobox, Transition } from '@headlessui/react'
import clsx from 'clsx'
import { FormControl } from 'components/FormControl'
import { matchSorter } from 'match-sorter'
import { Fragment, useState } from 'react'
import { FaChevronDown, FaInfoCircle } from 'react-icons/fa'
import type { QueryListItem } from './query'
import { QUERY_LIST } from './query'
export interface QueryComboboxProps {
value: QueryListItem | null
onChange: (item: QueryListItem) => void
}
export const QueryCombobox = ({ value, onChange }: QueryComboboxProps) => {
const [search, setSearch] = useState('')
const filtered = search === '' ? QUERY_LIST : matchSorter(QUERY_LIST, search, { keys: ['id', 'name', 'description'] })
return (
<Combobox
as={FormControl}
htmlId="query"
labelAs={Combobox.Label}
onChange={onChange}
subtitle="Collection queries"
title="Query"
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?: QueryListItem) => val?.name ?? ''}
id="message-type"
onChange={(event) => setSearch(event.target.value)}
placeholder="Select query"
/>
<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">
Query 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-plumbus-70': 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

@ -0,0 +1,103 @@
import type { MinterInstance } from 'contracts/minter'
import type { SG721Instance } from 'contracts/sg721'
export type QueryType = typeof QUERY_TYPES[number]
export const QUERY_TYPES = [
'collection_info',
'mint_price',
'num_tokens',
'tokens_minted_to_user',
// 'token_owners',
'token_info',
] as const
export interface QueryListItem {
id: QueryType
name: string
description?: string
}
export const QUERY_LIST: QueryListItem[] = [
{
id: 'collection_info',
name: 'Collection Info',
description: `Get information about the collection.`,
},
{
id: 'mint_price',
name: 'Mint Price',
description: `Get the price of minting a token.`,
},
{
id: 'num_tokens',
name: 'Mintable Number of Tokens',
description: `Get the mintable number of tokens in the collection.`,
},
{
id: 'tokens_minted_to_user',
name: 'Tokens Minted to User',
description: `Get the number of tokens minted in the collection to a user.`,
},
// {
// id: 'token_owners',
// name: 'Token Owners',
// description: `Get the list of users who own tokens in the collection.`,
// },
{
id: 'token_info',
name: 'Token Info',
description: `Get information about a token in the collection.`,
},
]
export interface DispatchExecuteProps {
type: QueryType
[k: string]: unknown
}
type Select<T extends QueryType> = T
export type DispatchQueryArgs = {
minterMessages?: MinterInstance
sg721Messages?: SG721Instance
} & (
| { type: undefined }
| { type: Select<'collection_info'> }
| { type: Select<'mint_price'> }
| { type: Select<'num_tokens'> }
| { type: Select<'tokens_minted_to_user'>; address: string }
// | { type: Select<'token_owners'> }
| { type: Select<'token_info'>; tokenId: string }
)
export const dispatchQuery = async (args: DispatchQueryArgs) => {
const { minterMessages, sg721Messages } = args
if (!minterMessages || !sg721Messages) {
throw new Error('Cannot execute actions')
}
switch (args.type) {
case 'collection_info': {
return sg721Messages.collectionInfo()
}
case 'mint_price': {
return minterMessages.getMintPrice()
}
case 'num_tokens': {
return minterMessages.getMintableNumTokens()
}
case 'tokens_minted_to_user': {
return minterMessages.getMintCount(args.address)
}
// case 'token_owners': {
// return minterMessages.updateStartTime(txSigner, args.startTime)
// }
case 'token_info': {
if (!args.tokenId) return
return sg721Messages.allNftInfo(args.tokenId)
}
default: {
throw new Error('Unknown action')
}
}
}

View File

@ -0,0 +1,116 @@
import { QueryCombobox } from 'components/collections/queries/Combobox'
import { useQueryComboboxState } from 'components/collections/queries/Combobox.hooks'
import { dispatchQuery } from 'components/collections/queries/query'
import { ContractPageHeader } from 'components/ContractPageHeader'
import { FormControl } from 'components/FormControl'
import { AddressInput, TextInput } from 'components/forms/FormInput'
import { useInputState } from 'components/forms/FormInput.hooks'
import { JsonPreview } from 'components/JsonPreview'
import { useContracts } from 'contexts/contracts'
import type { NextPage } from 'next'
import { NextSeo } from 'next-seo'
import { useMemo } from 'react'
import { toast } from 'react-hot-toast'
import { useQuery } from 'react-query'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
const CollectionQueriesPage: NextPage = () => {
const { minter: minterContract, sg721: sg721Contract } = useContracts()
const comboboxState = useQueryComboboxState()
const type = comboboxState.value?.id
const sg721ContractState = useInputState({
id: 'sg721-contract-address',
name: 'sg721-contract-address',
title: 'Sg721 Address',
subtitle: 'Address of the Sg721 contract',
})
const sg721ContractAddress = sg721ContractState.value
const minterContractState = useInputState({
id: 'minter-contract-address',
name: 'minter-contract-address',
title: 'Minter Address',
subtitle: 'Address of the Minter contract',
})
const minterContractAddress = minterContractState.value
const tokenIdState = useInputState({
id: 'token-id',
name: 'tokenId',
title: 'Token ID',
subtitle: 'Enter the token ID',
placeholder: '1',
})
const tokenId = tokenIdState.value
const addressState = useInputState({
id: 'address',
name: 'address',
title: 'User Address',
subtitle: 'Address of the user',
})
const address = addressState.value
const showTokenIdField = type === 'token_info'
const showAddressField = type === 'tokens_minted_to_user'
const minterMessages = useMemo(
() => minterContract?.use(minterContractAddress),
[minterContract, minterContractAddress],
)
const sg721Messages = useMemo(() => sg721Contract?.use(sg721ContractAddress), [sg721Contract, sg721ContractAddress])
const { data: response } = useQuery(
[sg721Messages, minterMessages, type, tokenId, address] as const,
async ({ queryKey }) => {
const [_sg721Messages, _minterMessages, _type, _tokenId, _address] = queryKey
const result = await dispatchQuery({
tokenId: _tokenId,
minterMessages: _minterMessages,
sg721Messages: _sg721Messages,
address: _address,
type: _type,
})
return result
},
{
placeholderData: null,
onError: (error: any) => {
toast.error(error.message)
},
enabled: Boolean(sg721ContractAddress && minterContractAddress && type),
retry: false,
},
)
return (
<section className="py-6 px-12 space-y-4">
<NextSeo title="Collection Queries" />
<ContractPageHeader
description="Here you can query your collection for information"
link={links.Documentation}
title="Collection Queries"
/>
<div className="grid grid-cols-2 p-4 space-x-8">
<div className="space-y-8">
<AddressInput {...sg721ContractState} />
<AddressInput {...minterContractState} />
<QueryCombobox {...comboboxState} />
{showAddressField && <AddressInput {...addressState} />}
{showTokenIdField && <TextInput {...tokenIdState} />}
</div>
<div className="space-y-8">
<FormControl title="Query Response">
<JsonPreview content={response || {}} isCopyable />
</FormControl>
</div>
</div>
</section>
)
}
export default withMetadata(CollectionQueriesPage, { center: false })