Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6c7c5809b | ||
|
|
a829c8fde4 | ||
|
|
06ef584e1f | ||
|
|
febfcc924c | ||
|
|
90ff207cf5 | ||
|
|
d558dcf81d | ||
|
|
fcacb149c8 | ||
|
|
68f38544a4 | ||
|
|
1e5e21aff9 |
27
components/Confirmed.tsx
Normal file
27
components/Confirmed.tsx
Normal file
@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { buildStyles, CircularProgressbar } from "react-circular-progressbar"
|
||||
import 'react-circular-progressbar/dist/styles.css';
|
||||
|
||||
|
||||
export default function Confirmed() {
|
||||
const [percentage, setPercentage] = useState(0)
|
||||
const [text, setText] = useState('🍪')
|
||||
|
||||
useEffect(() => {
|
||||
const t1 = setTimeout(() => setPercentage(100), 100)
|
||||
const t2 = setTimeout(() => setText('✅'), 600)
|
||||
|
||||
return () => {
|
||||
clearTimeout(t1)
|
||||
clearTimeout(t2)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<CircularProgressbar value={percentage} text={text} styles={
|
||||
buildStyles({
|
||||
pathColor: '#00BA00',
|
||||
})
|
||||
} />
|
||||
)
|
||||
}
|
||||
54
components/CouponBook.tsx
Normal file
54
components/CouponBook.tsx
Normal file
@ -0,0 +1,54 @@
|
||||
import { getAssociatedTokenAddress, getAccount, TokenAccountNotFoundError } from "@solana/spl-token"
|
||||
import { useConnection, useWallet } from "@solana/wallet-adapter-react"
|
||||
import { useState, useEffect } from "react"
|
||||
import { couponAddress } from "../lib/addresses"
|
||||
|
||||
export default function CouponBook() {
|
||||
const { connection } = useConnection()
|
||||
const { publicKey } = useWallet()
|
||||
const [couponBalance, setCouponBalance] = useState(0)
|
||||
|
||||
|
||||
async function getCouponBalance() {
|
||||
if (!publicKey) {
|
||||
setCouponBalance(0)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const userCouponAddress = await getAssociatedTokenAddress(couponAddress, publicKey)
|
||||
const userCouponAccount = await getAccount(connection, userCouponAddress)
|
||||
const coupons = userCouponAccount.amount > 5 ? 5 : Number(userCouponAccount.amount)
|
||||
|
||||
console.log("balance is", coupons)
|
||||
setCouponBalance(coupons)
|
||||
} catch (e) {
|
||||
if (e instanceof TokenAccountNotFoundError) {
|
||||
// This is ok, the API will create one when they make a payment
|
||||
console.log(`User ${publicKey} doesn't have a coupon account yet!`)
|
||||
setCouponBalance(0)
|
||||
} else {
|
||||
console.error('Error getting coupon balance', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
getCouponBalance()
|
||||
}, [publicKey])
|
||||
|
||||
const notCollected = 5 - couponBalance
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-center p-1 text-white bg-gray-900 rounded-md">
|
||||
<p>Collect 5 cookies to receive a 50% discount on your next purchase!</p>
|
||||
|
||||
<p className="flex flex-row gap-1 place-self-center">
|
||||
{[...Array(couponBalance)].map((_, i) => <span key={i}>🍪</span>)}
|
||||
{[...Array(notCollected)].map((_, i) => <span key={i}>⚪</span>)}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@ -16,11 +16,11 @@ export default function Products({ submitTarget, enabled }: Props) {
|
||||
<div className="grid grid-cols-2 gap-8">
|
||||
{products.map(product => {
|
||||
return (
|
||||
<div className="rounded-md bg-white text-left p-8" key={product.id}>
|
||||
<div className="p-8 text-left bg-white rounded-md" key={product.id}>
|
||||
<h3 className="text-2xl font-bold">{product.name}</h3>
|
||||
<p className="text-sm text-gray-800">{product.description}</p>
|
||||
<p className="my-4">
|
||||
<span className="mt-4 text-xl font-bold">{product.priceSol} SOL</span>
|
||||
<span className="mt-4 text-xl font-bold">${product.priceUsd}</span>
|
||||
{product.unitName && <span className="text-sm text-gray-800"> /{product.unitName}</span>}
|
||||
</p>
|
||||
<div className="mt-1">
|
||||
@ -33,7 +33,7 @@ export default function Products({ submitTarget, enabled }: Props) {
|
||||
</div>
|
||||
|
||||
<button
|
||||
className="items-center px-20 rounded-md py-2 max-w-fit self-center bg-gray-900 text-white hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
className="items-center self-center px-20 py-2 text-white bg-gray-900 rounded-md max-w-fit hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={!enabled}
|
||||
>
|
||||
Checkout
|
||||
|
||||
8
lib/addresses.ts
Normal file
8
lib/addresses.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { PublicKey } from "@solana/web3.js"
|
||||
|
||||
// Your shop wallet address
|
||||
export const shopAddress = new PublicKey('EXWr1Go8UyfA39U1dfRkcH8uUvqunbRhQEUQNm36UsyQ')
|
||||
// This is the same for everyone!
|
||||
export const usdcAddress = new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr')
|
||||
// This is your token/coupon address
|
||||
export const couponAddress = new PublicKey('Dk1ZdmaUez3mxzxxHrTKsJ7c1u6AXM5XhqSGDtCuvtna')
|
||||
@ -8,7 +8,7 @@ export default function calculatePrice(query: ParsedUrlQuery): BigNumber {
|
||||
const product = products.find(p => p.id === id)
|
||||
if (!product) continue;
|
||||
|
||||
const price = product.priceSol
|
||||
const price = product.priceUsd
|
||||
const productQuantity = new BigNumber(quantity as string)
|
||||
amount = amount.plus(productQuantity.multipliedBy(price))
|
||||
}
|
||||
|
||||
6554
package-lock.json
generated
6554
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
19
package.json
19
package.json
@ -4,23 +4,38 @@
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start"
|
||||
"start": "next start",
|
||||
"proxy": "local-ssl-proxy --source 3001 --target 3000",
|
||||
"my-ip": "node -e \"var ip = require('ip'); console.log(ip.address())\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@metaplex-foundation/mpl-candy-machine": "^4.2.0",
|
||||
"@solana/pay": "^0.2.0",
|
||||
"@solana/spl-token": "^0.2.0",
|
||||
"@solana/wallet-adapter-base": "^0.9.5",
|
||||
"@solana/wallet-adapter-react": "^0.15.4",
|
||||
"@solana/wallet-adapter-react-ui": "^0.9.6",
|
||||
"@solana/wallet-adapter-wallets": "^0.16.0",
|
||||
"@solana/web3.js": "^1.41.3",
|
||||
"@tailwindcss/forms": "^0.5.0",
|
||||
"bignumber.js": "^9.0.2",
|
||||
"bs58": "^5.0.0",
|
||||
"dotenv": "^16.0.0",
|
||||
"next": "latest",
|
||||
"react": "^17.0.2",
|
||||
"react-circular-progressbar": "^2.0.4",
|
||||
"react-dom": "^17.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "17.0.4",
|
||||
"@types/react": "17.0.38",
|
||||
"autoprefixer": "^10.4.0",
|
||||
"ip": "^1.1.5",
|
||||
"local-ssl-proxy": "^1.2.3",
|
||||
"postcss": "^8.4.5",
|
||||
"prettier": "^2.5.1",
|
||||
"prettier-plugin-tailwindcss": "^0.1.1",
|
||||
"tailwindcss": "^3.0.7",
|
||||
"typescript": "4.5.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,16 +2,44 @@ import '../styles/globals.css'
|
||||
import type { AppProps } from 'next/app'
|
||||
import Layout from '../components/Layout'
|
||||
import Head from 'next/head'
|
||||
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'
|
||||
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui'
|
||||
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'
|
||||
import { clusterApiUrl } from '@solana/web3.js'
|
||||
import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets'
|
||||
|
||||
// Default styles that can be overridden by your app
|
||||
require('@solana/wallet-adapter-react-ui/styles.css');
|
||||
|
||||
function MyApp({ Component, pageProps }: AppProps) {
|
||||
// The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
|
||||
const network = WalletAdapterNetwork.Devnet;
|
||||
|
||||
// You can also provide a custom RPC endpoint.
|
||||
const endpoint = clusterApiUrl(network);
|
||||
|
||||
// @solana/wallet-adapter-wallets includes all the adapters but supports tree shaking and lazy loading --
|
||||
// Only the wallets you configure here will be compiled into your application, and only the dependencies
|
||||
// of wallets that your users connect to will be loaded.
|
||||
const wallets = [
|
||||
new PhantomWalletAdapter(),
|
||||
new SolflareWalletAdapter({ network }),
|
||||
];
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<Head>
|
||||
<title>Cookies Inc</title>
|
||||
</Head>
|
||||
<Component {...pageProps} />
|
||||
</Layout>
|
||||
<ConnectionProvider endpoint={endpoint}>
|
||||
<WalletProvider wallets={wallets} autoConnect>
|
||||
<WalletModalProvider>
|
||||
<Layout>
|
||||
<Head>
|
||||
<title>Cookies Inc</title>
|
||||
</Head>
|
||||
<Component {...pageProps} />
|
||||
</Layout>
|
||||
</WalletModalProvider>
|
||||
</WalletProvider>
|
||||
</ConnectionProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default MyApp
|
||||
export default MyApp
|
||||
312
pages/api/makeTransaction.ts
Normal file
312
pages/api/makeTransaction.ts
Normal file
@ -0,0 +1,312 @@
|
||||
import { createAssociatedTokenAccountInstruction, createInitializeMintInstruction, createMintToInstruction, createTransferCheckedInstruction, getAssociatedTokenAddress, getMint, MintLayout, TOKEN_PROGRAM_ID } from "@solana/spl-token"
|
||||
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"
|
||||
import { clusterApiUrl, Connection, Keypair, PublicKey, SystemProgram, SYSVAR_CLOCK_PUBKEY, SYSVAR_INSTRUCTIONS_PUBKEY, SYSVAR_SLOT_HASHES_PUBKEY, Transaction, TransactionInstruction } from "@solana/web3.js"
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
import { usdcAddress } from "../../lib/addresses"
|
||||
import calculatePrice from "../../lib/calculatePrice"
|
||||
import { MintNftInstructionAccounts, MintNftInstructionArgs, createMintNftInstruction } from "@metaplex-foundation/mpl-candy-machine"
|
||||
import base58 from "bs58"
|
||||
// Constantsgst
|
||||
// metaplex token metadata program address
|
||||
const TOKEN_METADATA_PROGRAM_ID = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');
|
||||
|
||||
// associated token account program address
|
||||
const SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID = new PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL')
|
||||
|
||||
// candy machine program address
|
||||
const CANDY_MACHINE_PROGRAM_ID = new PublicKey('cndy3Z4yapfJBmL3ShUp5exZKqR3z33thTzeNMm2gRZ')
|
||||
|
||||
// You need to update the next 2 to your candy machine
|
||||
// my candy machine address
|
||||
const MY_CANDY_MACHINE_ID = new PublicKey("F8Kxjnp3dXyBamR4DKXSGvnzdz4PckJrQxWSingWfdQg")
|
||||
|
||||
// my wallet address used to create the candy machine
|
||||
const CANDY_MACHINE_OWNER = new PublicKey("9AUvdLggr4DezH1FEHFBVqQPNUF9q6sZGTYoPMyum2sk")
|
||||
|
||||
export type MakeTransactionInputData = {
|
||||
account: string,
|
||||
}
|
||||
|
||||
type MakeTransactionGetResponse = {
|
||||
label: string,
|
||||
icon: string,
|
||||
}
|
||||
|
||||
export type MakeTransactionOutputData = {
|
||||
transaction: string,
|
||||
message: string,
|
||||
}
|
||||
|
||||
type ErrorOutput = {
|
||||
error: string
|
||||
}
|
||||
|
||||
function get(res: NextApiResponse<MakeTransactionGetResponse>) {
|
||||
res.status(200).json({
|
||||
label: "Cookies Inc",
|
||||
icon: "https://freesvg.org/img/1370962427.png",
|
||||
})
|
||||
}
|
||||
|
||||
// Copied from candy-machine-ui: https://github.dev/metaplex-foundation/metaplex/blob/e20c14069be57ffa09428dd25a07a5bcf7ef51c4/js/packages/candy-machine-ui/src/candy-machine.ts#L222
|
||||
const getMetadata = async (mint: PublicKey): Promise<PublicKey> => {
|
||||
return (
|
||||
await PublicKey.findProgramAddress(
|
||||
[
|
||||
Buffer.from('metadata'),
|
||||
TOKEN_METADATA_PROGRAM_ID.toBuffer(),
|
||||
mint.toBuffer(),
|
||||
],
|
||||
TOKEN_METADATA_PROGRAM_ID,
|
||||
)
|
||||
)[0];
|
||||
};
|
||||
|
||||
// Copied from candy-machine-ui: https://github.dev/metaplex-foundation/metaplex/blob/e20c14069be57ffa09428dd25a07a5bcf7ef51c4/js/packages/candy-machine-ui/src/candy-machine.ts#L206
|
||||
const getMasterEdition = async (
|
||||
mint: PublicKey,
|
||||
): Promise<PublicKey> => {
|
||||
return (
|
||||
await PublicKey.findProgramAddress(
|
||||
[
|
||||
Buffer.from('metadata'),
|
||||
TOKEN_METADATA_PROGRAM_ID.toBuffer(),
|
||||
mint.toBuffer(),
|
||||
Buffer.from('edition'),
|
||||
],
|
||||
TOKEN_METADATA_PROGRAM_ID,
|
||||
)
|
||||
)[0];
|
||||
};
|
||||
|
||||
// Copied from candy-machine-ui: https://github.dev/metaplex-foundation/metaplex/blob/631983372cfbdfa99a45c26141f8756cd77efc99/js/packages/candy-machine-ui/src/utils.ts#L55-L63
|
||||
const getAtaForMint = async (payer: PublicKey, mint: PublicKey,): Promise<[PublicKey, number]> => {
|
||||
return await PublicKey.findProgramAddress(
|
||||
[payer.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
|
||||
SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID,
|
||||
);
|
||||
};
|
||||
|
||||
// Copied from candy-machine-ui: https://github.dev/metaplex-foundation/metaplex/blob/e20c14069be57ffa09428dd25a07a5bcf7ef51c4/js/packages/candy-machine-ui/src/candy-machine.ts#L237-L238
|
||||
const getCandyMachineCreator = async (candyMachine: PublicKey): Promise<[PublicKey, number]> => {
|
||||
return await PublicKey.findProgramAddress(
|
||||
[Buffer.from('candy_machine'), candyMachine.toBuffer()],
|
||||
CANDY_MACHINE_PROGRAM_ID,
|
||||
);
|
||||
};
|
||||
|
||||
const createSetupInstructions = async (
|
||||
connection: Connection,
|
||||
payer: PublicKey,
|
||||
mintFor: PublicKey,
|
||||
mint: PublicKey
|
||||
): Promise<TransactionInstruction[]> => {
|
||||
const minimumBalance = await connection.getMinimumBalanceForRentExemption(MintLayout.span)
|
||||
const userTokenAccountAddress = (await getAtaForMint(mintFor, mint))[0];
|
||||
|
||||
return [
|
||||
SystemProgram.createAccount({
|
||||
fromPubkey: payer,
|
||||
newAccountPubkey: mint,
|
||||
space: MintLayout.span,
|
||||
lamports: minimumBalance,
|
||||
programId: TOKEN_PROGRAM_ID,
|
||||
}),
|
||||
createInitializeMintInstruction(
|
||||
mint,
|
||||
0, // decimals
|
||||
mintFor, // mint authority
|
||||
mintFor, // freeze authority
|
||||
),
|
||||
createAssociatedTokenAccountInstruction(
|
||||
payer, // payer
|
||||
userTokenAccountAddress, // user token address
|
||||
mintFor, // owner
|
||||
mint, // mint
|
||||
),
|
||||
createMintToInstruction(
|
||||
mint, // mint
|
||||
userTokenAccountAddress, // destination
|
||||
mintFor, // authority
|
||||
1, // amount
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
const createMetaplexMintInstruction = async (
|
||||
payer: PublicKey,
|
||||
mintFor: PublicKey,
|
||||
mint: PublicKey
|
||||
): Promise<TransactionInstruction> => {
|
||||
const metadata = await getMetadata(mint)
|
||||
const masterEdition = await getMasterEdition(mint)
|
||||
|
||||
const [candyMachineCreator, creatorBump] = await getCandyMachineCreator(
|
||||
MY_CANDY_MACHINE_ID,
|
||||
);
|
||||
|
||||
const accounts: MintNftInstructionAccounts = {
|
||||
// from metaplex CLI
|
||||
candyMachine: MY_CANDY_MACHINE_ID,
|
||||
// from getCandyMachineCreator
|
||||
candyMachineCreator: candyMachineCreator,
|
||||
// who is paying for the NFT to be minted
|
||||
payer: payer,
|
||||
// treasury, I just set this to myself (this is set in metaplex CLI)
|
||||
wallet: CANDY_MACHINE_OWNER,
|
||||
// metadata public key, from getMetadata call
|
||||
metadata,
|
||||
// mint public key, generated
|
||||
mint: mint,
|
||||
// mint + update authorities are who we're minting for
|
||||
mintAuthority: mintFor,
|
||||
updateAuthority: mintFor,
|
||||
// master edition public key, from getMasterEdition call
|
||||
masterEdition,
|
||||
// token metadata program is hardcoded
|
||||
tokenMetadataProgram: TOKEN_METADATA_PROGRAM_ID,
|
||||
// clock, from web3.js
|
||||
clock: SYSVAR_CLOCK_PUBKEY,
|
||||
// copied from candy-machine-ui, which uses this
|
||||
recentBlockhashes: SYSVAR_SLOT_HASHES_PUBKEY,
|
||||
// also just copied candy-machine-ui
|
||||
instructionSysvarAccount: SYSVAR_INSTRUCTIONS_PUBKEY,
|
||||
}
|
||||
|
||||
const args: MintNftInstructionArgs = {
|
||||
creatorBump
|
||||
}
|
||||
|
||||
return createMintNftInstruction(accounts, args)
|
||||
}
|
||||
|
||||
async function post(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<MakeTransactionOutputData | ErrorOutput>
|
||||
) {
|
||||
try {
|
||||
// We pass the selected items in the query, calculate the expected cost
|
||||
const amount = calculatePrice(req.query)
|
||||
if (amount.toNumber() === 0) {
|
||||
res.status(400).json({ error: "Can't checkout with charge of 0" })
|
||||
return
|
||||
}
|
||||
|
||||
// We pass the reference to use in the query
|
||||
const { reference } = req.query
|
||||
if (!reference) {
|
||||
res.status(400).json({ error: "No reference provided" })
|
||||
return
|
||||
}
|
||||
|
||||
// We pass the buyer's public key in JSON body
|
||||
const { account } = req.body as MakeTransactionInputData
|
||||
if (!account) {
|
||||
res.status(40).json({ error: "No account provided" })
|
||||
return
|
||||
}
|
||||
|
||||
// We get the shop private key from .env - this is the same as in our script
|
||||
const shopPrivateKey = process.env.SHOP_PRIVATE_KEY as string
|
||||
if (!shopPrivateKey) {
|
||||
res.status(500).json({ error: "Shop private key not available" })
|
||||
}
|
||||
const shopKeypair = Keypair.fromSecretKey(base58.decode(shopPrivateKey))
|
||||
|
||||
|
||||
const buyerPublicKey = new PublicKey(account)
|
||||
const shopPublicKey = shopKeypair.publicKey
|
||||
|
||||
const network = WalletAdapterNetwork.Devnet
|
||||
const endpoint = clusterApiUrl(network)
|
||||
const connection = new Connection(endpoint)
|
||||
|
||||
|
||||
// Get details about the USDC token
|
||||
const usdcMint = await getMint(connection, usdcAddress)
|
||||
// Get the buyer's USDC token account address
|
||||
const buyerUsdcAddress = await getAssociatedTokenAddress(usdcAddress, buyerPublicKey)
|
||||
// Get the shop's USDC token account address
|
||||
const shopUsdcAddress = await getAssociatedTokenAddress(usdcAddress, CANDY_MACHINE_OWNER)
|
||||
|
||||
// Get a recent blockhash to include in the transaction
|
||||
const { blockhash } = await (connection.getLatestBlockhash('finalized'))
|
||||
|
||||
const transaction = new Transaction({
|
||||
recentBlockhash: blockhash,
|
||||
// The buyer pays the transaction fee
|
||||
feePayer: shopPublicKey,
|
||||
})
|
||||
|
||||
const amountToPay = amount
|
||||
|
||||
// Create the instruction to send USDC from the buyer to the shop
|
||||
const transferInstruction = createTransferCheckedInstruction(
|
||||
buyerUsdcAddress, // source
|
||||
usdcAddress, // mint (token address)
|
||||
shopUsdcAddress, // destination
|
||||
buyerPublicKey, // owner of source address
|
||||
amountToPay.toNumber() * (10 ** usdcMint.decimals), // amount to transfer (in units of the USDC token)
|
||||
usdcMint.decimals, // decimals of the USDC token
|
||||
)
|
||||
|
||||
// Add the reference to the instruction as a key
|
||||
// This will mean this transaction is returned when we query for the reference
|
||||
transferInstruction.keys.push({
|
||||
pubkey: new PublicKey(reference),
|
||||
isSigner: false,
|
||||
isWritable: false,
|
||||
})
|
||||
|
||||
const mint = Keypair.generate()
|
||||
|
||||
// Create the mint setup instructions
|
||||
const mintSetupInstructions = await createSetupInstructions(connection, shopPublicKey, buyerPublicKey, mint.publicKey)
|
||||
|
||||
// Create the mint NFT instruction
|
||||
const mintNFTInstruction = await createMetaplexMintInstruction(shopPublicKey, buyerPublicKey, mint.publicKey)
|
||||
|
||||
// Add all instructions to the transaction
|
||||
transaction.add(transferInstruction, ...mintSetupInstructions, mintNFTInstruction)
|
||||
|
||||
// Sign the transaction as the mint, which is required for setup instructions
|
||||
// Also sign as the shop, which is paying the NFT costs
|
||||
// We must partial sign because the transfer instruction still requires the user
|
||||
transaction.partialSign(mint, shopKeypair)
|
||||
|
||||
// Serialize the transaction and convert to base64 to return it
|
||||
const serializedTransaction = transaction.serialize({
|
||||
// We will need the buyer to sign this transaction after it's returned to them
|
||||
requireAllSignatures: false
|
||||
})
|
||||
const base64 = serializedTransaction.toString('base64')
|
||||
|
||||
// Insert into database: reference, amount
|
||||
|
||||
const message = "Free dinosaur with all cookies! 🍪"
|
||||
|
||||
// Return the serialized transaction
|
||||
res.status(200).json({
|
||||
transaction: base64,
|
||||
message,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
res.status(500).json({ error: 'error creating transaction', })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<MakeTransactionGetResponse | MakeTransactionOutputData | ErrorOutput>
|
||||
) {
|
||||
if (req.method === "GET") {
|
||||
return get(res)
|
||||
} else if (req.method === "POST") {
|
||||
return await post(req, res)
|
||||
} else {
|
||||
return res.status(405).json({ error: "Method not allowed" })
|
||||
}
|
||||
}
|
||||
@ -1,18 +1,137 @@
|
||||
import { useConnection, useWallet } from "@solana/wallet-adapter-react";
|
||||
import { WalletMultiButton } from "@solana/wallet-adapter-react-ui";
|
||||
import { Keypair, Transaction } from "@solana/web3.js";
|
||||
import { findReference, FindReferenceError } from "@solana/pay";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import BackLink from "../components/BackLink";
|
||||
import PageHeading from "../components/PageHeading";
|
||||
import calculatePrice from "../lib/calculatePrice";
|
||||
import Loading from "../components/Loading";
|
||||
import { MakeTransactionInputData, MakeTransactionOutputData } from "./api/makeTransaction";
|
||||
|
||||
export default function Checkout() {
|
||||
const router = useRouter()
|
||||
const router = useRouter();
|
||||
const { connection } = useConnection();
|
||||
const { publicKey, sendTransaction } = useWallet();
|
||||
|
||||
const amount = calculatePrice(router.query)
|
||||
// State to hold API response fields
|
||||
const [transaction, setTransaction] = useState<Transaction | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
// Read the URL query (which includes our chosen products)
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(router.query)) {
|
||||
if (value) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const v of value) {
|
||||
searchParams.append(key, v);
|
||||
}
|
||||
} else {
|
||||
searchParams.append(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate the unique reference which will be used for this transaction
|
||||
const reference = useMemo(() => Keypair.generate().publicKey, []);
|
||||
|
||||
// Add it to the params we'll pass to the API
|
||||
searchParams.append('reference', reference.toString());
|
||||
|
||||
// Use our API to fetch the transaction for the selected items
|
||||
async function getTransaction() {
|
||||
if (!publicKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const body: MakeTransactionInputData = {
|
||||
account: publicKey.toString(),
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/makeTransaction?${searchParams.toString()}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
const json = await response.json() as MakeTransactionOutputData
|
||||
|
||||
if (response.status !== 200) {
|
||||
console.error(json);
|
||||
return;
|
||||
}
|
||||
|
||||
// Deserialize the transaction from the response
|
||||
const transaction = Transaction.from(Buffer.from(json.transaction, 'base64'));
|
||||
setTransaction(transaction);
|
||||
setMessage(json.message);
|
||||
console.log(transaction);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
getTransaction()
|
||||
}, [publicKey])
|
||||
|
||||
// Send the fetched transaction to the connected wallet
|
||||
async function trySendTransaction() {
|
||||
if (!transaction) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await sendTransaction(transaction, connection)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Send the transaction once it's fetched
|
||||
useEffect(() => {
|
||||
trySendTransaction()
|
||||
}, [transaction])
|
||||
|
||||
// Check every 0.5s if the transaction is completed
|
||||
useEffect(() => {
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
// Check if there is any transaction for the reference
|
||||
const signatureInfo = await findReference(connection, reference);
|
||||
router.push('/confirmed')
|
||||
} catch (e) {
|
||||
if (e instanceof FindReferenceError) {
|
||||
// No transaction found yet, ignore this error
|
||||
return;
|
||||
}
|
||||
console.error('Unknown error', e)
|
||||
}
|
||||
}, 500)
|
||||
return () => {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!publicKey) {
|
||||
return (
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<div><BackLink href='/'>Cancel</BackLink></div>
|
||||
|
||||
<WalletMultiButton />
|
||||
|
||||
<p>You need to connect your wallet to make transactions</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8 items-center">
|
||||
<BackLink href='/'>Cancel</BackLink>
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<div><BackLink href='/'>Cancel</BackLink></div>
|
||||
|
||||
<PageHeading>Checkout {amount.toString()} SOL</PageHeading>
|
||||
<WalletMultiButton />
|
||||
|
||||
{message ?
|
||||
<p>{message} Please approve the transaction using your wallet</p> :
|
||||
<p>Creating transaction... <Loading /></p>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
15
pages/confirmed.tsx
Normal file
15
pages/confirmed.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
import BackLink from '../components/BackLink';
|
||||
import Confirmed from '../components/Confirmed';
|
||||
import PageHeading from '../components/PageHeading';
|
||||
|
||||
export default function ConfirmedPage() {
|
||||
return (
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<BackLink href='/'>Home</BackLink>
|
||||
|
||||
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
|
||||
|
||||
<div className='h-80 w-80'><Confirmed /></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,12 +1,27 @@
|
||||
import { useWallet } from '@solana/wallet-adapter-react'
|
||||
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui'
|
||||
import CouponBook from '../components/CouponBook'
|
||||
import Products from '../components/Products'
|
||||
import SiteHeading from '../components/SiteHeading'
|
||||
|
||||
export default function HomePage() {
|
||||
// We get the public key of the connected wallet, if there is one
|
||||
const { publicKey } = useWallet()
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-8 max-w-4xl items-stretch m-auto pt-24">
|
||||
<div className="flex flex-col items-stretch max-w-4xl gap-8 pt-24 m-auto">
|
||||
<SiteHeading>Cookies Inc</SiteHeading>
|
||||
|
||||
<Products submitTarget='/checkout' enabled={true} />
|
||||
{/* We add the Solana wallet connect button */}
|
||||
<div className="basis-1/4">
|
||||
<WalletMultiButton className='!bg-gray-900 hover:scale-105' />
|
||||
</div>
|
||||
|
||||
{/* We display the coupon book if there's a connected wallet */}
|
||||
{publicKey && <CouponBook />}
|
||||
|
||||
{/* We disable checking out without a connected wallet */}
|
||||
<Products submitTarget='/checkout' enabled={publicKey !== null} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
119
pages/shop/checkout.tsx
Normal file
119
pages/shop/checkout.tsx
Normal file
@ -0,0 +1,119 @@
|
||||
import { createQR, encodeURL, TransferRequestURLFields, findReference, validateTransfer, FindReferenceError, ValidateTransferError, TransactionRequestURLFields } from "@solana/pay";
|
||||
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
|
||||
import { clusterApiUrl, Connection, Keypair } from "@solana/web3.js";
|
||||
import { useRouter } from "next/router";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import BackLink from "../../components/BackLink";
|
||||
import PageHeading from "../../components/PageHeading";
|
||||
import { shopAddress, usdcAddress } from "../../lib/addresses";
|
||||
import calculatePrice from "../../lib/calculatePrice";
|
||||
|
||||
export default function Checkout() {
|
||||
const router = useRouter()
|
||||
|
||||
// ref to a div where we'll show the QR code
|
||||
const qrRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const amount = useMemo(() => calculatePrice(router.query), [router.query])
|
||||
|
||||
// Read the URL query (which includes our chosen products)
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(router.query)) {
|
||||
if (value) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const v of value) {
|
||||
searchParams.append(key, v);
|
||||
}
|
||||
} else {
|
||||
searchParams.append(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate the unique reference which will be used for this transaction
|
||||
const reference = useMemo(() => Keypair.generate().publicKey, []);
|
||||
|
||||
// Add it to the params we'll pass to the API
|
||||
searchParams.append('reference', reference.toString());
|
||||
|
||||
// Get a connection to Solana devnet
|
||||
const network = WalletAdapterNetwork.Devnet
|
||||
const endpoint = clusterApiUrl(network)
|
||||
const connection = new Connection(endpoint)
|
||||
|
||||
// Solana Pay transfer params
|
||||
const urlParams: TransferRequestURLFields = {
|
||||
recipient: shopAddress,
|
||||
splToken: usdcAddress,
|
||||
amount,
|
||||
reference,
|
||||
label: "Cookies Inc",
|
||||
message: "Thanks for your order! 🍪",
|
||||
}
|
||||
|
||||
// Show the QR code
|
||||
useEffect(() => {
|
||||
// window.location is only available in the browser, so create the URL in here
|
||||
const { location } = window
|
||||
const apiUrl = `${location.protocol}//${location.host}/api/makeTransaction?${searchParams.toString()}`
|
||||
const urlParams: TransactionRequestURLFields = {
|
||||
link: new URL(apiUrl),
|
||||
label: "Cookies Inc",
|
||||
message: "Thanks for your order! 🍪",
|
||||
}
|
||||
const solanaUrl = encodeURL(urlParams)
|
||||
const qr = createQR(solanaUrl, 512, 'transparent')
|
||||
if (qrRef.current && amount.isGreaterThan(0)) {
|
||||
qrRef.current.innerHTML = ''
|
||||
qr.append(qrRef.current)
|
||||
}
|
||||
})
|
||||
|
||||
// Check every 0.5s if the transaction is completed
|
||||
useEffect(() => {
|
||||
const interval = setInterval(async () => {
|
||||
try {
|
||||
// Check if there is any transaction for the reference
|
||||
const signatureInfo = await findReference(connection, reference, { finality: 'confirmed' })
|
||||
// Validate that the transaction has the expected recipient, amount and SPL token
|
||||
await validateTransfer(
|
||||
connection,
|
||||
signatureInfo.signature,
|
||||
{
|
||||
recipient: shopAddress,
|
||||
amount,
|
||||
splToken: usdcAddress,
|
||||
reference,
|
||||
},
|
||||
{ commitment: 'confirmed' }
|
||||
)
|
||||
router.push('/shop/confirmed')
|
||||
} catch (e) {
|
||||
if (e instanceof FindReferenceError) {
|
||||
// No transaction found yet, ignore this error
|
||||
return;
|
||||
}
|
||||
if (e instanceof ValidateTransferError) {
|
||||
// Transaction is invalid
|
||||
console.error('Transaction is invalid', e)
|
||||
return;
|
||||
}
|
||||
console.error('Unknown error', e)
|
||||
}
|
||||
}, 500)
|
||||
return () => {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [amount])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-8">
|
||||
<BackLink href='/shop'>Cancel</BackLink>
|
||||
|
||||
<PageHeading>Checkout ${amount.toString()}</PageHeading>
|
||||
|
||||
{/* div added to display the QR code */}
|
||||
<div ref={qrRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
15
pages/shop/confirmed.tsx
Normal file
15
pages/shop/confirmed.tsx
Normal file
@ -0,0 +1,15 @@
|
||||
import BackLink from '../../components/BackLink';
|
||||
import Confirmed from '../../components/Confirmed';
|
||||
import PageHeading from '../../components/PageHeading';
|
||||
|
||||
export default function ConfirmedPage() {
|
||||
return (
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<BackLink href='/shop'>Next order</BackLink>
|
||||
|
||||
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
|
||||
|
||||
<div className='h-80 w-80'><Confirmed /></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
10
pages/shop/index.tsx
Normal file
10
pages/shop/index.tsx
Normal file
@ -0,0 +1,10 @@
|
||||
import Products from '../../components/Products'
|
||||
import SiteHeading from '../../components/SiteHeading'
|
||||
|
||||
export default function ShopPage() {
|
||||
return (
|
||||
<div className="flex flex-col items-stretch max-w-4xl gap-8 pt-24 m-auto">
|
||||
<SiteHeading>Cookies Inc</SiteHeading>
|
||||
<Products submitTarget='/shop/checkout' enabled={true} /> </div>
|
||||
)
|
||||
}
|
||||
59
scripts/create-coupon.js
Normal file
59
scripts/create-coupon.js
Normal file
@ -0,0 +1,59 @@
|
||||
import { createAssociatedTokenAccount, createMint, getAccount, mintToChecked } from '@solana/spl-token'
|
||||
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'
|
||||
import { clusterApiUrl, Connection, Keypair } from '@solana/web3.js'
|
||||
import base58 from 'bs58'
|
||||
|
||||
// Read .env into process.env
|
||||
import 'dotenv/config'
|
||||
|
||||
// Initialise Solana connection
|
||||
const network = WalletAdapterNetwork.Devnet
|
||||
const endpoint = clusterApiUrl(network)
|
||||
const connection = new Connection(endpoint)
|
||||
|
||||
// Initialise shop account
|
||||
const shopPrivateKey = process.env.SHOP_PRIVATE_KEY
|
||||
if (!shopPrivateKey) {
|
||||
throw new Error('SHOP_PRIVATE_KEY not set')
|
||||
}
|
||||
const shopAccount = Keypair.fromSecretKey(base58.decode(shopPrivateKey))
|
||||
|
||||
// Create the token, returns the token public key
|
||||
console.log("Creating token...")
|
||||
const myCouponAddress = await createMint(
|
||||
connection,
|
||||
shopAccount, // payer
|
||||
shopAccount.publicKey, // who has permission to mint?
|
||||
shopAccount.publicKey, // who has permission to freeze?
|
||||
0 // decimals (0 = whole numbers)
|
||||
)
|
||||
console.log("Token created:", myCouponAddress.toString())
|
||||
|
||||
// Create the associated token account for the shop
|
||||
console.log("Creating token account for the shop...")
|
||||
const shopCouponAddress = await createAssociatedTokenAccount(
|
||||
connection,
|
||||
shopAccount, // payer
|
||||
myCouponAddress, // token
|
||||
shopAccount.publicKey, // who to create an account for
|
||||
)
|
||||
console.log("Token account created:", shopCouponAddress.toString())
|
||||
|
||||
// Mint 1 million coupons to the shop account
|
||||
console.log("Minting 1 million coupons to the shop account...")
|
||||
await mintToChecked(
|
||||
connection,
|
||||
shopAccount, // payer
|
||||
myCouponAddress, // token
|
||||
shopCouponAddress, // recipient
|
||||
shopAccount, // authority to mint
|
||||
1_000_000, // amount
|
||||
0, //decimals
|
||||
)
|
||||
console.log("Minted 1 million coupons to the shop account")
|
||||
|
||||
const { amount } = await getAccount(connection, shopCouponAddress)
|
||||
console.log({
|
||||
myCouponAddress: myCouponAddress.toString(),
|
||||
balance: amount.toLocaleString(),
|
||||
})
|
||||
3
scripts/package.json
Normal file
3
scripts/package.json
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user