Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
legacy-peer-deps=true
19 changes: 19 additions & 0 deletions app/WagmiProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { WagmiProvider } from "wagmi";

import { config } from "@/lib/wagmi";

export function Providers(props: { children: ReactNode }) {
const [queryClient] = useState(() => new QueryClient());

return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</WagmiProvider>
);
}
33 changes: 21 additions & 12 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import "./globals.css"
import type { Metadata } from "next"
import { Fragment_Mono } from "next/font/google"
import ProviderWrapper from "@/components/dynamic-wrapper"
import { DynamicContextProvider, DynamicWagmiConnector } from "../lib/dynamic";
import { Providers } from "./WagmiProvider";

const fragment = Fragment_Mono({
subsets: ["latin"],
Expand All @@ -14,14 +15,22 @@ export const metadata: Metadata = {
"Here is something that we can do together. Let's make something cool!",
}

export default function RootLayout({ children }: React.PropsWithChildren) {
return (
<html lang="en">
<ProviderWrapper>
<body className={fragment.className}>
{children}
</body>
</ProviderWrapper>
</html>
)
}
export default function RootLayout({ children }: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<DynamicContextProvider
settings={{
environmentId: "XXXXX",
}}
>
<Providers>
<DynamicWagmiConnector>
<body className={fragment.className}>{children}</body>
</DynamicWagmiConnector>
</Providers>
</DynamicContextProvider>
</html>
);
}
4 changes: 2 additions & 2 deletions components/RightSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { bringElement, modifyShape } from "@/lib/shapes";

import Text from "./settings/Text";
import Color from "./settings/Color";
import Export from "./settings/Export";
import MintButton from "./settings/Export";
import Dimensions from "./settings/Dimensions";

const RightSidebar = ({
Expand Down Expand Up @@ -68,7 +68,7 @@ const RightSidebar = ({
handleInputChange={handleInputChange}
/> */}

<Export />
<MintButton />
<div className="text-xs text-primary-purple mt-3 p-4 px-5 border-b border-t border-slate-700">
<h3 className='text-[10px] uppercase'>Tips</h3>
<span>Press / to chat with your cursor
Expand Down
147 changes: 147 additions & 0 deletions components/mintToken.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"use client"
import { BaseError, Address } from "viem";
import html2canvas from 'html2canvas';
import pinataSDK from '@pinata/sdk';
import {
useAccount,
useChainId,
useSimulateContract,
useWriteContract,
useWaitForTransactionReceipt
} from 'wagmi';
import { useState, useCallback } from 'react';
import { zoraNftCreatorV1Config } from "@zoralabs/zora-721-contracts";

const tokenAddress = "0xa2fea3537915dc6c7c7a97a82d1236041e6feb2e";

const pinata = new pinataSDK('YOUR_PINATA_API_KEY', 'YOUR_PINATA_API_SECRET');

const captureWhiteboard = async (elementId: string): Promise<Blob | null> => {
const whiteboardElement = document.getElementById(elementId);
if (!whiteboardElement) {
throw new Error('Whiteboard element not found');
}

const canvas = await html2canvas(whiteboardElement);
return new Promise((resolve) => {
canvas.toBlob((blob) => {
if (blob) {
resolve(blob);
} else {
resolve(null);
}
}, 'image/png');
});
};

const uploadToIPFS = async (imageBlob: Blob): Promise<string> => {
const reader = new FileReader();
reader.readAsDataURL(imageBlob);
return new Promise((resolve, reject) => {
reader.onloadend = async () => {
const base64data = typeof reader.result === 'string' ? reader.result.split(',')[1] : '';
try {
const response = await fetch('/api/upload-to-ipfs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: base64data, filename: 'whiteboard.png' }),
});
const { ipfsHash } = await response.json();
resolve(ipfsHash);
} catch (error) {
reject(error);
}
};
});
};

const createMetadata = (imageHash: string) => ({
name: "Whiteboard Capture",
description: "A captured whiteboard session",
image: `ipfs://${imageHash}`
});

export const useMintToken = () => {
const { address } = useAccount();
const chainId = useChainId();

const [isMinting, setIsMinting] = useState(false);
const [metadataUri, setMetadataUri] = useState<string | null>(null);

const simulateResult = useSimulateContract({
address: zoraNftCreatorV1Config.address[chainId as keyof typeof zoraNftCreatorV1Config.address] as Address,
abi: zoraNftCreatorV1Config.abi,
functionName: "createDropWithReferral",
args: metadataUri ? [
"Playgotchi Playground Board", // contractName
"PPB", // symbol
address!, // defaultAdmin
BigInt(1), // editionSize
0, // royaltyBps
address!, // fundsRecipient
{
maxSalePurchasePerAddress: 4294967295,
presaleEnd: BigInt(0),
presaleStart: BigInt(0),
presaleMerkleRoot: "0x0000000000000000000000000000000000000000000000000000000000000000",
publicSaleEnd: BigInt("0xFFFFFFFFFFFFFFFF"),
publicSalePrice: BigInt(0),
publicSaleStart: BigInt(0),
},
"A captured Playgotchi Playground Board session", // description
metadataUri, // imageUri
"0x124F3eB5540BfF243c2B57504e0801E02696920E", // createReferral
] : undefined,
});

const { writeContract, data: writeData, error: writeError, isPending: isWritePending } = useWriteContract();

const { isLoading: isWaitLoading, isSuccess } = useWaitForTransactionReceipt({
hash: writeData,
});

const mintToken = useCallback(async (elementId: string) => {
if (!address) {
throw new Error('Wallet not connected');
}

setIsMinting(true);

try {
const blob = await captureWhiteboard(elementId);
if (!blob) throw new Error('Failed to capture whiteboard');

const imageHash = await uploadToIPFS(blob);
console.log(`Pinned image to IPFS: ${imageHash}`);

const metadata = createMetadata(imageHash);
const metadataContent = JSON.stringify(metadata);
const metadataBlob = new Blob([metadataContent], { type: 'application/json' });
const metadataHash = await uploadToIPFS(metadataBlob);
console.log(`Pinned metadata to IPFS: ${metadataHash}`);

setMetadataUri(`ipfs://${metadataHash}`);

if (simulateResult.data?.request) {
await writeContract(simulateResult.data.request);
} else {
throw new Error('Failed to simulate contract interaction');
}
} catch (error) {
console.error('Error minting token:', error);
} finally {
setIsMinting(false);
}
}, [address, simulateResult.data, writeContract]);

return {
mintToken,
isMinting,
isPending: isWritePending || isWaitLoading,
isSuccess,
isError: !!simulateResult.error || !!writeError,
error: (writeError as BaseError)?.shortMessage || (simulateResult.error as BaseError)?.shortMessage
};
};

export default useMintToken;
39 changes: 25 additions & 14 deletions components/settings/Export.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import { Button } from "@/components/ui/button";
import React from 'react';
import { useMintToken } from '../mintToken';

const MintButton: React.FC = () => {
const { mintToken, isMinting, isPending, isSuccess, isError, error } = useMintToken();

import { Button } from "@/components/ui/button";
const handleMint = () => {
mintToken('whiteboard-element-id'); // Replace with the actual ID of your whiteboard element
};

const Export = () => (
<div className='flex flex-col gap-3 px-5 py-3'>
<h3 className='text-[10px] uppercase'>Collect</h3>
<Button
variant='primary'
className='w-full'
onClick={() => {}}
>
Mint Button
</Button>
</div>
);
return (
<div className='flex flex-col gap-3 px-5 py-3'>
<h3 className='text-[10px] uppercase'>Collect</h3>
<Button
variant='primary'
className='w-full'
onClick={handleMint}
disabled={isMinting || isPending}
>
{isMinting || isPending ? 'Minting...' : 'Mint Button'}
</Button>
{isSuccess && <p className="text-green-500 mt-2">Token minted successfully!</p>}
{isError && <p className="text-red-500 mt-2">Error: {error}</p>}
</div>
);
};

export default Export;
export default MintButton;
26 changes: 26 additions & 0 deletions config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { baseSepolia } from "viem/chains";
import {
http,
custom,
createPublicClient,
createWalletClient,
Address,
} from "viem";

export const chain = baseSepolia;
export const chainId = baseSepolia.id;

export const publicClient = createPublicClient({
// this will determine which chain to interact with
chain: baseSepolia,
transport: http(),
});

export const walletClient = createWalletClient({
chain: baseSepolia,
transport: custom(window.ethereum!),
});

const [minterAccount] = (await walletClient.getAddresses()) as [Address];

export { minterAccount };
3 changes: 2 additions & 1 deletion lib/dynamic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"use client";

export * from "@dynamic-labs/sdk-react-core";
export * from "@dynamic-labs/ethereum";
export * from "@dynamic-labs/ethereum";
export * from "@dynamic-labs/wagmi-connector";
20 changes: 20 additions & 0 deletions lib/wagmi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// lib/wagmi.ts
import { http, createConfig } from "wagmi";
import { baseSepolia, base } from "wagmi/chains";

export const config = createConfig({
chains: [baseSepolia, base],
multiInjectedProviderDiscovery: false,
ssr: true,
transports: {
[baseSepolia.id]: http(),
[base.id]: http(),

},
});

declare module "wagmi" {
interface Register {
config: typeof config;
}
}
11 changes: 10 additions & 1 deletion next.config.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
webpack: (config) => {
webpack: (config, { isServer }) => {
config.externals.push({
"utf-8-validate": "commonjs utf-8-validate",
bufferutil: "commonjs bufferutil",
canvas: "commonjs canvas",
});

// Add the following fallback configuration
if (!isServer) {
config.resolve.fallback = {
fs: false,
// other fallbacks if needed
};
}

// config.infrastructureLogging = { debug: /PackFileCache/ };
return config;
},
Expand Down
Loading