Compare commits
8 Commits
start
...
5-coupon-v
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a829c8fde4 | ||
|
|
06ef584e1f | ||
|
|
febfcc924c | ||
|
|
90ff207cf5 | ||
|
|
d558dcf81d | ||
|
|
fcacb149c8 | ||
|
|
68f38544a4 | ||
|
|
1e5e21aff9 |
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)
|
||||
|
||||
@ -2,6 +2,7 @@ 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('🍪')
|
||||
@ -23,4 +24,4 @@ export default function Confirmed() {
|
||||
})
|
||||
} />
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -41,7 +41,7 @@ export default function CouponBook() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col bg-gray-900 text-white rounded-md p-1 items-center">
|
||||
<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">
|
||||
@ -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
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
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')
|
||||
// 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))
|
||||
}
|
||||
|
||||
5770
package-lock.json
generated
5770
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
@ -4,22 +4,33 @@
|
||||
"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": {
|
||||
"@solana/pay": "^0.2.0",
|
||||
"@solana/spl-token": "^0.4.6",
|
||||
"@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.1.0",
|
||||
"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",
|
||||
|
||||
@ -1,109 +1,137 @@
|
||||
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 { 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, 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 findReference(connection, reference);
|
||||
router.push('/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])
|
||||
}, [])
|
||||
|
||||
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 items-center gap-8">
|
||||
<BackLink href='/shop'>Cancel</BackLink>
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<div><BackLink href='/'>Cancel</BackLink></div>
|
||||
|
||||
<PageHeading>Checkout ${amount.toString()}</PageHeading>
|
||||
<WalletMultiButton />
|
||||
|
||||
{/* div added to display the QR code */}
|
||||
<div ref={qrRef} />
|
||||
{message ?
|
||||
<p>{message} Please approve the transaction using your wallet</p> :
|
||||
<p>Creating transaction... <Loading /></p>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
await validateTransfer(
|
||||
connection,
|
||||
signatureInfo.signature,
|
||||
{
|
||||
recipient: shopAddress,
|
||||
amount,
|
||||
splToken: usdcAddress,
|
||||
reference,
|
||||
},
|
||||
{ commitment: 'confirmed' }
|
||||
)
|
||||
}
|
||||
@ -4,7 +4,7 @@ import PageHeading from '../components/PageHeading';
|
||||
|
||||
export default function ConfirmedPage() {
|
||||
return (
|
||||
<div className='flex flex-col gap-8 items-center'>
|
||||
<div className='flex flex-col items-center gap-8'>
|
||||
<BackLink href='/'>Home</BackLink>
|
||||
|
||||
<PageHeading>Thankyou, enjoy your cookies!</PageHeading>
|
||||
|
||||
@ -9,7 +9,7 @@ export default function HomePage() {
|
||||
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>
|
||||
|
||||
{/* We add the Solana wallet connect button */}
|
||||
@ -21,8 +21,7 @@ export default function HomePage() {
|
||||
{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>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -16,11 +16,8 @@ export default function Checkout() {
|
||||
|
||||
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,11 +30,27 @@ 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());
|
||||
|
||||
// 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
|
||||
@ -91,7 +104,7 @@ export default function Checkout() {
|
||||
return () => {
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [])
|
||||
}, [amount])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-8">
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
@ -3,7 +3,7 @@ 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">
|
||||
<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>
|
||||
)
|
||||
|
||||
@ -56,5 +56,4 @@ 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"
|
||||
}
|
||||
@ -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