Merge pull request #365 from public-awesome/develop

Sync dev > main
This commit is contained in:
Serkan Reis 2024-04-10 19:00:42 +03:00 committed by GitHub
commit 6487646f2c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 303 additions and 56 deletions

View File

@ -43,7 +43,7 @@ export interface WhitelistDetailsDataProps {
type WhitelistState = 'none' | 'existing' | 'new'
type WhitelistType = 'standard' | 'flex' | 'merkletree'
export type WhitelistType = 'standard' | 'flex' | 'merkletree'
export const WhitelistDetails = ({
onChange,

View File

@ -1,8 +1,11 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable no-nested-ternary */
import { Combobox, Transition } from '@headlessui/react'
import clsx from 'clsx'
import { FormControl } from 'components/FormControl'
import type { ExecuteListItem } from 'contracts/whitelist/messages/execute'
import { EXECUTE_LIST } from 'contracts/whitelist/messages/execute'
import { EXECUTE_LIST as WL_MERKLE_TREE_EXECUTE_LIST } from 'contracts/whitelistMerkleTree/messages/execute'
import { matchSorter } from 'match-sorter'
import { Fragment, useState } from 'react'
import { FaChevronDown, FaInfoCircle } from 'react-icons/fa'
@ -10,13 +13,20 @@ import { FaChevronDown, FaInfoCircle } from 'react-icons/fa'
export interface ExecuteComboboxProps {
value: ExecuteListItem | null
onChange: (item: ExecuteListItem) => void
whitelistType?: 'standard' | 'flex' | 'merkletree'
}
export const ExecuteCombobox = ({ value, onChange }: ExecuteComboboxProps) => {
export const ExecuteCombobox = ({ value, onChange, whitelistType }: ExecuteComboboxProps) => {
const [search, setSearch] = useState('')
const filtered =
search === '' ? EXECUTE_LIST : matchSorter(EXECUTE_LIST, search, { keys: ['id', 'name', 'description'] })
whitelistType !== 'merkletree'
? search === ''
? EXECUTE_LIST
: matchSorter(EXECUTE_LIST, search, { keys: ['id', 'name', 'description'] })
: search === ''
? WL_MERKLE_TREE_EXECUTE_LIST
: matchSorter(WL_MERKLE_TREE_EXECUTE_LIST, search, { keys: ['id', 'name', 'description'] })
return (
<Combobox

View File

@ -162,7 +162,7 @@ export const WhiteListMerkleTree = (client: SigningCosmWasmClient, txSigner: str
const merkleTreeUri = async (): Promise<string> => {
return client.queryContractSmart(contractAddress, {
merkle_tree_uri: {},
merkle_tree_u_r_i: {},
})
}

View File

@ -36,16 +36,16 @@ export const EXECUTE_LIST: ExecuteListItem[] = [
name: 'Update Admins',
description: `Update the list of administrators for the whitelist`,
},
{
id: 'add_members',
name: 'Add Members',
description: `Add members to the whitelist`,
},
{
id: 'remove_members',
name: 'Remove Members',
description: `Remove members from the whitelist`,
},
// {
// id: 'add_members',
// name: 'Add Members',
// description: `Add members to the whitelist`,
// },
// {
// id: 'remove_members',
// name: 'Remove Members',
// description: `Remove members from the whitelist`,
// },
// {
// id: 'update_per_address_limit',
// name: 'Update Per Address Limit',

View File

@ -1,8 +1,8 @@
import type { WhiteListMerkleTreeInstance } from '../contract'
export type QueryType = typeof QUERY_TYPES[number]
export type WhitelistMerkleTreeQueryType = typeof WHITELIST_MERKLE_TREE_QUERY_TYPES[number]
export const QUERY_TYPES = [
export const WHITELIST_MERKLE_TREE_QUERY_TYPES = [
'has_started',
'has_ended',
'is_active',
@ -14,12 +14,12 @@ export const QUERY_TYPES = [
] as const
export interface QueryListItem {
id: QueryType
id: WhitelistMerkleTreeQueryType
name: string
description?: string
}
export const QUERY_LIST: QueryListItem[] = [
export const WHITELIST_MERKLE_TREE_QUERY_LIST: QueryListItem[] = [
{ id: 'has_started', name: 'Has Started', description: 'Check if the whitelist minting has started' },
{ id: 'has_ended', name: 'Has Ended', description: 'Check if the whitelist minting has ended' },
{ id: 'is_active', name: 'Is Active', description: 'Check if the whitelist minting is active' },
@ -32,7 +32,7 @@ export const QUERY_LIST: QueryListItem[] = [
export interface DispatchQueryProps {
messages: WhiteListMerkleTreeInstance | undefined
type: QueryType
type: WhitelistMerkleTreeQueryType
address: string
startAfter?: string
limit?: number

View File

@ -48,7 +48,7 @@ const WhitelistExecutePage: NextPage = () => {
const [lastTx, setLastTx] = useState('')
const [memberList, setMemberList] = useState<string[]>([])
const [flexMemberList, setFlexMemberList] = useState<WhitelistFlexMember[]>([])
const [whitelistType, setWhitelistType] = useState<'standard' | 'flex'>('standard')
const [whitelistType, setWhitelistType] = useState<'standard' | 'flex' | 'merkletree'>('standard')
const comboboxState = useExecuteComboboxState()
const type = comboboxState.value?.id
@ -211,6 +211,8 @@ const WhitelistExecutePage: NextPage = () => {
.then((contractType) => {
if (contractType?.includes('flex')) {
setWhitelistType('flex')
} else if (contractType?.includes('merkle')) {
setWhitelistType('merkletree')
} else {
setWhitelistType('standard')
}
@ -236,7 +238,7 @@ const WhitelistExecutePage: NextPage = () => {
<form className="grid grid-cols-2 p-4 space-x-8" onSubmit={mutate}>
<div className="space-y-8">
<AddressInput {...contractState} />
<ExecuteCombobox {...comboboxState} />
<ExecuteCombobox whitelistType={whitelistType} {...comboboxState} />
<Conditional test={showLimitState}>
<NumberInput {...limitState} />
</Conditional>

View File

@ -1,6 +1,7 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable no-nested-ternary */
import { coin } from '@cosmjs/proto-signing'
import axios from 'axios'
import { Alert } from 'components/Alert'
import { Button } from 'components/Button'
import { Conditional } from 'components/Conditional'
@ -34,17 +35,22 @@ import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
import { useWallet } from 'utils/wallet'
import { WHITELIST_CODE_ID, WHITELIST_FLEX_CODE_ID } from '../../../utils/constants'
import {
WHITELIST_CODE_ID,
WHITELIST_FLEX_CODE_ID,
WHITELIST_MERKLE_TREE_API_URL,
WHITELIST_MERKLE_TREE_CODE_ID,
} from '../../../utils/constants'
const WhitelistInstantiatePage: NextPage = () => {
const wallet = useWallet()
const { whitelist: contract } = useContracts()
const { whitelist: contract, whitelistMerkleTree: whitelistMerkleTreeContract } = useContracts()
const { timezone } = useGlobalSettings()
const [startDate, setStartDate] = useState<Date | undefined>(undefined)
const [endDate, setEndDate] = useState<Date | undefined>(undefined)
const [adminsMutable, setAdminsMutable] = useState<boolean>(true)
const [whitelistType, setWhitelistType] = useState<'standard' | 'flex'>('standard')
const [whitelistType, setWhitelistType] = useState<'standard' | 'flex' | 'merkletree'>('standard')
const [whitelistStandardArray, setWhitelistStandardArray] = useState<string[]>([])
const [whitelistFlexArray, setWhitelistFlexArray] = useState<WhitelistFlexMember[]>([])
@ -85,12 +91,16 @@ const WhitelistInstantiatePage: NextPage = () => {
const addressListState = useAddressListState()
const { data, isLoading, mutate } = useMutation(
async (event: FormEvent): Promise<InstantiateResponse | null> => {
async (event: FormEvent): Promise<InstantiateResponse | undefined | null> => {
event.preventDefault()
if (!contract) {
throw new Error('Smart contract connection failed')
}
if (!whitelistMerkleTreeContract && whitelistType === 'merkletree') {
throw new Error('Smart contract connection failed')
}
if (!startDate) {
throw new Error('Start date is required')
}
@ -132,19 +142,79 @@ const WhitelistInstantiatePage: NextPage = () => {
admins_mutable: adminsMutable,
}
return toast.promise(
contract.instantiate(
whitelistType === 'standard' ? WHITELIST_CODE_ID : WHITELIST_FLEX_CODE_ID,
whitelistType === 'standard' ? standardMsg : flexMsg,
whitelistType === 'standard' ? 'Stargaze Whitelist Contract' : 'Stargaze Whitelist Flex Contract',
wallet.address,
),
{
loading: 'Instantiating contract...',
error: 'Instantiation failed!',
success: 'Instantiation success!',
},
)
if (whitelistType !== 'merkletree') {
return toast.promise(
contract.instantiate(
whitelistType === 'standard' ? WHITELIST_CODE_ID : WHITELIST_FLEX_CODE_ID,
whitelistType === 'standard' ? standardMsg : flexMsg,
whitelistType === 'standard' ? 'Stargaze Whitelist Contract' : 'Stargaze Whitelist Flex Contract',
wallet.address,
),
{
loading: 'Instantiating contract...',
error: 'Instantiation failed!',
success: 'Instantiation success!',
},
)
} else if (whitelistType === 'merkletree') {
const members = whitelistStandardArray
const membersCsv = members.join('\n')
const membersBlob = new Blob([membersCsv], { type: 'text/csv' })
const membersFile = new File([membersBlob], 'members.csv', { type: 'text/csv' })
const formData = new FormData()
formData.append('whitelist', membersFile)
const response = await toast
.promise(
axios.post(`${WHITELIST_MERKLE_TREE_API_URL}/create_whitelist`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
}),
{
loading: 'Fetching merkle root hash...',
success: 'Merkle root fetched successfully.',
error: 'Error fetching root hash from Whitelist Merkle Tree API.',
},
)
.catch((error) => {
console.log('error', error)
throw new Error('Whitelist instantiation failed.')
})
const rootHash = response.data.root_hash
console.log('rootHash', rootHash)
const merkleTreeMsg = {
merkle_root: rootHash,
merkle_tree_uri: null,
start_time: (startDate.getTime() * 1_000_000).toString(),
end_time: (endDate.getTime() * 1_000_000).toString(),
mint_price: coin(String(Number(unitPriceState.value) * 1000000), selectedMintToken?.denom || 'ustars'),
per_address_limit: perAddressLimitState.value,
admins: [
...new Set(
addressListState.values
.map((a) => a.address.trim())
.filter((address) => address !== '' && isValidAddress(address.trim()) && address.startsWith('stars')),
),
] || [wallet.address],
admins_mutable: adminsMutable,
}
return toast.promise(
whitelistMerkleTreeContract?.instantiate(
WHITELIST_MERKLE_TREE_CODE_ID,
merkleTreeMsg,
'Stargaze Whitelist Merkle Tree Contract',
wallet.address,
) as Promise<InstantiateResponse>,
{
loading: 'Instantiating contract...',
error: 'Instantiation failed!',
success: 'Instantiation success!',
},
)
}
},
{
onError: (error) => {
@ -176,7 +246,7 @@ const WhitelistInstantiatePage: NextPage = () => {
/>
<LinkTabs activeIndex={0} data={whitelistLinkTabs} />
<div className="flex justify-between mb-5 ml-6 max-w-[300px] text-lg font-bold">
<div className="flex justify-between mb-5 ml-6 max-w-[520px] text-lg font-bold">
<div className="form-check form-check-inline">
<input
checked={whitelistType === 'standard'}
@ -216,6 +286,26 @@ const WhitelistInstantiatePage: NextPage = () => {
Whitelist Flex
</label>
</div>
<div className="form-check form-check-inline">
<input
checked={whitelistType === 'merkletree'}
className="peer sr-only"
id="inlineRadio3"
name="inlineRadioOptions3"
onClick={() => {
setWhitelistType('merkletree')
}}
type="radio"
value="merkletree"
/>
<label
className="inline-block py-1 px-2 text-gray peer-checked:text-white hover:text-white peer-checked:bg-black hover:rounded-sm peer-checked:border-b-2 hover:border-b-2 peer-checked:border-plumbus hover:border-plumbus cursor-pointer form-check-label"
htmlFor="inlineRadio3"
>
Whitelist Merkle Tree
</label>
</div>
</div>
<Conditional test={Boolean(data)}>
@ -251,7 +341,7 @@ const WhitelistInstantiatePage: NextPage = () => {
</div>
<FormGroup subtitle="Your whitelisted addresses" title="Whitelist File">
<Conditional test={whitelistType === 'standard'}>
<Conditional test={whitelistType === 'standard' || whitelistType === 'merkletree'}>
<WhitelistUpload onChange={whitelistFileOnChange} />
<Conditional test={whitelistStandardArray.length > 0}>
<JsonPreview content={whitelistStandardArray} initialState={false} title="File Contents" />
@ -283,8 +373,10 @@ const WhitelistInstantiatePage: NextPage = () => {
</select>
</div>
<NumberInput isRequired {...memberLimitState} />
<Conditional test={whitelistType === 'standard'}>
<Conditional test={whitelistType !== 'merkletree'}>
<NumberInput isRequired {...memberLimitState} />
</Conditional>
<Conditional test={whitelistType === 'standard' || whitelistType === 'merkletree'}>
<NumberInput isRequired {...perAddressLimitState} />
</Conditional>
<Conditional test={whitelistType === 'flex'}>

View File

@ -1,4 +1,6 @@
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable no-nested-ternary */
/* eslint-disable no-await-in-loop */
/* eslint-disable @typescript-eslint/no-unsafe-return */
@ -8,6 +10,7 @@
import { toUtf8 } from '@cosmjs/encoding'
import clsx from 'clsx'
import { Button } from 'components/Button'
import type { WhitelistType } from 'components/collections/creation/WhitelistDetails'
import { Conditional } from 'components/Conditional'
import { ContractPageHeader } from 'components/ContractPageHeader'
import { FormControl } from 'components/FormControl'
@ -19,12 +22,18 @@ import { whitelistLinkTabs } from 'components/LinkTabs.data'
import { useContracts } from 'contexts/contracts'
import type { QueryType } from 'contracts/whitelist/messages/query'
import { dispatchQuery, QUERY_LIST } from 'contracts/whitelist/messages/query'
import type { WhitelistMerkleTreeQueryType } from 'contracts/whitelistMerkleTree/messages/query'
import {
dispatchQuery as disptachWhitelistMerkleTreeQuery,
WHITELIST_MERKLE_TREE_QUERY_LIST,
} from 'contracts/whitelistMerkleTree/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 { WHITELIST_MERKLE_TREE_API_URL } from 'utils/constants'
import { useDebounce } from 'utils/debounce'
import { withMetadata } from 'utils/layout'
import { links } from 'utils/links'
@ -33,8 +42,11 @@ import { useWallet } from 'utils/wallet'
const WhitelistQueryPage: NextPage = () => {
const { whitelist: contract } = useContracts()
const { whitelistMerkleTree: contractWhitelistMerkleTree } = useContracts()
const wallet = useWallet()
const [exporting, setExporting] = useState(false)
const [whitelistType, setWhitelistType] = useState<WhitelistType>('standard')
const [proofHashes, setProofHashes] = useState<string[]>([])
const contractState = useInputState({
id: 'contract-address',
@ -44,6 +56,46 @@ const WhitelistQueryPage: NextPage = () => {
})
const contractAddress = contractState.value
const debouncedWhitelistContractState = useDebounce(contractAddress, 300)
useEffect(() => {
async function getWhitelistContractType() {
if (debouncedWhitelistContractState.length > 0) {
const client = await wallet.getCosmWasmClient()
const data = await toast.promise(
client.queryContractRaw(
debouncedWhitelistContractState,
toUtf8(Buffer.from(Buffer.from('contract_info').toString('hex'), 'hex').toString()),
),
{
loading: 'Retrieving whitelist type...',
error: 'Whitelist type retrieval failed.',
success: 'Whitelist type retrieved.',
},
)
const whitelistContract: string = JSON.parse(new TextDecoder().decode(data as Uint8Array)).contract
console.log(contract)
return whitelistContract
}
}
void getWhitelistContractType()
.then((whitelistContract) => {
if (whitelistContract?.includes('merkletree')) {
setWhitelistType('merkletree')
} else if (whitelistContract?.includes('flex')) {
setWhitelistType('flex')
} else {
setWhitelistType('standard')
}
})
.catch((err) => {
console.log(err)
setWhitelistType('standard')
console.log('Unable to retrieve contract type. Defaulting to "standard".')
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedWhitelistContractState, wallet.isWalletConnected])
const addressState = useInputState({
id: 'address',
name: 'address',
@ -52,6 +104,47 @@ const WhitelistQueryPage: NextPage = () => {
})
const address = addressState.value
const debouncedAddress = useDebounce(address, 300)
const fetchProofHashes = async (whitelistContractAddress: string, memberAddress: string): Promise<string[]> => {
if (whitelistContractAddress.length === 0 || memberAddress.length === 0)
throw new Error('Contract or member address is empty.')
const resolvedAddress = await resolveAddress(memberAddress, wallet)
const merkleRootResponse = await (
await wallet.getCosmWasmClient()
).queryContractSmart(contractAddress, { merkle_root: {} })
const proofs = await toast.promise(
fetch(`${WHITELIST_MERKLE_TREE_API_URL}/whitelist/${merkleRootResponse.merkle_root}/${resolvedAddress}`)
.then((res) => res.json())
.then((data) => data.proofs)
.catch((e) => {
console.log(e)
setProofHashes([])
}),
{
loading: 'Fetching proof hashes...',
error: 'Error fetching proof hashes from Whitelist Merkle Tree API.',
success: 'Proof hashes fetched.',
},
)
return proofs as string[] | []
}
useEffect(() => {
if (
whitelistType === 'merkletree' &&
whitelistMerkleTreeQueryType === 'has_member' &&
debouncedAddress.length > 0
) {
void fetchProofHashes(contractAddress, debouncedAddress)
.then((proofs) => setProofHashes(proofs))
.catch((e) => {
console.log(e)
setProofHashes([])
})
}
}, [debouncedAddress])
const limit = useNumberInputState({
id: 'limit',
name: 'limit',
@ -80,22 +173,59 @@ const WhitelistQueryPage: NextPage = () => {
}, [debouncedLimit])
const [type, setType] = useState<QueryType>('config')
const [whitelistMerkleTreeQueryType, setWhitelistMerkleTreeQueryType] =
useState<WhitelistMerkleTreeQueryType>('config')
const addressVisible = type === 'has_member'
const addressVisible = type === 'has_member' || whitelistMerkleTreeQueryType === 'has_member'
const { data: response } = useQuery(
[contractAddress, type, contract, wallet.address, address, startAfter.value, limit.value] as const,
[
contractAddress,
type,
whitelistMerkleTreeQueryType,
contract,
contractWhitelistMerkleTree,
wallet.address,
address,
startAfter.value,
limit.value,
proofHashes,
whitelistType,
] as const,
async ({ queryKey }) => {
const [_contractAddress, _type, _contract, _wallet, _address, _startAfter, _limit] = queryKey
const [
_contractAddress,
_type,
_whitelistMerkleTreeQueryType,
_contract,
_contractWhitelistMerkleTree,
_wallet,
_address,
_startAfter,
_limit,
_proofHashes,
_whitelistType,
] = queryKey
const messages = contract?.use(contractAddress)
const whitelistMerkleTreeMessages = contractWhitelistMerkleTree?.use(contractAddress)
const res = await resolveAddress(_address, wallet).then(async (resolvedAddress) => {
const result = await dispatchQuery({
messages,
type,
address: resolvedAddress,
startAfter: _startAfter || undefined,
limit: _limit,
})
const result =
whitelistType === 'merkletree'
? await disptachWhitelistMerkleTreeQuery({
messages: whitelistMerkleTreeMessages,
address: resolvedAddress,
type: whitelistMerkleTreeQueryType,
limit: _limit,
proofHashes: _proofHashes,
})
: await dispatchQuery({
messages,
type,
address: resolvedAddress,
startAfter: _startAfter || undefined,
limit: _limit,
})
return result
})
return res
@ -105,7 +235,7 @@ const WhitelistQueryPage: NextPage = () => {
onError: (error: any) => {
toast.error(error.message, { style: { maxWidth: 'none' } })
},
enabled: Boolean(contractAddress && contract),
enabled: Boolean(contractAddress && (contract || contractWhitelistMerkleTree)),
},
)
@ -230,9 +360,13 @@ const WhitelistQueryPage: NextPage = () => {
defaultValue="config"
id="contract-query-type"
name="query-type"
onChange={(e) => setType(e.target.value as QueryType)}
onChange={(e) =>
whitelistType === 'merkletree'
? setWhitelistMerkleTreeQueryType(e.target.value as WhitelistMerkleTreeQueryType)
: setType(e.target.value as QueryType)
}
>
{QUERY_LIST.map(({ id, name }) => (
{(whitelistType === 'merkletree' ? WHITELIST_MERKLE_TREE_QUERY_LIST : QUERY_LIST).map(({ id, name }) => (
<option key={`query-${id}`} className="mt-2 text-lg bg-[#1A1A1A]" value={id}>
{name}
</option>
@ -255,7 +389,16 @@ const WhitelistQueryPage: NextPage = () => {
</Button>
</Conditional>
</div>
<JsonPreview content={contractAddress ? { type, response } : null} title="Query Response" />
<JsonPreview
content={
contractAddress
? whitelistType === 'merkletree'
? { type: whitelistMerkleTreeQueryType, response }
: { type, response }
: null
}
title="Query Response"
/>
</div>
</section>
)