Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate markets from nftobject #155

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion @filter/CollectionsFilterList.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SearchableEntity } from 'types/zora.api.generated'

import { useState } from 'react'

import { SearchableEntity } from '@zoralabs/zdk/dist/queries/queries-sdk'
import { Accordion, InputField, Stack } from '@zoralabs/zord'

import { FilterCollectionListItem } from './FilterCollectionListItem'
Expand Down
1 change: 1 addition & 0 deletions @filter/FilterProperties.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function FilterProperties({ collectionAddress }: { collectionAddress: str
{filterPropertiesList.map((property: AggregateAttribute) => (
<Box key={property.traitType} className={['filter-properties-list']}>
<FilterPropertySelect
__typename={property.__typename}
traitType={property.traitType || ''}
valueMetrics={property.valueMetrics}
/>
Expand Down
1 change: 0 additions & 1 deletion @filter/FilterPropertySelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export function FilterPropertySelect({ traitType, valueMetrics }: AggregateAttri
<Select
name="filter-property"
id="filter-property"
value={isReset ? '' : undefined}
w="100%"
color="text1"
textAlign="right"
Expand Down
2 changes: 1 addition & 1 deletion @filter/hooks/useSearchQuery.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import useSWR from 'swr'
import { SearchResult, SearchableEntity } from 'types/zora.api.generated'

import { zdk } from '@shared'
import { SearchResult, SearchableEntity } from '@zoralabs/zdk/dist/queries/queries-sdk'

export function useSearchQuery(query: string, entityType: SearchableEntity) {
const { data, ...rest } = useSWR(
Expand Down
104 changes: 64 additions & 40 deletions @filter/hooks/useTokensQuery.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,70 @@
import useSWRInfinite from 'swr/infinite'
import {
FilteredTokensQuery,
NetworkInput,
PaginationInput,
TokenSortInput,
TokenWithMarketsSummary,
TokensQueryFilter,
TokensQueryInput,
} from 'types/zora.api.generated'

import { FILTERED_TOKENS } from 'data/filteredTokens'

import { useCallback, useMemo } from 'react'
import { useCallback } from 'react'

import { flatten } from 'lodash'

import { getAddress } from '@ethersproject/address'
import { GetNFTReturnType } from '@shared'
import { zdk } from '@shared/utils/zdk'
import { transformNFTZDK } from '@zoralabs/nft-hooks/dist/backends'
import { prepareJson } from '@zoralabs/nft-hooks/dist/fetcher/NextUtils'
import { NFTObject } from '@zoralabs/nft-hooks/dist/types/NFTInterface'
import { TokensQueryArgs } from '@zoralabs/zdk'
import {
TokenSortInput,
TokensQueryFilter,
TokensQueryInput,
} from '@zoralabs/zdk/dist/queries/queries-sdk'
import { zoraApiFetcher } from '@shared'

const PAGE_SIZE = 12 // must be divisible by 2,3,4 to ensure grid stays intact

export interface UseTokenQueryProps {
contractAllowList?: string[] | undefined
contractAddress?: string | null
ownerAddress?: string
initialData?: GetNFTReturnType
initialData?: PaginatedFilteredTokensQueryResponse
sort?: TokenSortInput
filter?: TokensQueryFilter
where?: TokensQueryInput
initialPageSize?: number
refreshInterval?: number
}

async function getNFTs(query: TokensQueryArgs): Promise<GetNFTReturnType> {
const resp = await zdk.tokens(query)
const tokens = resp.tokens.nodes
/* @ts-ignore */
.map((token) => transformNFTZDK(token, { rawData: token }))
.map(prepareJson)
// async function _getNFTs(query: TokensQueryArgs): Promise<GetNFTReturnType> {
// const resp = await zdk.tokens(query)
// const tokens = resp.tokens.nodes
// /* @ts-ignore */
// .map((token) => transformNFTZDK(token, { rawData: token }))
// .map(prepareJson)
// return {
// tokens,
// nextCursor: resp.tokens.pageInfo.endCursor,
// }
// }

export type PaginatedFilteredTokensQueryResponse = {
tokens: TokenWithMarketsSummary[]
nextCursor?: string | null
}

type FilteredTokensQueryParams = {
where?: TokensQueryInput
sort?: TokenSortInput
filter?: TokensQueryFilter
pagination?: PaginationInput
networks: NetworkInput[]
}

async function getNFTs(
query: FilteredTokensQueryParams
): Promise<PaginatedFilteredTokensQueryResponse> {
const res = await zoraApiFetcher<FilteredTokensQuery>(FILTERED_TOKENS, query)

return {
tokens,
nextCursor: resp.tokens.pageInfo.endCursor,
tokens: res.tokens.nodes,
nextCursor: res.tokens.pageInfo.endCursor, // @bj wanna discuss it
}
}

Expand All @@ -53,8 +78,11 @@ export function useTokensQuery({
initialData,
refreshInterval = 30000,
}: UseTokenQueryProps) {
const getKey = (pageIndex: number, previousPageData: GetNFTReturnType) => {
if (pageIndex > 0 && !previousPageData.nextCursor) return null // reached the end
const getKey = (
pageIndex: number,
previousPageData: PaginatedFilteredTokensQueryResponse | null
) => {
if (pageIndex > 0 && !previousPageData?.nextCursor) return null // reached the end
return {
where: {
...(contractAddress && {
Expand All @@ -74,35 +102,31 @@ export function useTokensQuery({
after: previousPageData?.nextCursor,
limit: PAGE_SIZE,
},
includeFullDetails: true,
}
}

const {
data: resp,
error,
setSize,
size,
isValidating,
} = useSWRInfinite<GetNFTReturnType>(getKey, getNFTs, {
fallbackData: initialData && [initialData],
refreshInterval: refreshInterval,
})
const { data, error, setSize, size, isValidating } =
useSWRInfinite<PaginatedFilteredTokensQueryResponse>(getKey, getNFTs, {
fallbackData: initialData && [initialData],
refreshInterval: refreshInterval,
})

const data = useMemo(() => resp?.map((r) => r.tokens), [resp])
const flattenedData = useMemo(() => flatten(data), [data])
if (error) {
console.error(error)
}

const handleLoadMore = useCallback(() => setSize(size + 1), [setSize, size])

const isLoadingInitialData = !data && !error
const isLoadingMore =
isLoadingInitialData || (size > 0 && data && typeof data[size - 1] === 'undefined')
const isEmpty = data?.[0]?.length === 0
const isReachingEnd = isEmpty || (data && data[data.length - 1]?.length < PAGE_SIZE)
const isEmpty = data?.length === 0
const isReachingEnd = isEmpty || (data && [data.length - 1]?.length < PAGE_SIZE)
const isRefreshing = isValidating && data && data.length === size

console.log({ data, f: flatten(data) })

return {
data: flattenedData,
data: flatten(data),
isValidating,
isRefreshing,
isLoadingMore,
Expand Down
43 changes: 28 additions & 15 deletions @filter/providers/CollectionFilterProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { createContext, useContext, useMemo } from 'react'
import { TokenWithMarketsSummary } from 'types/zora.api.generated'

import { ReactNode, createContext, useContext, useMemo } from 'react'

import {
attributesToFilterParams,
Expand All @@ -7,11 +9,15 @@ import {
sortMethodToSortParams,
} from '@filter'
import { stringDefaults, themeDefaults } from '@filter/constants'
import { useTokensQuery } from '@filter/hooks/useTokensQuery'
import {
PaginatedFilteredTokensQueryResponse,
useTokensQuery,
} from '@filter/hooks/useTokensQuery'
import { initialFilterStore, useFilterStore } from '@filter/state/filterStore'
import {
CollectionFilterContextTypes,
CollectionFilterProviderProps,
FilterContextInputProps,
} from '@filter/typings'
import { MARKET_INFO_STATUSES } from '@zoralabs/nft-hooks/dist/types/NFTInterface'

Expand Down Expand Up @@ -66,7 +72,10 @@ export function CollectionFilterProvider({
useFilterOwnerCollections = false,
strings = stringDefaults,
theme = themeDefaults,
}: CollectionFilterProviderProps) {
}: {
children?: ReactNode
initialPage?: PaginatedFilteredTokensQueryResponse
} & FilterContextInputProps) {
const filterStore = useFilterStore(filtersVisible)
const { filters } = filterStore
const {
Expand All @@ -79,8 +88,7 @@ export function CollectionFilterProvider({
contractAllowList,
contractAddress,
ownerAddress,
// initialData: initialPage && { tokens: initialPage },
initialData: initialPage && initialPage,
initialData: initialPage,
refreshInterval: 60000,
sort: sortMethodToSortParams(filters.sortMethod, filters.marketStatus),
filter: {
Expand All @@ -91,15 +99,20 @@ export function CollectionFilterProvider({
},
})

const tokensWithActiveMarkets = useMemo(
() =>
items.filter((token) =>
token.markets?.map((mkt) =>
[MARKET_INFO_STATUSES.ACTIVE, MARKET_INFO_STATUSES.PENDING].includes(mkt.status)
)
),
[items]
)
console.log({ AAAA: items })

const tokensWithActiveMarkets = useMemo(() => {
if (items.length === 0) return []

return items[0].tokens.filter((token) =>
token.marketsSummary?.map((mkt) =>
[
MARKET_INFO_STATUSES.ACTIVE.toString(),
MARKET_INFO_STATUSES.PENDING.toString(),
].includes(mkt.status)
)
)
}, [items])

// - Allows us to adjust the options available to users when sorting (eg. no sorting by price when there are no prices!)
const tokensHaveActiveMarkets = useMemo(
Expand All @@ -111,7 +124,7 @@ export function CollectionFilterProvider({
<CollectionFilterContext.Provider
value={{
filterStore,
items,
items: items.length > 0 ? items[0].tokens : ([] as TokenWithMarketsSummary[]),
isValidating,
isReachingEnd,
isEmpty,
Expand Down
3 changes: 2 additions & 1 deletion @filter/state/filterStore.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { MediaType } from 'types/zora.api.generated'

import { useCallback, useEffect, useMemo, useState } from 'react'

import {
Expand All @@ -12,7 +14,6 @@ import {
SortMethodType,
TokenContractsFilter,
} from '@filter/typings'
import { MediaType } from '@zoralabs/zdk/dist/queries/queries-sdk'

import { removeItemAtIndex } from '../utils/store'

Expand Down
6 changes: 4 additions & 2 deletions @filter/typings/filter-provider.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { TokenWithMarketsSummary } from 'types/zora.api.generated'

import { ReactNode } from 'react'

import { stringDefaults, themeDefaults } from '@filter/constants'
import { GetNFTReturnType } from '@shared'
import { NFTObject } from '@zoralabs/nft-hooks'

import { FilterStore } from './filter-store'

Expand Down Expand Up @@ -52,7 +53,7 @@ export interface FilterContextInputProps extends FilterConfigProps {
}

export interface TokenQueryReturnTypes extends FilterContextInputProps {
items: NFTObject[]
items: TokenWithMarketsSummary[]
isValidating: boolean
isReachingEnd: boolean | undefined
isEmpty: boolean
Expand All @@ -69,5 +70,6 @@ export interface CollectionFilterContextTypes extends TokenQueryReturnTypes {
export interface CollectionFilterProviderProps extends FilterContextInputProps {
children?: ReactNode
// initialPage?: NFTObject[]
// TODO remove
initialPage?: GetNFTReturnType
}
3 changes: 2 additions & 1 deletion @filter/typings/filter-store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MediaType } from 'types/zora.api.generated'

import { MouseEventHandler } from 'react'

import { Currency } from '@shared'
import { MediaType } from '@zoralabs/zdk/dist/queries/queries-sdk'

type Address = string

Expand Down
15 changes: 8 additions & 7 deletions @filter/utils/sortMethods.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
import {
CollectionAttributesFilter,
MarketStatusFilter,
PriceRangeFilter,
SortMethodType,
} from '@filter/typings'
import {
MarketCategory,
MarketStatus,
Expand All @@ -12,7 +6,14 @@ import {
TokenSortInput,
TokenSortKey,
TokensQueryFilter,
} from '@zoralabs/zdk/dist/queries/queries-sdk'
} from 'types/zora.api.generated'

import {
CollectionAttributesFilter,
MarketStatusFilter,
PriceRangeFilter,
SortMethodType,
} from '@filter/typings'

export function marketStatusToSortAxis(marketType: MarketStatusFilter) {
switch (marketType) {
Expand Down
19 changes: 11 additions & 8 deletions @market/components/MarketModalHeading.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
import React from 'react'

import { CollectionThumbnail } from '@media/CollectionThumbnail'
import { NFTObject } from '@zoralabs/nft-hooks'
import { Flex, Heading } from '@zoralabs/zord'

interface MarketModalHeadingProps {
nftObj: NFTObject
action?: string
tokenId: string
contractAddress: string
collectionName: string
}

export function MarketModalHeading({ nftObj, action }: MarketModalHeadingProps) {
const { nft } = nftObj
export function MarketModalHeading({
tokenId,
contractAddress,
collectionName,
action,
}: MarketModalHeadingProps) {
return (
<Flex w="100%" justify="space-between" textAlign="left" gap="x6">
<Heading as="h2" size="md">
{`${action} ${nftObj.nft?.contract.name} #${nft?.tokenId}`}
{`${action} ${collectionName} #${tokenId}`}
</Heading>
{/* @BJ TODO: This component causes 500 error when it hits the useNounsToken contract call? */}
{nft?.contract?.address && (
<CollectionThumbnail collectionAddress={nft?.contract.address} />
)}
{contractAddress && <CollectionThumbnail collectionAddress={contractAddress} />}
</Flex>
)
}
Loading