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

fix: bug with network switching #153

Merged
merged 1 commit into from
Jul 21, 2022
Merged
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
92 changes: 47 additions & 45 deletions hooks/useMintCandyMachine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,51 +24,53 @@ const useMintCandyMachine = (account: string) => {
const wallet = useWallet()

async function refreshCandyMachineState() {
if (!anchorWallet || !wallet.publicKey) return
const provider = new AnchorProvider(connection, anchorWallet, {
preflightCommitment: 'recent',
})

const idl = await Program.fetchIdl(CANDY_MACHINE_PROGRAM_V2_ID, provider)

const program = new Program(idl!, CANDY_MACHINE_PROGRAM_V2_ID, provider)
const state: any = await program.account.candyMachine.fetch(new PublicKey(account))

const itemsAvailable = state.data.itemsAvailable.toNumber()
const itemsRedeemed = state.itemsRedeemed.toNumber()
const itemsRemaining = itemsAvailable - itemsRedeemed
const captcha = !!state.data.gatekeeper
let nftPrice = new BN(state.data.price).toNumber() / LAMPORTS_PER_SOL
let active = new BN(state.goLiveDate).toNumber() < new Date().getTime() / 1000

setItemsRemaining(itemsRemaining)
setNftPrice(nftPrice)
setIsActive(active)
setIsCaptcha(captcha)

setCandyMachine({
id: new PublicKey(account),
program,
state: {
authority: state.authority,
itemsAvailable,
itemsRedeemed,
itemsRemaining,
isSoldOut: itemsRemaining === 0,
isActive: false,
isPresale: false,
isWhitelistOnly: false,
goLiveDate: state.data.goLiveDate,
treasury: state.wallet,
tokenMint: state.tokenMint,
gatekeeper: state.data.gatekeeper,
endSettings: state.data.endSettings,
whitelistMintSettings: state.data.whitelistMintSettings,
hiddenSettings: state.data.hiddenSettings,
price: state.data.price,
retainAuthority: state.data.retainAuthority,
},
})
try {
if (!anchorWallet || !wallet.publicKey) return
const provider = new AnchorProvider(connection, anchorWallet, {
preflightCommitment: 'recent',
})

const idl = await Program.fetchIdl(CANDY_MACHINE_PROGRAM_V2_ID, provider)

const program = new Program(idl!, CANDY_MACHINE_PROGRAM_V2_ID, provider)
const state: any = await program.account.candyMachine.fetch(new PublicKey(account))

const itemsAvailable = state.data.itemsAvailable.toNumber()
const itemsRedeemed = state.itemsRedeemed.toNumber()
const itemsRemaining = itemsAvailable - itemsRedeemed
const captcha = !!state.data.gatekeeper
let nftPrice = new BN(state.data.price).toNumber() / LAMPORTS_PER_SOL
let active = new BN(state.goLiveDate).toNumber() < new Date().getTime() / 1000

setItemsRemaining(itemsRemaining)
setNftPrice(nftPrice)
setIsActive(active)
setIsCaptcha(captcha)

setCandyMachine({
id: new PublicKey(account),
program,
state: {
authority: state.authority,
itemsAvailable,
itemsRedeemed,
itemsRemaining,
isSoldOut: itemsRemaining === 0,
isActive: false,
isPresale: false,
isWhitelistOnly: false,
goLiveDate: state.data.goLiveDate,
treasury: state.wallet,
tokenMint: state.tokenMint,
gatekeeper: state.data.gatekeeper,
endSettings: state.data.endSettings,
whitelistMintSettings: state.data.whitelistMintSettings,
hiddenSettings: state.data.hiddenSettings,
price: state.data.price,
retainAuthority: state.data.retainAuthority,
},
})
} catch (_) {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be better if this catch contained something?

}

const mintAccount = async (beforeTransactions: Transaction[] = [], afterTransactions: Transaction[] = []) => {
Expand Down
1 change: 0 additions & 1 deletion hooks/useRPC.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const RPC_API_DEVNET = process.env.NEXT_PUBLIC_RPC_API_DEVNET as string
const RPC_API_MAINNET = process.env.NEXT_PUBLIC_RPC_API_MAINNET as string

const useRPC = () => {
console.log(RPC_API_DEVNET, RPC_API_MAINNET)
const [network] = useRecoilState(networkState)
const connection = new Connection(RPC_API_MAINNET, 'finalized')
const [rpc, setRpc] = useState<Connection>(connection)
Expand Down
54 changes: 33 additions & 21 deletions pages/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AnchorProvider, BN, Program } from '@project-serum/anchor'
import { useAnchorWallet } from '@solana/wallet-adapter-react'
import { Connection, PublicKey } from '@solana/web3.js'
import { PublicKey } from '@solana/web3.js'
import {
Spinner,
Title,
Expand All @@ -13,7 +13,6 @@ import {
import { useRPC } from 'hooks'
import { CANDY_MACHINE_PROGRAM_V2_ID } from 'lib/candy-machine/constants'
import { IFetchedCandyMachineConfig } from 'lib/candy-machine/interfaces'
import { Account } from 'lib/candy-machine/types'
import { Nft } from 'lib/nft/interfaces'
import type { NextPage } from 'next'
import Head from 'next/head'
Expand All @@ -32,6 +31,7 @@ const CandyMachine: NextPage = () => {
const { connection } = useRPC()
const [candyMachineConfig, setCandyMachineConfig] = useState<IFetchedCandyMachineConfig>()
const [error, setError] = useState('')
const [initialLoad, setInitialLoad] = useState(false)
const [nfts, setNfts] = useState<Nft[]>([])
const [mintedNfts, setMintedNfts] = useState<Nft[]>([])
const [collectionNft, setCollectionNft] = useState<Nft>()
Expand Down Expand Up @@ -82,15 +82,12 @@ const CandyMachine: NextPage = () => {
setIsLoading(false)
}

async function fetchCandyMachine({
candyMachineAccount,
connection,
}: {
candyMachineAccount: Account
connection: Connection
}): Promise<IFetchedCandyMachineConfig | undefined> {
async function fetchCandyMachine(): Promise<IFetchedCandyMachineConfig | undefined> {
setError('')
if (candyMachineAccount && anchorWallet) {
try {
console.log(4, error)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing console.log


setIsLoading(true)
const provider = new AnchorProvider(connection, anchorWallet, {
preflightCommitment: 'processed',
Expand All @@ -104,13 +101,13 @@ const CandyMachine: NextPage = () => {

state.data.solTreasuryAccount = state.wallet
state.data.itemsRedeemed = state.itemsRedeemed
setInitialLoad(true)
setIsLoading(false)

return state.data
} catch (err) {
console.error(err)
initialLoad && setError((err as Error).message)
setIsLoading(false)
setError((err as Error).message)
}
}
}
Expand All @@ -131,12 +128,30 @@ const CandyMachine: NextPage = () => {
}

useEffect(() => {
refreshCandyMachineState()
getNfts()
fetchCandyMachine({ candyMachineAccount, connection }).then(setCandyMachineConfig)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [candyMachineAccount, connection, anchorWallet])
;(async function () {
setError('')
fetchCandyMachine().then(setCandyMachineConfig)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be a good idea to include .catch here?

await getNfts()
})()
if (initialLoad) {
setInitialLoad(false)
}
}, [connection])

if (!initialLoad && error.includes('Account does not exist')) {
return (
<>
<Head>
<title>Update Candy Machine</title>
<meta name='description' content='Generated by create next app' />
<link rel='icon' href='/favicon.ico' />
</Head>
<div className='d-flex flex-column flex-items-center flex-justify-center mt-11 f2'>
This is not a candy machine account.
</div>
</>
)
}
return (
<>
<Head>
Expand All @@ -160,11 +175,8 @@ const CandyMachine: NextPage = () => {
{isLoading && <Spinner />}
{error && (
<div className='d-flex flex-column items-center justify-center mt-11'>
Error fetching candy machine config
<button
className='rounded-lg bg-slate-400 p-2 mt-4'
onClick={() => fetchCandyMachine({ candyMachineAccount, connection: connection })}
>
{error}
<button className='rounded-lg bg-slate-400 p-2 mt-4' onClick={() => fetchCandyMachine()}>
Fetch again
</button>
</div>
Expand Down