Skip to content

Commit

Permalink
feat: add a few new features
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinfaveri committed Sep 20, 2021
1 parent 76e9935 commit 511bb80
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 12 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@solana/wallet-adapter-react-ui": "^0.2.0",
"@solana/wallet-adapter-wallets": "^0.8.0",
"@solana/web3.js": "^1.26.0",
"axios": "^0.21.4",
"next": "11.1.2",
"patch-package": "^6.4.7",
"postinstall-postinstall": "^2.1.0",
Expand Down
34 changes: 30 additions & 4 deletions src/hooks/use-candy-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,13 @@ export default function useCandyMachine() {
const [, setBalance] = useWalletBalance()
const [candyMachine, setCandyMachine] = useState<CandyMachine>();
const wallet = useWallet();
const [isMinting, setIsMinting] = useState(false); // true when user got to press MINT
const [isSoldOut, setIsSoldOut] = useState(false); // true when items remaining is zero
const [nftsData, setNftsData] = useState<any>({} = {
itemsRemaining: 0,
itemsRedeemed: 0,
itemsAvailable: 0
} as any);
const [isMinting, setIsMinting] = useState(false);
const [isSoldOut, setIsSoldOut] = useState(false);
const [mintStartDate, setMintStartDate] = useState(new Date(parseInt(process.env.NEXT_PUBLIC_CANDY_START_DATE!, 10)));

useEffect(() => {
Expand Down Expand Up @@ -61,6 +66,27 @@ export default function useCandyMachine() {
})();
}, [wallet, candyMachineId, connection]);

useEffect(() => {
(async () => {
if (!isMinting) {
const anchorWallet = {
publicKey: wallet.publicKey,
signAllTransactions: wallet.signAllTransactions,
signTransaction: wallet.signTransaction,
} as anchor.Wallet;

const { itemsRemaining, itemsRedeemed, itemsAvailable } =
await getCandyMachineState(
anchorWallet,
candyMachineId,
connection
);

setNftsData({ itemsRemaining, itemsRedeemed, itemsAvailable });
}
})();
}, [wallet, candyMachineId, connection, isMinting]);

const onMint = async () => {
try {
setIsMinting(true);
Expand All @@ -81,7 +107,7 @@ export default function useCandyMachine() {
);

if (!status?.err) {
toast.success("Congratulations! Mint succeeded!")
toast.success("Congratulations! Mint succeeded! Check on your wallet :)")
} else {
toast.error("Mint failed! Please try again!")
}
Expand Down Expand Up @@ -114,5 +140,5 @@ export default function useCandyMachine() {
};


return { isSoldOut, mintStartDate, isMinting, onMint }
return { isSoldOut, mintStartDate, isMinting, nftsData, onMint }
}
9 changes: 6 additions & 3 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const Home = () => {
const [isActive, setIsActive] = useState(false); // true when countdown completes
const wallet = useWallet();

const { isSoldOut, mintStartDate, isMinting, onMint } = useCandyMachine()
const { isSoldOut, mintStartDate, isMinting, onMint, nftsData } = useCandyMachine()

return (
<main className="p-5">
Expand All @@ -34,7 +34,10 @@ const Home = () => {
}

{wallet.connected &&
<p>Balance: {(balance || 0).toLocaleString()} SOL</p>
<>
<p>Balance: {(balance || 0).toLocaleString()} SOL</p>
<p>Available/Minted/Total: {nftsData.itemsRemaining}/{nftsData.itemsRedeemed}/{nftsData.itemsAvailable}</p>
</>
}

<div>
Expand All @@ -60,7 +63,7 @@ const Home = () => {

<div className="flex float-right space-x-5">
<WalletMultiButton />
<WalletDisconnectButton />
<WalletDisconnectButton />
</div>
</main>
);
Expand Down
38 changes: 34 additions & 4 deletions src/utils/candy-machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import {
TOKEN_PROGRAM_ID,
Token,
} from "@solana/spl-token";
import { LAMPORTS_PER_SOL } from "@solana/web3.js";
import { Metadata } from '../libs/metaplex/index.esm';
import axios from "axios";

export const CANDY_MACHINE_PROGRAM = new anchor.web3.PublicKey(
"cndyAnrLdpjq1Ssp1z8xxDsB8dxe7u4HL5Nxi2K5WXZ"
);
Expand Down Expand Up @@ -117,11 +119,11 @@ export const awaitTransactionSignatureConfirmation = async (
connection.removeSignatureListener(subId);
}
done = true;
console.log("Returning status", status);
console.log("Returning status ", status);
return status;
}

/* export */ const createAssociatedTokenAccountInstruction = (
const createAssociatedTokenAccountInstruction = (
associatedTokenAddress: anchor.web3.PublicKey,
payer: anchor.web3.PublicKey,
walletAddress: anchor.web3.PublicKey,
Expand Down Expand Up @@ -231,6 +233,35 @@ const getTokenWallet = async (
)[0];
};

export async function getNftsForOwner(connection: anchor.web3.Connection, ownerAddress: anchor.web3.PublicKey) {
const allTokens = []
const tokenAccounts = await connection.getParsedTokenAccountsByOwner(ownerAddress, {
programId: TOKEN_PROGRAM_ID
});

for (let index = 0; index < tokenAccounts.value.length; index++) {
const tokenAccount = tokenAccounts.value[index];
const tokenAmount = tokenAccount.account.data.parsed.info.tokenAmount;

if (tokenAmount.amount == "1" && tokenAmount.decimals == "0") {

let [pda] = await anchor.web3.PublicKey.findProgramAddress([
Buffer.from("metadata"),
TOKEN_METADATA_PROGRAM_ID.toBuffer(),
(new anchor.web3.PublicKey(tokenAccount.account.data.parsed.info.mint)).toBuffer(),
], TOKEN_METADATA_PROGRAM_ID);
const accountInfo = await connection.getParsedAccountInfo(pda);

const metadata: any = new Metadata(ownerAddress.toString(), accountInfo.value);

const { data } = await axios.get(metadata.data.data.uri)
allTokens.push(data)
}
}

return allTokens
}

export const mintOneToken = async (
candyMachine: CandyMachine,
config: anchor.web3.PublicKey,
Expand All @@ -242,7 +273,6 @@ export const mintOneToken = async (
const { connection, program } = candyMachine;
const metadata = await getMetadata(mint.publicKey);
const masterEdition = await getMasterEdition(mint.publicKey);

const rent = await connection.getMinimumBalanceForRentExemption(
MintLayout.span
);
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,7 @@ axios@^0.18.0:
follow-redirects "1.5.10"
is-buffer "^2.0.2"

axios@^0.21.0:
axios@^0.21.0, axios@^0.21.4:
version "0.21.4"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.4.tgz#c67b90dc0568e5c1cf2b0b858c43ba28e2eda575"
integrity sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==
Expand Down

0 comments on commit 511bb80

Please sign in to comment.