MintNftButton.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import Image from "next/image"
  2. import { useCallback, useState } from "react"
  3. import { Button, HStack, VStack } from "@chakra-ui/react"
  4. import { useConnection, useWallet } from "@solana/wallet-adapter-react"
  5. import { useGameState } from "@/contexts/GameStateProvider"
  6. import { program } from "@/utils/anchor"
  7. import { Keypair, PublicKey, SystemProgram } from "@solana/web3.js"
  8. import { web3 } from "@coral-xyz/anchor"
  9. import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getAssociatedTokenAddressSync } from "@solana/spl-token";
  10. const MintNftButton = () => {
  11. const { publicKey, sendTransaction, wallet } = useWallet()
  12. const { connection } = useConnection()
  13. const { gameState, playerDataPDA } = useGameState()
  14. const [isLoadingMainWallet, showSpinner] = useState(false)
  15. const onMintNftClick = useCallback(async () => {
  16. if (!publicKey || !playerDataPDA) return
  17. showSpinner(true)
  18. try {
  19. const nftAuthority = await PublicKey.findProgramAddress(
  20. [Buffer.from("nft_authority")],
  21. program.programId
  22. );
  23. const mint = new Keypair();
  24. const destinationTokenAccount = getAssociatedTokenAddressSync(
  25. mint.publicKey,
  26. publicKey,
  27. false,
  28. TOKEN_2022_PROGRAM_ID,
  29. );
  30. const transaction = await program.methods
  31. .mintNft()
  32. .accounts({
  33. signer: publicKey,
  34. systemProgram: SystemProgram.programId,
  35. tokenProgram: TOKEN_2022_PROGRAM_ID,
  36. tokenAccount: destinationTokenAccount,
  37. mint: mint.publicKey,
  38. rent: web3.SYSVAR_RENT_PUBKEY,
  39. associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
  40. nftAuthority: nftAuthority[0],
  41. })
  42. .signers([mint])
  43. .transaction();
  44. console.log("transaction", transaction);
  45. const txSig = await sendTransaction(transaction, connection,{
  46. signers: [mint],
  47. skipPreflight: true
  48. } );
  49. console.log(`https://explorer.solana.com/tx/${txSig}?cluster=devnet`)
  50. } catch (error: any) {
  51. console.log("error", `Minting failed! ${error?.message} ${error?.stack}`)
  52. } finally {
  53. showSpinner(false)
  54. }
  55. }, [publicKey, playerDataPDA, connection])
  56. return (
  57. <>
  58. {publicKey && gameState && (
  59. <VStack>
  60. <Image src="/Beaver.png" alt="Energy Icon" width={64} height={64} />
  61. <HStack>
  62. <Button
  63. isLoading={isLoadingMainWallet}
  64. onClick={onMintNftClick}
  65. width="175px"
  66. >
  67. Mint Nft
  68. </Button>
  69. </HStack>
  70. </VStack>
  71. )}
  72. </>
  73. )
  74. }
  75. export default MintNftButton