Compare commits

...

6 Commits

Author SHA1 Message Date
Callum McIntyre
5b46d85f62 Detect payment on the /shop/checkout page 2022-03-25 14:38:05 +00:00
Callum McIntyre
22539b7fbe Add the shop page and checkout displaying a QR code 2022-03-25 11:33:30 +00:00
Callum McIntyre
2a15606b68 Update the app to charge in USDC instead of SOL 2022-03-25 10:48:55 +00:00
Callum McIntyre
f5fad1e5e3 Add /confirmed page and redirect after the transaction 2022-03-25 10:16:46 +00:00
Callum McIntyre
5e41c31eab Fetch + send transaction on checkout page 2022-03-24 17:34:07 +00:00
Callum McIntyre
6ed7e5844d Connect wallet + create transaction using API 2022-03-24 13:27:41 +00:00
14 changed files with 2674 additions and 36 deletions

25
components/Confirmed.tsx Normal file
View File

@ -0,0 +1,25 @@
import { useEffect, useState } from "react"
import { buildStyles, CircularProgressbar } from "react-circular-progressbar"
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',
})
} />
)
}

View File

@ -20,7 +20,7 @@ export default function Products({ submitTarget, enabled }: Props) {
<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> {/* We updated this line */}
{product.unitName && <span className="text-sm text-gray-800"> /{product.unitName}</span>}
</p>
<div className="mt-1">
@ -29,7 +29,6 @@ export default function Products({ submitTarget, enabled }: Props) {
</div>
)
})}
</div>
<button

7
lib/addresses.ts Normal file
View File

@ -0,0 +1,7 @@
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')

View File

@ -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))
}

2235
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -6,10 +6,18 @@
"start": "next start"
},
"dependencies": {
"@solana/pay": "^0.1.3",
"@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.15.5",
"@solana/web3.js": "^1.36.0",
"@tailwindcss/forms": "^0.5.0",
"bignumber.js": "^9.0.2",
"next": "latest",
"react": "^17.0.2",
"react-circular-progressbar": "^2.0.4",
"react-dom": "^17.0.2"
},
"devDependencies": {

View File

@ -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

View File

@ -0,0 +1,110 @@
import { createTransferCheckedInstruction, getAssociatedTokenAddress, getMint } from "@solana/spl-token"
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"
import { clusterApiUrl, Connection, PublicKey, Transaction } from "@solana/web3.js"
import { NextApiRequest, NextApiResponse } from "next"
import { shopAddress, usdcAddress } from "../../lib/addresses"
import calculatePrice from "../../lib/calculatePrice"
export type MakeTransactionInputData = {
account: string,
}
export type MakeTransactionOutputData = {
transaction: string,
message: string,
}
type ErrorOutput = {
error: string
}
export default async function handler(
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
}
const buyerPublicKey = new PublicKey(account)
const shopPublicKey = shopAddress
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, shopPublicKey)
// 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: buyerPublicKey,
})
// 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
amount.toNumber() * (10 ** (await 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,
})
// Add the instruction to the transaction
transaction.add(transferInstruction)
// 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
// Return the serialized transaction
res.status(200).json({
transaction: base64,
message: "Thanks for your order! 🍪",
})
} catch (err) {
console.error(err);
res.status(500).json({ error: 'error creating transaction', })
return
}
}

View File

@ -1,18 +1,137 @@
import { findTransactionSignature, FindTransactionSignatureError } from "@solana/pay";
import { useConnection, useWallet } from "@solana/wallet-adapter-react";
import { WalletMultiButton } from "@solana/wallet-adapter-react-ui";
import { Keypair, Transaction } from "@solana/web3.js";
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 findTransactionSignature(connection, reference, {}, 'confirmed')
router.push('/confirmed')
} catch (e) {
if (e instanceof FindTransactionSignatureError) {
// 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 gap-8 items-center'>
<div><BackLink href='/buy'>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 gap-8 items-center'>
<div><BackLink href='/buy'>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>
)
}

16
pages/confirmed.tsx Normal file
View File

@ -0,0 +1,16 @@
import 'react-circular-progressbar/dist/styles.css';
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 gap-8 items-center'>
<BackLink href='/'>Home</BackLink>
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
<div className='h-80 w-80'><Confirmed /></div>
</div>
)
}

View File

@ -1,12 +1,24 @@
import { useWallet } from '@solana/wallet-adapter-react'
import { WalletMultiButton } from '@solana/wallet-adapter-react-ui'
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">
<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 disable checking out without a connected wallet */}
{/* Also the submitTarget is /buy/transaction instead of /checkout */}
<Products submitTarget='/checkout' enabled={publicKey !== null} />
</div>
)
}

88
pages/shop/checkout.tsx Normal file
View File

@ -0,0 +1,88 @@
import { createQR, encodeURL, EncodeURLComponents, findTransactionSignature, FindTransactionSignatureError, validateTransactionSignature, ValidateTransactionSignatureError } 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])
// Unique address that we can listen for payments to
const reference = useMemo(() => Keypair.generate().publicKey, [])
// 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: EncodeURLComponents = {
recipient: shopAddress,
splToken: usdcAddress,
amount,
reference,
label: "Cookies Inc",
message: "Thanks for your order! 🍪",
}
// Encode the params into the format shown
const url = encodeURL(urlParams)
console.log({ url })
// Show the QR code
useEffect(() => {
const qr = createQR(url, 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 findTransactionSignature(connection, reference, {}, 'confirmed')
// Validate that the transaction has the expected recipient, amount and SPL token
await validateTransactionSignature(connection, signatureInfo.signature, shopAddress, amount, usdcAddress, reference, 'confirmed')
router.push('/shop/confirmed')
} catch (e) {
if (e instanceof FindTransactionSignatureError) {
// No transaction found yet, ignore this error
return;
}
if (e instanceof ValidateTransactionSignatureError) {
// Transaction is invalid
console.error('Transaction is invalid', e)
return;
}
console.error('Unknown error', e)
}
}, 500)
return () => {
clearInterval(interval)
}
}, [])
return (
<div className="flex flex-col gap-8 items-center">
<BackLink href='/shop'>Cancel</BackLink>
<PageHeading>Checkout ${amount.toString()}</PageHeading>
{/* div added to display the QR code */}
<div ref={qrRef} />
</div>
)
}

16
pages/shop/confirmed.tsx Normal file
View File

@ -0,0 +1,16 @@
import 'react-circular-progressbar/dist/styles.css';
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 gap-8 items-center'>
<BackLink href='/shop'>Next order</BackLink>
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
<div className='h-80 w-80'><Confirmed /></div>
</div>
)
}

11
pages/shop/index.tsx Normal file
View File

@ -0,0 +1,11 @@
import Products from '../../components/Products'
import SiteHeading from '../../components/SiteHeading'
export default function ShopPage() {
return (
<div className="flex flex-col gap-8 max-w-4xl items-stretch m-auto pt-24">
<SiteHeading>Cookies Inc</SiteHeading>
<Products submitTarget='/shop/checkout' enabled={true} />
</div>
)
}