Compare commits
7 Commits
extra-no-p
...
start
| Author | SHA1 | Date | |
|---|---|---|---|
| dbc8257f62 | |||
|
|
befad36185 | ||
|
|
409cc887a7 | ||
|
|
4e1b340378 | ||
|
|
323c14723a | ||
|
|
526c5e1fb2 | ||
|
|
169c4de724 |
21
LICENSE
Normal file
21
LICENSE
Normal file
@ -0,0 +1,21 @@
|
||||
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 +1,3 @@
|
||||
# Take payments IRL with Solana Pay
|
||||
|
||||
Code for [Pointer Solana Pay Tutorial](pointer.gg/tutorials/solana-pay-irl-payments)
|
||||
|
||||
26
components/Confirmed.tsx
Normal file
26
components/Confirmed.tsx
Normal file
@ -0,0 +1,26 @@
|
||||
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/coupon-book.tsx
Normal file
54
components/coupon-book.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 bg-gray-900 text-white rounded-md p-1 items-center">
|
||||
<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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
6
lib/addresses.ts
Normal file
6
lib/addresses.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { PublicKey } from "@solana/web3.js"
|
||||
|
||||
// this is your shop wallet address
|
||||
export const shopAddress = new PublicKey('...')
|
||||
// this is the same for everyone!
|
||||
export const usdcAddress = new PublicKey('Gh9ZwEmdLJ8DscKNTkTqPbNwLNNBjuSzaG9Vp2KGtKJr')
|
||||
3820
package-lock.json
generated
3820
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,5 @@
|
||||
{
|
||||
"name": "solana-pay-tutorial",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@ -6,10 +7,13 @@
|
||||
"start": "next start"
|
||||
},
|
||||
"dependencies": {
|
||||
"@solana/pay": "^0.2.0",
|
||||
"@solana/spl-token": "^0.4.6",
|
||||
"@tailwindcss/forms": "^0.5.0",
|
||||
"bignumber.js": "^9.0.2",
|
||||
"next": "latest",
|
||||
"react": "^17.0.2",
|
||||
"react-circular-progressbar": "^2.1.0",
|
||||
"react-dom": "^17.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@ -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
|
||||
198
pages/api/makeTransaction.tsx
Normal file
198
pages/api/makeTransaction.tsx
Normal file
@ -0,0 +1,198 @@
|
||||
import { createTransferCheckedInstruction, getAssociatedTokenAddress, getMint, getOrCreateAssociatedTokenAccount } from "@solana/spl-token"
|
||||
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base"
|
||||
import { clusterApiUrl, Connection, Keypair, PublicKey, Transaction } from "@solana/web3.js"
|
||||
import { NextApiRequest, NextApiResponse } from "next"
|
||||
import { couponAddress, shopAddress, usdcAddress } from "../../lib/addresses"
|
||||
import calculatePrice from "../../lib/calculatePrice"
|
||||
import base58 from 'bs58'
|
||||
|
||||
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",
|
||||
})
|
||||
}
|
||||
|
||||
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 the buyer and seller coupon token accounts
|
||||
// Buyer one may not exist, so we create it (which costs SOL) as the shop account if it doesn't
|
||||
const buyerCouponAccount = await getOrCreateAssociatedTokenAccount(
|
||||
connection,
|
||||
shopKeypair, // shop pays the fee to create it
|
||||
couponAddress, // which token the account is for
|
||||
buyerPublicKey, // who the token account belongs to (the buyer)
|
||||
)
|
||||
|
||||
const shopCouponAddress = await getAssociatedTokenAddress(couponAddress, shopPublicKey)
|
||||
|
||||
// If the buyer has at least 5 coupons, they can use them and get a discount
|
||||
const buyerGetsCouponDiscount = buyerCouponAccount.amount >= 5
|
||||
|
||||
// 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,
|
||||
})
|
||||
|
||||
// If the buyer has the coupon discount, divide the amount in USDC by 2
|
||||
const amountToPay = buyerGetsCouponDiscount ? amount.dividedBy(2) : 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,
|
||||
})
|
||||
|
||||
// Create the instruction to send the coupon from the shop to the buyer
|
||||
const couponInstruction = buyerGetsCouponDiscount ?
|
||||
// The coupon instruction is to send 5 coupons from the buyer to the shop
|
||||
createTransferCheckedInstruction(
|
||||
buyerCouponAccount.address, // source account (coupons)
|
||||
couponAddress, // token address (coupons)
|
||||
shopCouponAddress, // destination account (coupons)
|
||||
buyerPublicKey, // owner of source account
|
||||
5, // amount to transfer
|
||||
0, // decimals of the token - we know this is 0
|
||||
) :
|
||||
// The coupon instruction is to send 1 coupon from the shop to the buyer
|
||||
createTransferCheckedInstruction(
|
||||
shopCouponAddress, // source account (coupon)
|
||||
couponAddress, // token address (coupon)
|
||||
buyerCouponAccount.address, // destination account (coupon)
|
||||
shopPublicKey, // owner of source account
|
||||
1, // amount to transfer
|
||||
0, // decimals of the token - we know this is 0
|
||||
)
|
||||
|
||||
// Add the shop as a signer to the coupon instruction
|
||||
// If the shop is sending a coupon, it already will be a signer
|
||||
// But if the buyer is sending the coupons, the shop won't be a signer automatically
|
||||
// It's useful security to have the shop sign the transaction
|
||||
couponInstruction.keys.push({
|
||||
pubkey: shopPublicKey,
|
||||
isSigner: true,
|
||||
isWritable: false,
|
||||
})
|
||||
|
||||
// Add both instructions to the transaction
|
||||
transaction.add(transferInstruction, couponInstruction)
|
||||
|
||||
// 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)
|
||||
|
||||
// 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 = buyerGetsCouponDiscount ? "50% Discount! 🍪" : "Thanks for your order! 🍪"
|
||||
|
||||
// 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,109 @@
|
||||
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 { useRouter } from "next/router";
|
||||
import BackLink from "../components/BackLink";
|
||||
import PageHeading from "../components/PageHeading";
|
||||
import calculatePrice from "../lib/calculatePrice";
|
||||
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()
|
||||
|
||||
const amount = calculatePrice(router.query)
|
||||
// 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: TransferRequestURLFields = {
|
||||
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 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 gap-8 items-center">
|
||||
<BackLink href='/'>Cancel</BackLink>
|
||||
<div className="flex flex-col items-center gap-8">
|
||||
<BackLink href='/shop'>Cancel</BackLink>
|
||||
|
||||
<PageHeading>Checkout {amount.toString()} SOL</PageHeading>
|
||||
<PageHeading>Checkout ${amount.toString()}</PageHeading>
|
||||
|
||||
{/* div added to display the QR code */}
|
||||
<div ref={qrRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
await validateTransfer(
|
||||
connection,
|
||||
signatureInfo.signature,
|
||||
{
|
||||
recipient: shopAddress,
|
||||
amount,
|
||||
splToken: usdcAddress,
|
||||
reference,
|
||||
},
|
||||
{ commitment: 'confirmed' }
|
||||
)
|
||||
|
||||
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 gap-8 items-center'>
|
||||
<BackLink href='/'>Home</BackLink>
|
||||
|
||||
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
|
||||
|
||||
<div className='h-80 w-80'><Confirmed /></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -1,12 +1,28 @@
|
||||
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">
|
||||
<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 */}
|
||||
{/* Also the submitTarget is /buy/transaction instead of /checkout */}
|
||||
<Products submitTarget='/checkout' enabled={publicKey !== null} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
106
pages/shop/checkout.tsx
Normal file
106
pages/shop/checkout.tsx
Normal file
@ -0,0 +1,106 @@
|
||||
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])
|
||||
|
||||
// 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() });
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get a connection to Solana devnet
|
||||
const network = WalletAdapterNetwork.Devnet
|
||||
const endpoint = clusterApiUrl(network)
|
||||
const connection = new Connection(endpoint)
|
||||
|
||||
// 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)
|
||||
}
|
||||
}, [])
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
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 gap-8 max-w-4xl items-stretch m-auto pt-24">
|
||||
<SiteHeading>Cookies Inc</SiteHeading>
|
||||
<Products submitTarget='/shop/checkout' enabled={true} /> </div>
|
||||
)
|
||||
}
|
||||
60
scripts/create-coupon.tsx
Normal file
60
scripts/create-coupon.tsx
Normal file
@ -0,0 +1,60 @@
|
||||
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(),
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"target": "es2017"17"17"17"17"17",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user