Compare commits
12 Commits
start
...
extra-no-p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b362714d3c | ||
|
|
794430cb88 | ||
|
|
2f151312b4 | ||
|
|
f552f3d6fd | ||
|
|
6e2a127510 | ||
|
|
6f8aba4427 | ||
|
|
5b46d85f62 | ||
|
|
22539b7fbe | ||
|
|
2a15606b68 | ||
|
|
f5fad1e5e3 | ||
|
|
5e41c31eab | ||
|
|
6ed7e5844d |
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 pointer.gg
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@ -1,3 +1 @@
|
||||
# Take payments IRL with Solana Pay
|
||||
|
||||
Code for [Pointer Solana Pay Tutorial](pointer.gg/tutorials/solana-pay-irl-payments)
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
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)
|
||||
|
||||
@ -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
|
||||
|
||||
19
contexts/ConfigProvider.tsx
Normal file
19
contexts/ConfigProvider.tsx
Normal file
@ -0,0 +1,19 @@
|
||||
import React, { PropsWithChildren } from 'react';
|
||||
|
||||
export interface ConfigProviderProps {
|
||||
baseUrl: string,
|
||||
}
|
||||
|
||||
const ConfigContext = React.createContext({ baseUrl: 'https://localhost:3001' });
|
||||
|
||||
export function ConfigProvider(props: PropsWithChildren<ConfigProviderProps>) {
|
||||
return (
|
||||
<ConfigContext.Provider value={{ baseUrl: props.baseUrl }}>
|
||||
{props.children}
|
||||
</ConfigContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useConfig() {
|
||||
return React.useContext(ConfigContext);
|
||||
}
|
||||
@ -1,6 +1,10 @@
|
||||
import { PublicKey } from "@solana/web3.js"
|
||||
|
||||
// this is your shop wallet address
|
||||
export const shopAddress = new PublicKey('...')
|
||||
// Your shop wallet address
|
||||
export const shopAddress = new PublicKey('EXWr1Go8UyfA39U1dfRkcH8uUvqunbRhQEUQNm36UsyQ')
|
||||
|
||||
// this is the same for everyone!
|
||||
export const usdcAddress = new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr')
|
||||
export const usdcAddress = new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr')
|
||||
|
||||
// This is your token/coupon address
|
||||
export const couponAddress = new PublicKey('74aFyMgbKppdab4wEVz5AXL3UGbxMkwkwgK2LVzn3MmG')
|
||||
@ -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))
|
||||
}
|
||||
|
||||
4990
package-lock.json
generated
4990
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
18
package.json
18
package.json
@ -1,22 +1,28 @@
|
||||
{
|
||||
"name": "solana-pay-tutorial",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start"
|
||||
"start": "next start",
|
||||
"proxy": "local-ssl-proxy --source 3002 --target 3000"
|
||||
},
|
||||
"dependencies": {
|
||||
"@solana/pay": "^0.2.0",
|
||||
"@solana/spl-token": "^0.4.6",
|
||||
"@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.1.0",
|
||||
"react-circular-progressbar": "^2.0.4",
|
||||
"react-dom": "^17.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bs58": "^4.0.1",
|
||||
"@types/node": "17.0.4",
|
||||
"@types/react": "17.0.38",
|
||||
"autoprefixer": "^10.4.0",
|
||||
@ -26,4 +32,4 @@
|
||||
"tailwindcss": "^3.0.7",
|
||||
"typescript": "4.5.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import '../styles/globals.css'
|
||||
import type { AppProps } from 'next/app'
|
||||
import { AppContext, AppProps, default as NextApp } from 'next/app'
|
||||
import Layout from '../components/Layout'
|
||||
import Head from 'next/head'
|
||||
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'
|
||||
@ -7,11 +7,16 @@ 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'
|
||||
import { ConfigProvider } from '../contexts/ConfigProvider'
|
||||
|
||||
// Default styles that can be overridden by your app
|
||||
require('@solana/wallet-adapter-react-ui/styles.css');
|
||||
|
||||
function MyApp({ Component, pageProps }: AppProps) {
|
||||
interface MyAppProps extends AppProps {
|
||||
host: string;
|
||||
}
|
||||
|
||||
function MyApp({ Component, pageProps, host }: MyAppProps) {
|
||||
// The network can be set to 'devnet', 'testnet', or 'mainnet-beta'.
|
||||
const network = WalletAdapterNetwork.Devnet;
|
||||
|
||||
@ -26,6 +31,8 @@ function MyApp({ Component, pageProps }: AppProps) {
|
||||
new SolflareWalletAdapter({ network }),
|
||||
];
|
||||
|
||||
const baseUrl = `https://${host}`;
|
||||
|
||||
return (
|
||||
<ConnectionProvider endpoint={endpoint}>
|
||||
<WalletProvider wallets={wallets} autoConnect>
|
||||
@ -34,7 +41,9 @@ function MyApp({ Component, pageProps }: AppProps) {
|
||||
<Head>
|
||||
<title>Cookies Inc</title>
|
||||
</Head>
|
||||
<Component {...pageProps} />
|
||||
<ConfigProvider baseUrl={baseUrl}>
|
||||
<Component {...pageProps} />
|
||||
</ConfigProvider>
|
||||
</Layout>
|
||||
</WalletModalProvider>
|
||||
</WalletProvider>
|
||||
@ -42,4 +51,15 @@ function MyApp({ Component, pageProps }: AppProps) {
|
||||
)
|
||||
}
|
||||
|
||||
MyApp.getInitialProps = async (appContext: AppContext) => {
|
||||
const props = await NextApp.getInitialProps(appContext)
|
||||
const { req } = appContext.ctx;
|
||||
const host = req?.headers.host || 'localhost:3001';
|
||||
|
||||
return {
|
||||
...props,
|
||||
host,
|
||||
};
|
||||
};
|
||||
|
||||
export default MyApp
|
||||
@ -39,6 +39,7 @@ async function post(
|
||||
// We pass the selected items in the query, calculate the expected cost
|
||||
const amount = calculatePrice(req.query)
|
||||
if (amount.toNumber() === 0) {
|
||||
console.log('Returning 400: amount = 0')
|
||||
res.status(400).json({ error: "Can't checkout with charge of 0" })
|
||||
return
|
||||
}
|
||||
@ -46,6 +47,7 @@ async function post(
|
||||
// We pass the reference to use in the query
|
||||
const { reference } = req.query
|
||||
if (!reference) {
|
||||
console.log('Returning 400: no reference')
|
||||
res.status(400).json({ error: "No reference provided" })
|
||||
return
|
||||
}
|
||||
@ -53,13 +55,15 @@ async function post(
|
||||
// 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" })
|
||||
console.log('Returning 400: no account')
|
||||
res.status(400).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) {
|
||||
console.log('Returning 500: shop private key not available')
|
||||
res.status(500).json({ error: "Shop private key not available" })
|
||||
}
|
||||
const shopKeypair = Keypair.fromSecretKey(base58.decode(shopPrivateKey))
|
||||
@ -154,31 +158,40 @@ async function post(
|
||||
})
|
||||
|
||||
// Add both instructions to the transaction
|
||||
transaction.add(transferInstruction, couponInstruction)
|
||||
transaction.add(transferInstruction)
|
||||
|
||||
// Sign the transaction as the shop, which is required to transfer the coupon
|
||||
// We must partial sign because the transfer instruction still requires the user
|
||||
transaction.partialSign(shopKeypair)
|
||||
// transaction.partialSign(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')
|
||||
|
||||
const tx2 = Transaction.from(serializedTransaction)
|
||||
|
||||
const serializedTx2 = transaction.serialize({
|
||||
requireAllSignatures: false
|
||||
})
|
||||
|
||||
const base64 = serializedTx2.toString('base64')
|
||||
|
||||
// Insert into database: reference, amount
|
||||
|
||||
const message = buyerGetsCouponDiscount ? "50% Discount! 🍪" : "Thanks for your order! 🍪"
|
||||
|
||||
// Return the serialized transaction
|
||||
res.status(200).json({
|
||||
const responseBody = {
|
||||
transaction: base64,
|
||||
message,
|
||||
})
|
||||
}
|
||||
|
||||
console.log('returning 200', responseBody)
|
||||
res.status(200).json(responseBody)
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
res.status(500).json({ error: 'error creating transaction', })
|
||||
return
|
||||
}
|
||||
@ -195,4 +208,4 @@ export default async function handler(
|
||||
} else {
|
||||
return res.status(405).json({ error: "Method not allowed" })
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,109 +1,138 @@
|
||||
import { createQR, encodeURL, TransferRequestURLFields, findReference, validateTransfer, FindReferenceError, ValidateTransferError } from "@solana/pay";
|
||||
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
|
||||
import { clusterApiUrl, Connection, Keypair } from "@solana/web3.js";
|
||||
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, useRef } from "react";
|
||||
import BackLink from "../../components/BackLink";
|
||||
import PageHeading from "../../components/PageHeading";
|
||||
import { shopAddress, usdcAddress } from "../../lib/addresses";
|
||||
import calculatePrice from "../../lib/calculatePrice";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import BackLink from "../components/BackLink";
|
||||
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();
|
||||
|
||||
// ref to a div where we'll show the QR code
|
||||
const qrRef = useRef<HTMLDivElement>(null)
|
||||
// State to hold API response fields
|
||||
const [transaction, setTransaction] = useState<Transaction | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(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: TransferRequestURLFields = {
|
||||
recipient: shopAddress,
|
||||
splToken: usdcAddress,
|
||||
amount,
|
||||
reference,
|
||||
label: "Cookies Inc",
|
||||
message: "Thanks for your order! 🍪",
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Encode the params into the format shown
|
||||
const url = encodeURL(urlParams)
|
||||
console.log({ url })
|
||||
// Generate the unique reference which will be used for this transaction
|
||||
const reference = useMemo(() => Keypair.generate().publicKey, []);
|
||||
|
||||
// Show the QR code
|
||||
useEffect(() => {
|
||||
const qr = createQR(url, 512, 'transparent')
|
||||
if (qrRef.current && amount.isGreaterThan(0)) {
|
||||
qrRef.current.innerHTML = ''
|
||||
qr.append(qrRef.current)
|
||||
// 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, { 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')
|
||||
const signatureInfo = await findTransactionSignature(connection, reference, {}, 'confirmed')
|
||||
router.push('/confirmed')
|
||||
} catch (e) {
|
||||
if (e instanceof FindReferenceError) {
|
||||
if (e instanceof FindTransactionSignatureError) {
|
||||
// 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])
|
||||
}, [])
|
||||
|
||||
if (!publicKey) {
|
||||
return (
|
||||
<div className='flex flex-col gap-8 items-center'>
|
||||
<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 items-center gap-8">
|
||||
<BackLink href='/shop'>Cancel</BackLink>
|
||||
<div className='flex flex-col gap-8 items-center'>
|
||||
<div><BackLink href='/'>Cancel</BackLink></div>
|
||||
|
||||
<PageHeading>Checkout ${amount.toString()}</PageHeading>
|
||||
<WalletMultiButton />
|
||||
|
||||
{message ?
|
||||
<p>{message} Please approve the transaction using your wallet</p> :
|
||||
<p>Creating transaction... <Loading /></p>
|
||||
}
|
||||
|
||||
{/* div added to display the QR code */}
|
||||
<div ref={qrRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
await validateTransfer(
|
||||
connection,
|
||||
signatureInfo.signature,
|
||||
{
|
||||
recipient: shopAddress,
|
||||
amount,
|
||||
splToken: usdcAddress,
|
||||
reference,
|
||||
},
|
||||
{ commitment: 'confirmed' }
|
||||
)
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import 'react-circular-progressbar/dist/styles.css';
|
||||
import BackLink from '../components/BackLink';
|
||||
import Confirmed from '../components/Confirmed';
|
||||
import PageHeading from '../components/PageHeading';
|
||||
@ -12,4 +13,4 @@ export default function ConfirmedPage() {
|
||||
<div className='h-80 w-80'><Confirmed /></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,8 +21,8 @@ export default function HomePage() {
|
||||
{publicKey && <CouponBook />}
|
||||
|
||||
{/* We disable checking out without a connected wallet */}
|
||||
{/* Also the submitTarget is /buy/transaction instead of /checkout */}
|
||||
{/* Also the submitTarget is /checkout instead of /checkout */}
|
||||
<Products submitTarget='/checkout' enabled={publicKey !== null} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,12 +1,11 @@
|
||||
import { createQR, encodeURL, TransferRequestURLFields, findReference, validateTransfer, FindReferenceError, ValidateTransferError, TransactionRequestURLFields } from "@solana/pay";
|
||||
import { createQR, 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";
|
||||
import { useConfig } from "../../contexts/ConfigProvider";
|
||||
|
||||
export default function Checkout() {
|
||||
const router = useRouter()
|
||||
@ -14,13 +13,8 @@ export default function Checkout() {
|
||||
// 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, [])
|
||||
|
||||
// Read the URL query (which includes our chosen products)
|
||||
const searchParams = new URLSearchParams({ reference: reference.toString() });
|
||||
const searchParams = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(router.query)) {
|
||||
if (value) {
|
||||
if (Array.isArray(value)) {
|
||||
@ -33,54 +27,50 @@ export default function Checkout() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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());
|
||||
|
||||
console.log({ query: router.query, params: searchParams.toString() })
|
||||
|
||||
// Get a connection to Solana devnet
|
||||
const network = WalletAdapterNetwork.Devnet
|
||||
const endpoint = clusterApiUrl(network)
|
||||
const connection = new Connection(endpoint)
|
||||
|
||||
const { baseUrl } = useConfig()
|
||||
|
||||
// Encode the params into the format shown
|
||||
const apiUrlEncoded = encodeURIComponent(`${baseUrl}/api/makeTransaction?${searchParams.toString()}`)
|
||||
const url = `solana:${apiUrlEncoded}`
|
||||
console.log({ url })
|
||||
|
||||
// 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)) {
|
||||
const qr = createQR(url, 512, 'transparent')
|
||||
if (qrRef.current) {
|
||||
qrRef.current.innerHTML = ''
|
||||
qr.append(qrRef.current)
|
||||
}
|
||||
})
|
||||
}, [url])
|
||||
|
||||
// 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' })
|
||||
await findTransactionSignature(connection, reference, {}, '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' }
|
||||
)
|
||||
// await validateTransactionSignature(connection, signatureInfo.signature, shopAddress, amount, usdcAddress, reference, 'confirmed')
|
||||
router.push('/shop/confirmed')
|
||||
} catch (e) {
|
||||
if (e instanceof FindReferenceError) {
|
||||
if (e instanceof FindTransactionSignatureError) {
|
||||
// No transaction found yet, ignore this error
|
||||
return;
|
||||
}
|
||||
if (e instanceof ValidateTransferError) {
|
||||
if (e instanceof ValidateTransactionSignatureError) {
|
||||
// Transaction is invalid
|
||||
console.error('Transaction is invalid', e)
|
||||
return;
|
||||
@ -94,13 +84,13 @@ export default function Checkout() {
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-8">
|
||||
<div className="flex flex-col gap-8 items-center">
|
||||
<BackLink href='/shop'>Cancel</BackLink>
|
||||
|
||||
<PageHeading>Checkout ${amount.toString()}</PageHeading>
|
||||
<PageHeading>Checkout</PageHeading>
|
||||
|
||||
{/* div added to display the QR code */}
|
||||
<div ref={qrRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
16
pages/shop/confirmed.tsx
Normal file
16
pages/shop/confirmed.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@ -5,6 +5,7 @@ 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>
|
||||
<Products submitTarget='/shop/checkout' enabled={true} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -55,6 +55,6 @@ console.log("Minted 1 million coupons to the shop account")
|
||||
const { amount } = await getAccount(connection, shopCouponAddress)
|
||||
console.log({
|
||||
myCouponAddress: myCouponAddress.toString(),
|
||||
shopCouponAddress: shopCouponAddress.toString(),
|
||||
balance: amount.toLocaleString(),
|
||||
})
|
||||
|
||||
})
|
||||
3
scripts/package.json
Normal file
3
scripts/package.json
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2017"17"17"17"17"17",
|
||||
"target": "es5",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user