Skip to content

Commit

Permalink
fix: metadata fixes for packs (metaplex-foundation#1224)
Browse files Browse the repository at this point in the history
* fix: metadata fixes for packs

* Fix preview images are broken on pack creation page
* Extract metadata loading from update method in meta.tsx. Use separate useEffect to fetch metadata on token accounts or route page change.

* fix: back btn
  • Loading branch information
zaxozhu authored Dec 15, 2021
1 parent c1f968f commit 3aa4158
Show file tree
Hide file tree
Showing 12 changed files with 102 additions and 145 deletions.
102 changes: 35 additions & 67 deletions js/packages/common/src/contexts/meta/meta.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import React, { useCallback, useContext, useEffect, useState } from 'react';
import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react';
import { useWallet } from '@solana/wallet-adapter-react';

import { queryExtendedMetadata } from './queryExtendedMetadata';
Expand Down Expand Up @@ -26,6 +32,7 @@ import { StringPublicKey, TokenAccount, useUserAccounts } from '../..';
const MetaContext = React.createContext<MetaContextState>({
...getEmptyMetaState(),
isLoading: false,
isLoadingMetadata: false,
// @ts-ignore
update: () => [AuctionData, BidderMetadata, BidderPot],
});
Expand All @@ -37,12 +44,14 @@ export function MetaProvider({ children = null as any }) {

const [state, setState] = useState<MetaState>(getEmptyMetaState());
const [page, setPage] = useState(0);
const [metadataLoaded, setMetadataLoaded] = useState(false);
const [lastLength, setLastLength] = useState(0);
const { userAccounts } = useUserAccounts();

const [isLoading, setIsLoading] = useState(true);

const [isLoadingMetadata, setIsLoadingMetadata] = useState(false);
const loadedMetadataLength = useRef(0);

const updateMints = useCallback(
async metadataByMint => {
try {
Expand Down Expand Up @@ -173,6 +182,9 @@ export function MetaProvider({ children = null as any }) {
userTokenAccounts: TokenAccount[],
tempState?: MetaState,
): Promise<void> {
setIsLoadingMetadata(true);
loadedMetadataLength.current = userTokenAccounts.length;

const nextState = await pullYourMetadata(
connection,
userTokenAccounts,
Expand All @@ -181,6 +193,7 @@ export function MetaProvider({ children = null as any }) {
await updateMints(nextState.metadataByMint);

setState(nextState);
setIsLoadingMetadata(false);
}

async function pullAllSiteData() {
Expand All @@ -204,11 +217,7 @@ export function MetaProvider({ children = null as any }) {
return;
}

async function update(
auctionAddress?: any,
bidderAddress?: any,
userTokenAccounts?: TokenAccount[],
) {
async function update(auctionAddress?: any, bidderAddress?: any) {
if (!storeAddress) {
if (isReady) {
//@ts-ignore
Expand Down Expand Up @@ -246,27 +255,6 @@ export function MetaProvider({ children = null as any }) {
} else {
console.log('------->Pagination detected, pulling page', page);

// Ensures we get the latest so beat race conditions and avoid double pulls.
let currMetadataLoaded = false;
setMetadataLoaded(loaded => {
currMetadataLoaded = loaded;
return loaded;
});
if (
userTokenAccounts &&
userTokenAccounts.length &&
!currMetadataLoaded
) {
console.log('--------->User metadata loading now.');

setMetadataLoaded(true);
nextState = await pullYourMetadata(
connection,
userTokenAccounts,
nextState,
);
}

const auction = window.location.href.match(/#\/auction\/(\w+)/);
const billing = window.location.href.match(
/#\/auction\/(\w+)\/billing/,
Expand Down Expand Up @@ -320,8 +308,6 @@ export function MetaProvider({ children = null as any }) {

console.log('------->set finished');

await updateMints(nextState.metadataByMint);

if (auctionAddress && bidderAddress) {
nextState = await pullAuctionSubaccounts(
connection,
Expand Down Expand Up @@ -349,52 +335,33 @@ export function MetaProvider({ children = null as any }) {
console.log('not running queued update right now, still loading');
} else {
console.log('running queued update');
update(undefined, undefined, userAccounts);
update(undefined, undefined);
clearInterval(interval);
}
}, 3000);
} else {
console.log('no update is running, updating.');
update(undefined, undefined, userAccounts);
update(undefined, undefined);
}
}, [connection, setState, updateMints, storeAddress, isReady, page]);

// Fetch metadata on userAccounts change
useEffect(() => {
const shouldFetch =
!isLoading &&
!isLoadingMetadata &&
loadedMetadataLength.current !== userAccounts.length;

if (shouldFetch) {
pullUserMetadata(userAccounts);
}
}, [
connection,
setState,
updateMints,
storeAddress,
isReady,
page,
userAccounts.length > 0,
isLoading,
isLoadingMetadata,
loadedMetadataLength.current,
userAccounts.length,
]);

// TODO: fetch names dynamically
// TODO: get names for creators
// useEffect(() => {
// (async () => {
// const twitterHandles = await connection.getProgramAccounts(NAME_PROGRAM_ID, {
// filters: [
// {
// dataSize: TWITTER_ACCOUNT_LENGTH,
// },
// {
// memcmp: {
// offset: VERIFICATION_AUTHORITY_OFFSET,
// bytes: TWITTER_VERIFICATION_AUTHORITY.toBase58()
// }
// }
// ]
// });

// const handles = twitterHandles.map(t => {
// const owner = new PublicKey(t.account.data.slice(32, 64));
// const name = t.account.data.slice(96, 114).toString();
// });

// console.log(handles);

// })();
// }, [whitelistedCreatorsByCreator]);

return (
<MetaContext.Provider
value={{
Expand All @@ -410,6 +377,7 @@ export function MetaProvider({ children = null as any }) {
pullPackPage,
pullUserMetadata,
isLoading,
isLoadingMetadata,
}}
>
{children}
Expand Down
1 change: 1 addition & 0 deletions js/packages/common/src/contexts/meta/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export interface MetaState {

export interface MetaContextState extends MetaState {
isLoading: boolean;
isLoadingMetadata: boolean;
update: (
auctionAddress?: any,
bidderAddress?: any,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const ArtCard = ({ index, isModalOpened }: ArtCardProps) => {

const isOpenedCard = index < cardsRedeemed;
const metadata = openedMetadata[index];
const pubkey = (isOpenedCard && metadata?.metadata.pubkey) || '';
const pubkey = metadata?.metadata.pubkey || '';

const { ref, data } = useExtendedArt(pubkey);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const RedeemModal = ({
)}
{modalState === openState.TransactionApproval && (
<TransactionApprovalStep
goBack={() => setModalState(openState.Claiming)}
goBack={() => setModalState(openState.Initial)}
/>
)}
{shouldEnableRedeem && (
Expand Down
5 changes: 1 addition & 4 deletions js/packages/web/src/views/pack/contexts/PackContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from '@oyster/common';
import { ProvingProcess } from '@oyster/common/dist/lib/models/packs/accounts/ProvingProcess';
import { useWallet } from '@solana/wallet-adapter-react';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { useParams, useLocation } from 'react-router';

import { claimPackCards } from '../transactions/claimPackCards';
Expand All @@ -21,7 +21,6 @@ import { useOpenedMetadata } from './hooks/useOpenedMetadata';
import { PackContextProps } from './interface';
import { useListenForProvingProcess } from './hooks/useListenForProvingProcess';
import { fetchProvingProcessWithRetry } from './utils/fetchProvingProcessWithRetry';
import { useListenForTokenAccounts } from './hooks/useListenForTokenAccounts';

export const PackContext = React.createContext<PackContextProps>({
isLoading: false,
Expand All @@ -40,8 +39,6 @@ export const PackProvider: React.FC = ({ children }) => {
const { search } = useLocation();
const { voucherMint, provingProcessKey } = getSearchParams(search);

useListenForTokenAccounts();

const {
packs,
packCards,
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { memo, ReactElement } from 'react';
import classNames from 'classnames';

import { ArtContent } from '../../../../components/ArtContent';
import { useExtendedArt } from '../../../../hooks';

import { ItemRowProps } from './interface';

const ItemRow = ({
Expand All @@ -13,7 +15,9 @@ const ItemRow = ({
}: ItemRowProps): ReactElement => {
const { metadata, masterEdition } = item;
const { pubkey } = metadata;
const { name, uri } = metadata?.info?.data;
const { name } = metadata?.info?.data;

const { ref, data } = useExtendedArt(pubkey);

const maximumSupply: string =
masterEdition?.info.maxSupply?.toString() || 'Unlimited';
Expand All @@ -25,10 +29,10 @@ const ItemRow = ({
});

return (
<div className={itemRowCls} onClick={onClick}>
<div className={itemRowCls} onClick={onClick} ref={ref}>
{children}
<div className="preview-column">
<ArtContent pubkey={pubkey} uri={uri} preview={false} />
<ArtContent uri={data?.image} preview={false} />
</div>
<div className="name-column">
<p className="name-column__name">{name}</p>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { ReactElement } from 'react';

import SmallLoader from '../../../../components/SmallLoader';
import ItemRow from '../ItemRow';

import { SelectItemsStepProps } from './interface';
Expand All @@ -11,9 +12,14 @@ const SelectItemsStep = ({
items,
showSupply,
emptyMessage,
isLoading,
}: SelectItemsStepProps): ReactElement => {
const shouldShowEmptyMessage = !items?.length && emptyMessage;

if (isLoading) {
return <SmallLoader />;
}

return (
<div>
{items.map(item => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export interface SelectItemsStepProps {
selectedItems: Record<string, SafetyDepositDraft>;
showSupply?: boolean;
emptyMessage?: string;
isLoading?: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,20 @@ import { SidebarProps } from './interface';

const { Step } = Steps;

const Sidebar = ({ step, setStep, submit, isValidStep, buttonLoading }: SidebarProps) => {
const Sidebar = ({
step,
setStep,
submit,
isValidStep,
buttonLoading,
}: SidebarProps) => {
const { connected } = useWallet();
const { isLoading } = useMeta();
const { width } = useWindowDimensions();

const isFinalStep = step === CreatePackSteps.ReviewAndMint;
const shouldDisable = !isValidStep || !connected || isLoading;
const shouldDisable =
!isValidStep || !connected || isLoading || buttonLoading;

const handleContinue = (): void => {
if (isFinalStep) {
Expand Down
7 changes: 6 additions & 1 deletion js/packages/web/src/views/packCreate/index.less
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@
.content-wrapper {
flex: 1;
padding: 0 48px;

.small-loader {
text-align: center;
}
}
}

.notification-container {
background-color: @grey-70;
border-radius: 16px;
div, a {
div,
a {
color: @grey-30;
}
}
Expand Down
Loading

0 comments on commit 3aa4158

Please sign in to comment.