Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
430115cf2b | ||
|
|
80c6b6a793 | ||
|
|
eb2d49c4e6 | ||
|
|
2996121187 | ||
|
|
cd6fd9a75d | ||
|
|
12c42c0311 | ||
|
|
5e11d63e11 | ||
|
|
1d6e98dafd | ||
|
|
c077f78e3a | ||
|
|
6b7983f47c | ||
|
|
859290f6c7 | ||
|
|
adec6be844 | ||
|
|
c80eed3552 | ||
|
|
0c7051b999 | ||
|
|
3c8e444fe6 | ||
|
|
367a25ca5a | ||
|
|
c0ffa1c871 | ||
|
|
36731096b9 | ||
|
|
1607229b21 | ||
|
|
75bf09126f | ||
|
|
9d8c7f1f7d | ||
|
|
9dc8f5a637 | ||
|
|
48361f92b7 | ||
|
|
1659ae3754 | ||
|
|
88d44aff50 | ||
|
|
c63b3497bd | ||
|
|
74a21635e4 | ||
|
|
66b9bf3c6b | ||
|
|
cf22c23b45 |
@@ -18,8 +18,8 @@
|
||||
## Features
|
||||
|
||||
- Support for React & React-Native
|
||||
- First party support for [Embedded Wallets](https://portal.thirdweb.com/connect/embedded-wallet/overview) (social/email login)
|
||||
- First party support for [Account Abstraction](https://portal.thirdweb.com/connect/account-abstraction/overview)
|
||||
- First party support for [Embedded Wallets](https://portal.thirdweb.com/wallets) (social/email login)
|
||||
- First party support for [Account Abstraction](https://portal.thirdweb.com/wallets/sponsor-gas)
|
||||
- Instant connection to any chain with RPC Edge integration
|
||||
- Integrated IPFS upload/download
|
||||
- UI Components for connection, transactions, nft rendering
|
||||
|
||||
@@ -34,7 +34,6 @@
|
||||
"@vercel/functions": "2.2.2",
|
||||
"@vercel/og": "^0.6.8",
|
||||
"abitype": "1.0.8",
|
||||
"chakra-react-select": "^4.7.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"color": "5.0.0",
|
||||
@@ -57,7 +56,7 @@
|
||||
"posthog-js": "1.256.1",
|
||||
"posthog-node": "^5.4.0",
|
||||
"prettier": "3.6.2",
|
||||
"qrcode": "^1.5.3",
|
||||
"qrcode": "1.5.3",
|
||||
"react": "19.1.0",
|
||||
"react-children-utilities": "^2.10.0",
|
||||
"react-day-picker": "^8.10.1",
|
||||
@@ -99,7 +98,7 @@
|
||||
"@types/node": "22.14.1",
|
||||
"@types/papaparse": "^5.3.16",
|
||||
"@types/pluralize": "^0.0.33",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/qrcode": "1.5.5",
|
||||
"@types/react": "19.1.8",
|
||||
"@types/react-dom": "19.1.6",
|
||||
"@types/react-table": "^7.7.20",
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
name,description,image,animation_url,external_url,background_color,youtube_url,additional,properties,can be,added
|
||||
Token 0 Name,Token 0 Description,ipfs://ipfsHash/0,ipfs://ipfsHash/0,https://thirdweb.com,#0098EE,,every,row,is a ,property
|
||||
|
@@ -1,4 +0,0 @@
|
||||
name,description,image,animation_url,external_url,background_color,youtube_url,additional,properties,can be,added
|
||||
Token 0 Name,Token 0 Description,0.png,0.mp4,https://thirdweb.com,#0098EE,,every,row,is a ,property
|
||||
Token 1 Name,Token 1 Description,0.png,0.mp4,https://thirdweb.com,#0098EE,,every,row,is a ,property
|
||||
Token 2 Name,Token 2 Description,0.png,0.mp4,https://thirdweb.com,#0098EE,,every,row,is a ,property
|
||||
|
@@ -1,2 +0,0 @@
|
||||
name,description,external_url,background_color,youtube_url,additional,properties,can be,added
|
||||
Token 0 Name,Token 0 Description,https://thirdweb.com,#0098EE,,every,row,is a ,property
|
||||
|
@@ -66,15 +66,20 @@ const projectRoute = "/team/:team_slug/:project_slug";
|
||||
|
||||
const projectPageRedirects = [
|
||||
{
|
||||
destination: `${projectRoute}/universal-bridge/:path*`,
|
||||
destination: `${projectRoute}/payments/:path*`,
|
||||
permanent: false,
|
||||
source: `${projectRoute}/connect/pay/:path*`,
|
||||
},
|
||||
{
|
||||
destination: `${projectRoute}/universal-bridge/:path*`,
|
||||
destination: `${projectRoute}/payments/:path*`,
|
||||
permanent: false,
|
||||
source: `${projectRoute}/connect/universal-bridge/:path*`,
|
||||
},
|
||||
{
|
||||
destination: `${projectRoute}/payments/:path*`,
|
||||
permanent: false,
|
||||
source: `${projectRoute}/universal-bridge/:path*`,
|
||||
},
|
||||
{
|
||||
destination: `${projectRoute}/account-abstraction/:path*`,
|
||||
permanent: false,
|
||||
@@ -375,12 +380,22 @@ async function redirects() {
|
||||
permanent: false,
|
||||
source: "/template/:slug",
|
||||
},
|
||||
// redirect /connect/pay to /universal-bridge
|
||||
// redirect /connect/pay to /payments
|
||||
{
|
||||
destination: "/universal-bridge",
|
||||
permanent: false,
|
||||
destination: "/payments",
|
||||
permanent: true,
|
||||
source: "/connect/pay",
|
||||
},
|
||||
{
|
||||
destination: "/payments",
|
||||
permanent: true,
|
||||
source: "/universal-bridge",
|
||||
},
|
||||
{
|
||||
destination: "/payments/:slug",
|
||||
permanent: true,
|
||||
source: "/universal-bridge/:slug",
|
||||
},
|
||||
// PREVIOUS CAMPAIGNS
|
||||
{
|
||||
destination: "/",
|
||||
|
||||
@@ -413,3 +413,18 @@ export function reportUpsellShown(properties: UpsellParams) {
|
||||
export function reportUpsellClicked(properties: UpsellParams) {
|
||||
posthog.capture("upsell clicked", properties);
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
// PAYMENTS
|
||||
// ----------------------------
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track conversions on payment overview page
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @samina
|
||||
*/
|
||||
export function reportPaymentCardClick(properties: { id: string }) {
|
||||
posthog.capture("payment card clicked", properties);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
AlertIcon,
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
InputGroup,
|
||||
InputRightElement,
|
||||
Textarea,
|
||||
} from "@chakra-ui/react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { ChevronLeftIcon, EyeIcon, EyeOffIcon } from "lucide-react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useDropzone } from "react-dropzone";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
EyeIcon,
|
||||
EyeOffIcon,
|
||||
HelpCircleIcon,
|
||||
LockKeyholeIcon,
|
||||
RefreshCcwIcon,
|
||||
ShuffleIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { CreateDelayedRevealBatchParams } from "thirdweb/extensions/erc721";
|
||||
@@ -25,12 +20,14 @@ import type { NFTInput } from "thirdweb/utils";
|
||||
import { z } from "zod";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Checkbox, CheckboxWithLabel } from "@/components/ui/checkbox";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import type { ComponentWithChildren } from "@/types/component-with-children";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Form, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { processInputData, shuffleData } from "@/utils/batch";
|
||||
import { TabButtons } from "../ui/tabs";
|
||||
import { BatchTable } from "./batch-table";
|
||||
import { SelectOption } from "./lazy-mint-form/select-option";
|
||||
import { UploadStep } from "./upload-step";
|
||||
|
||||
type DelayedSubmit = {
|
||||
@@ -44,16 +41,6 @@ type InstantSubmit = {
|
||||
|
||||
type SubmitType = DelayedSubmit | InstantSubmit;
|
||||
|
||||
interface BatchLazyMintEVMProps {
|
||||
nextTokenIdToMint: bigint;
|
||||
canCreateDelayedRevealBatch: boolean;
|
||||
onSubmit: (formData: SubmitType) => Promise<unknown>;
|
||||
chainId: number;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
type BatchLazyMintProps = BatchLazyMintEVMProps;
|
||||
|
||||
const BatchLazyMintFormSchema = z
|
||||
.object({
|
||||
confirmPassword: z
|
||||
@@ -73,7 +60,7 @@ const BatchLazyMintFormSchema = z
|
||||
name: z.string().min(1, "A name is required"),
|
||||
})
|
||||
.optional(),
|
||||
revealType: z.literal("instant").or(z.literal("delayed")).optional(),
|
||||
revealType: z.literal("instant").or(z.literal("delayed")),
|
||||
|
||||
// shared logic
|
||||
shuffle: z.boolean().default(false),
|
||||
@@ -91,18 +78,21 @@ function useBatchLazyMintForm() {
|
||||
return useForm<BatchLazyMintFormType>({
|
||||
defaultValues: {
|
||||
metadatas: [],
|
||||
revealType: undefined,
|
||||
revealType: "instant",
|
||||
shuffle: false,
|
||||
},
|
||||
resolver: zodResolver(BatchLazyMintFormSchema),
|
||||
});
|
||||
}
|
||||
|
||||
export const BatchLazyMint: ComponentWithChildren<
|
||||
BatchLazyMintProps & {
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
> = (props) => {
|
||||
export function BatchLazyMint(props: {
|
||||
nextTokenIdToMint: bigint;
|
||||
canCreateDelayedRevealBatch: boolean;
|
||||
onSubmit: (formData: SubmitType) => Promise<unknown>;
|
||||
chainId: number;
|
||||
client: ThirdwebClient;
|
||||
isLoggedIn: boolean;
|
||||
}) {
|
||||
const [step, setStep] = useState(0);
|
||||
|
||||
const form = useBatchLazyMintForm();
|
||||
@@ -110,369 +100,415 @@ export const BatchLazyMint: ComponentWithChildren<
|
||||
const nftMetadatas = form.watch("metadatas");
|
||||
const hasError = !!form.getFieldState("metadatas", form.formState).error;
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop: async (acceptedFiles) => {
|
||||
try {
|
||||
await processInputData(acceptedFiles, (data) =>
|
||||
form.setValue("metadatas", data),
|
||||
);
|
||||
} catch {
|
||||
form.setError("metadatas", {
|
||||
message: "Invalid metadata files",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
|
||||
if (nftMetadatas.length === 0) {
|
||||
form.setError("metadatas", {
|
||||
message: "Invalid metadata files",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const paginationPortalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="mt-4 flex w-full flex-col"
|
||||
onSubmit={form.handleSubmit((data) => {
|
||||
// first shuffle
|
||||
const shuffledMetadatas = data.shuffle
|
||||
? shuffleData(data.metadatas)
|
||||
: data.metadatas;
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="mt-4 flex w-full flex-col"
|
||||
onSubmit={form.handleSubmit(async (data) => {
|
||||
// first shuffle
|
||||
const shuffledMetadatas = data.shuffle
|
||||
? shuffleData(data.metadatas)
|
||||
: data.metadatas;
|
||||
|
||||
// check submit is instant
|
||||
if (data.revealType === "instant") {
|
||||
return props.onSubmit({
|
||||
data: { metadatas: shuffledMetadatas },
|
||||
revealType: "instant",
|
||||
});
|
||||
}
|
||||
// validate password
|
||||
if (!data.password) {
|
||||
form.setError("password", {
|
||||
message: "A password is required for delayed reveal.",
|
||||
type: "validate",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// validate placeholder
|
||||
if (!data.placeHolder?.name) {
|
||||
form.setError("placeHolder.name", {
|
||||
message: "A name is required for delayed reveal.",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
// submit
|
||||
return props.onSubmit({
|
||||
data: {
|
||||
metadata: shuffledMetadatas,
|
||||
password: data.password,
|
||||
placeholderMetadata: {
|
||||
description: data.placeHolder?.description,
|
||||
image: data.placeHolder?.image,
|
||||
name: data.placeHolder?.name,
|
||||
// check submit is instant
|
||||
if (data.revealType === "instant") {
|
||||
return props.onSubmit({
|
||||
data: { metadatas: shuffledMetadatas },
|
||||
revealType: "instant",
|
||||
});
|
||||
}
|
||||
// validate password
|
||||
if (!data.password) {
|
||||
form.setError("password", {
|
||||
message: "A password is required for delayed reveal.",
|
||||
type: "validate",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// validate placeholder
|
||||
if (!data.placeHolder?.name) {
|
||||
form.setError("placeHolder.name", {
|
||||
message: "A name is required for delayed reveal.",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
// submit
|
||||
await props.onSubmit({
|
||||
data: {
|
||||
metadata: shuffledMetadatas,
|
||||
password: data.password,
|
||||
placeholderMetadata: {
|
||||
description: data.placeHolder?.description,
|
||||
image: data.placeHolder?.image,
|
||||
name: data.placeHolder?.name,
|
||||
},
|
||||
},
|
||||
},
|
||||
revealType: "delayed",
|
||||
});
|
||||
})}
|
||||
>
|
||||
{step === 0 ? (
|
||||
<div className="flex flex-col gap-6">
|
||||
{nftMetadatas.length > 0 ? (
|
||||
<>
|
||||
<BatchTable
|
||||
client={props.client}
|
||||
data={nftMetadatas}
|
||||
nextTokenIdToMint={props.nextTokenIdToMint}
|
||||
portalRef={paginationPortalRef}
|
||||
/>
|
||||
<div className="border-border border-t">
|
||||
<div className="flex flex-col items-center justify-between p-0 md:flex-row md:p-4">
|
||||
<div ref={paginationPortalRef} />
|
||||
<div className="mt-4 flex w-full flex-row items-center gap-2 md:mt-0 md:w-auto">
|
||||
<Button
|
||||
borderRadius="md"
|
||||
isDisabled={!hasError}
|
||||
onClick={() => {
|
||||
form.reset();
|
||||
}}
|
||||
w={{ base: "100%", md: "auto" }}
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
borderRadius="md"
|
||||
colorScheme="primary"
|
||||
onClick={() => setStep(1)}
|
||||
w={{ base: "100%", md: "auto" }}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
revealType: "delayed",
|
||||
});
|
||||
})}
|
||||
>
|
||||
{step === 0 ? (
|
||||
<div>
|
||||
{nftMetadatas.length > 0 ? (
|
||||
<div className="pb-10">
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-4">
|
||||
Upload NFTs
|
||||
</h2>
|
||||
|
||||
<BatchTable
|
||||
client={props.client}
|
||||
data={nftMetadatas}
|
||||
nextTokenIdToMint={props.nextTokenIdToMint}
|
||||
/>
|
||||
<div className="mt-5 flex justify-end gap-4">
|
||||
<Button
|
||||
className="w-full md:w-auto gap-2"
|
||||
disabled={!hasError}
|
||||
onClick={() => {
|
||||
form.reset();
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
<RefreshCcwIcon className="size-4" />
|
||||
Reset
|
||||
</Button>
|
||||
<Button
|
||||
className="w-full md:w-auto gap-2"
|
||||
onClick={() => setStep(1)}
|
||||
>
|
||||
Next <ArrowRightIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<UploadStep
|
||||
getInputProps={getInputProps}
|
||||
getRootProps={getRootProps}
|
||||
hasFailed={hasError}
|
||||
isDragActive={isDragActive}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Flex align="center" justify="space-between" mb={2} py={4} w="100%">
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
) : (
|
||||
<UploadStep
|
||||
hasFailed={hasError}
|
||||
reset={() => {
|
||||
form.reset();
|
||||
}}
|
||||
onDrop={async (acceptedFiles) => {
|
||||
try {
|
||||
await processInputData(acceptedFiles, (data) =>
|
||||
form.setValue("metadatas", data),
|
||||
);
|
||||
} catch {
|
||||
form.setError("metadatas", {
|
||||
message: "Invalid metadata files",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
|
||||
if (nftMetadatas.length === 0) {
|
||||
form.setError("metadatas", {
|
||||
message: "Invalid metadata files",
|
||||
type: "validate",
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="container px-0 max-w-4xl pb-14">
|
||||
<div className="flex mb-3">
|
||||
<Button
|
||||
className="text-muted-foreground"
|
||||
className="gap-2 -translate-x-3 text-muted-foreground"
|
||||
size="sm"
|
||||
onClick={() => setStep(0)}
|
||||
variant="ghost"
|
||||
>
|
||||
<ChevronLeftIcon className="size-5 cursor-pointer" />
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
Back
|
||||
</Button>
|
||||
<Heading className="my-auto" size="title.md">
|
||||
When will you reveal your NFTs?
|
||||
</Heading>
|
||||
</div>
|
||||
</Flex>
|
||||
<SelectReveal
|
||||
canCreateDelayedRevealBatch={props.canCreateDelayedRevealBatch}
|
||||
client={props.client}
|
||||
form={form}
|
||||
/>
|
||||
{form.watch("revealType") && (
|
||||
<>
|
||||
<CheckboxWithLabel>
|
||||
<Checkbox
|
||||
checked={form.watch("shuffle")}
|
||||
className="mt-3"
|
||||
onCheckedChange={(val) => form.setValue("shuffle", !!val)}
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-1 md:flex-row">
|
||||
<p>Shuffle the order of the NFTs before uploading.</p>
|
||||
<em>This is an off-chain operation and is not provable.</em>
|
||||
</div>
|
||||
</CheckboxWithLabel>
|
||||
<div className="w-full md:w-[61%]">
|
||||
<TransactionButton
|
||||
className="mt-4 w-full"
|
||||
client={props.client}
|
||||
disabled={!nftMetadatas.length}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={form.formState.isSubmitting}
|
||||
transactionCount={1}
|
||||
txChainID={props.chainId}
|
||||
type="submit"
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? `Uploading ${nftMetadatas.length} NFTs`
|
||||
: `Upload ${nftMetadatas.length} NFTs`}
|
||||
</TransactionButton>
|
||||
{props.children}
|
||||
</div>
|
||||
<Text mt={2} size="body.sm">
|
||||
<UnderlineLink
|
||||
className="text-primary-500"
|
||||
href="https://support.thirdweb.com/dashboard/n5evQ4EfEjEifczEQaZ1hL/batch-upload-troubleshooting/5WMQFqfaUTU1C8NM8FtJ2X"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Experiencing issues uploading your files?
|
||||
</UnderlineLink>
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
interface SelectRevealProps {
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-4">
|
||||
Upload NFTs
|
||||
</h2>
|
||||
|
||||
<SelectReveal
|
||||
canCreateDelayedRevealBatch={props.canCreateDelayedRevealBatch}
|
||||
client={props.client}
|
||||
form={form}
|
||||
/>
|
||||
|
||||
<div className="h-4" />
|
||||
|
||||
<div className="space-y-6">
|
||||
{form.watch("revealType") === "delayed" && (
|
||||
<DelayedRevealConfiguration client={props.client} form={form} />
|
||||
)}
|
||||
|
||||
{/* shuffle */}
|
||||
<ShuffleNFTsCard
|
||||
isShuffleEnabled={form.watch("shuffle")}
|
||||
onShuffleChange={(val) => form.setValue("shuffle", val)}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-end">
|
||||
<TransactionButton
|
||||
client={props.client}
|
||||
disabled={!nftMetadatas.length}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={form.formState.isSubmitting}
|
||||
transactionCount={1}
|
||||
txChainID={props.chainId}
|
||||
type="submit"
|
||||
>
|
||||
{form.formState.isSubmitting
|
||||
? `Uploading ${nftMetadatas.length} NFTs`
|
||||
: `Upload ${nftMetadatas.length} NFTs`}
|
||||
</TransactionButton>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Link
|
||||
className="text-sm flex items-center gap-2 text-muted-foreground hover:text-foreground"
|
||||
href="https://portal.thirdweb.com/knowledge-base/troubleshoot/contracts/batch-upload"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
<HelpCircleIcon className="size-4" />
|
||||
Experiencing issues uploading your files?
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function ShuffleNFTsCard(props: {
|
||||
isShuffleEnabled: boolean;
|
||||
onShuffleChange: (val: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="px-4 lg:px-6 py-8 border rounded-lg bg-card relative">
|
||||
<div className="flex mb-3">
|
||||
<div className="p-2 rounded-full border bg-card">
|
||||
<ShuffleIcon className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 className="font-semibold text-lg mb-0.5 tracking-tight">
|
||||
Shuffle NFTs
|
||||
</h3>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Shuffle the order of the NFTs before uploading. This is an off-chain
|
||||
operation and is not provable
|
||||
</p>
|
||||
|
||||
<Switch
|
||||
checked={props.isShuffleEnabled}
|
||||
onCheckedChange={(val) => props.onShuffleChange(!!val)}
|
||||
className="absolute right-4 top-4 lg:right-6 lg:top-8"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectReveal(props: {
|
||||
form: ReturnType<typeof useBatchLazyMintForm>;
|
||||
canCreateDelayedRevealBatch: boolean;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const { form, canCreateDelayedRevealBatch } = props;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{canCreateDelayedRevealBatch && (
|
||||
<TabButtons
|
||||
containerClassName="mb-8"
|
||||
tabClassName="!text-sm"
|
||||
tabs={[
|
||||
{
|
||||
name: "Reveal upon mint",
|
||||
onClick: () => {
|
||||
form.setValue("revealType", "instant");
|
||||
// reset all fields related to delayed reveal
|
||||
form.resetField("password");
|
||||
form.resetField("confirmPassword");
|
||||
form.resetField("placeHolder");
|
||||
},
|
||||
isActive: form.watch("revealType") === "instant",
|
||||
},
|
||||
{
|
||||
name: "Delayed Reveal",
|
||||
onClick: () => form.setValue("revealType", "delayed"),
|
||||
isActive: form.watch("revealType") === "delayed",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
{form.watch("revealType") === "instant" && (
|
||||
<div>
|
||||
<h2 className="font-semibold text-xl mb-1 tracking-tight leading-none">
|
||||
Reveal upon mint
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Collectors will immediately see the final NFT when they complete the
|
||||
minting
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{form.watch("revealType") === "delayed" && (
|
||||
<div>
|
||||
<h2 className="font-semibold text-xl mb-1 tracking-tight leading-none">
|
||||
Delayed Reveal
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Collectors will mint your placeholder image, then you reveal at a
|
||||
later time
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SelectReveal: React.FC<SelectRevealProps> = ({
|
||||
form,
|
||||
client,
|
||||
canCreateDelayedRevealBatch,
|
||||
}) => {
|
||||
function DelayedRevealConfiguration(props: {
|
||||
form: ReturnType<typeof useBatchLazyMintForm>;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const { form, client } = props;
|
||||
const [show, setShow] = useState(false);
|
||||
|
||||
const imageUrl = form.watch("placeHolder.image");
|
||||
|
||||
return (
|
||||
<Flex flexDir="column">
|
||||
<Flex
|
||||
flexDir={{ base: "column", md: "row" }}
|
||||
gap={{ base: 3, md: 6 }}
|
||||
mb={6}
|
||||
>
|
||||
<SelectOption
|
||||
description="Collectors will immediately see the final NFT when they complete the minting"
|
||||
isActive={form.watch("revealType") === "instant"}
|
||||
name="Reveal upon mint"
|
||||
onClick={() => form.setValue("revealType", "instant")}
|
||||
/>
|
||||
<SelectOption
|
||||
description="Collectors will mint your placeholder image, then you reveal at a later time"
|
||||
disabled={!canCreateDelayedRevealBatch}
|
||||
disabledText="This contract doesn't implement Delayed Reveal"
|
||||
isActive={form.watch("revealType") === "delayed"}
|
||||
name="Delayed Reveal"
|
||||
onClick={() => form.setValue("revealType", "delayed")}
|
||||
/>
|
||||
</Flex>
|
||||
<div className="flex flex-col gap-3">
|
||||
{form.watch("revealType") === "delayed" && (
|
||||
<>
|
||||
<Heading size="title.sm">Let's set a password</Heading>
|
||||
<Alert borderRadius="lg" status="warning">
|
||||
<AlertIcon />
|
||||
You'll need this password to reveal your NFTs. Please save it
|
||||
somewhere safe.
|
||||
</Alert>
|
||||
<div className="space-y-6">
|
||||
{/* password */}
|
||||
<div className="border px-4 lg:px-6 py-8 rounded-lg bg-card">
|
||||
<div className="flex mb-3">
|
||||
<div className="p-2 rounded-full border bg-card">
|
||||
<LockKeyholeIcon className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg mb-0.5 tracking-tight">
|
||||
Set password
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
You'll need this password to reveal your NFTs. Please save it
|
||||
somewhere safe
|
||||
</p>
|
||||
|
||||
<Flex
|
||||
flexDir={{ base: "column", md: "row" }}
|
||||
gap={{ base: 4, md: 0 }}
|
||||
>
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState("password", form.formState).error
|
||||
}
|
||||
isRequired
|
||||
mr={4}
|
||||
<div className="space-y-5">
|
||||
{/* select password */}
|
||||
<FormItem className="space-y-1">
|
||||
<FormLabel>Password</FormLabel>
|
||||
<div className="relative max-w-md">
|
||||
<Input
|
||||
{...form.register("password")}
|
||||
className="pr-10"
|
||||
type={show ? "text" : "password"}
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 h-auto text-muted-foreground"
|
||||
onClick={() => setShow(!show)}
|
||||
>
|
||||
<FormLabel>Password</FormLabel>
|
||||
<InputGroup>
|
||||
<Input
|
||||
{...form.register("password")}
|
||||
placeholder="Choose password"
|
||||
type={show ? "text" : "password"}
|
||||
/>
|
||||
<InputRightElement cursor="pointer">
|
||||
{show ? (
|
||||
<EyeIcon
|
||||
className="size-3"
|
||||
onClick={() => setShow(!show)}
|
||||
/>
|
||||
) : (
|
||||
<EyeOffIcon
|
||||
className="size-3"
|
||||
onClick={() => setShow(!show)}
|
||||
/>
|
||||
)}
|
||||
</InputRightElement>
|
||||
</InputGroup>
|
||||
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState("password", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState("confirmPassword", form.formState).error
|
||||
}
|
||||
isRequired
|
||||
>
|
||||
<FormLabel>Confirm password</FormLabel>
|
||||
<Input
|
||||
{...form.register("confirmPassword")}
|
||||
placeholder="Confirm password"
|
||||
type="password"
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState("confirmPassword", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</Flex>
|
||||
<div className="flex flex-col gap-5">
|
||||
<Heading size="title.sm">Placeholder</Heading>
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState("placeHolder.image", form.formState)
|
||||
.error
|
||||
}
|
||||
>
|
||||
<FormLabel>Image</FormLabel>
|
||||
<div className="w-auto md:w-[350px]">
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border border-border transition-all duration-200"
|
||||
client={client}
|
||||
setValue={(file) =>
|
||||
form.setValue("placeHolder.image", file)
|
||||
}
|
||||
showUploadButton
|
||||
value={imageUrl}
|
||||
/>
|
||||
</div>
|
||||
<FormHelperText>
|
||||
You can optionally upload an image as the placeholder.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState("placeHolder.image", form.formState)
|
||||
.error?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState("placeHolder.name", form.formState).error
|
||||
}
|
||||
isRequired
|
||||
>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input
|
||||
{...form.register("placeHolder.name")}
|
||||
placeholder="eg. My NFT (Coming soon)"
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState("placeHolder.name", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState("placeHolder.name", form.formState).error
|
||||
}
|
||||
>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<Textarea
|
||||
{...form.register("placeHolder.description")}
|
||||
placeholder="eg. Reveal on July 15th!"
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState(
|
||||
"placeHolder.description",
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
{show ? (
|
||||
<EyeIcon className="size-4" />
|
||||
) : (
|
||||
<EyeOffIcon className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<FormMessage>
|
||||
{form.getFieldState("password", form.formState).error?.message}
|
||||
</FormMessage>
|
||||
</FormItem>
|
||||
|
||||
{/* confirm password */}
|
||||
<FormItem className="space-y-1">
|
||||
<FormLabel>Confirm password</FormLabel>
|
||||
<div className="relative max-w-md">
|
||||
<Input
|
||||
{...form.register("confirmPassword")}
|
||||
className="pr-10"
|
||||
type="password"
|
||||
/>
|
||||
</div>
|
||||
<FormMessage>
|
||||
{
|
||||
form.getFieldState("confirmPassword", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormMessage>
|
||||
</FormItem>
|
||||
</div>
|
||||
</div>
|
||||
</Flex>
|
||||
|
||||
{/* placeholder */}
|
||||
<div className="border px-4 lg:px-6 py-8 rounded-lg bg-card">
|
||||
<div className="flex mb-3">
|
||||
<div className="p-2 rounded-full border bg-card">
|
||||
<EyeIcon className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg tracking-tight mb-0.5">
|
||||
Set placeholder metadata
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
The placeholder metadata will be displayed for all NFTs until you
|
||||
reveal your NFTs
|
||||
</p>
|
||||
<div className="flex flex-col lg:flex-row gap-5">
|
||||
<FormItem className="w-[200px]">
|
||||
<FormLabel>Image</FormLabel>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border bg-background transition-all duration-200 "
|
||||
client={client}
|
||||
setValue={(file) => form.setValue("placeHolder.image", file)}
|
||||
value={imageUrl}
|
||||
/>
|
||||
|
||||
<FormMessage>
|
||||
{
|
||||
form.getFieldState("placeHolder.image", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormMessage>
|
||||
</FormItem>
|
||||
<div className="grow space-y-5 flex flex-col">
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input
|
||||
className="max-w-sm"
|
||||
{...form.register("placeHolder.name")}
|
||||
placeholder="My NFT (Coming soon)"
|
||||
/>
|
||||
<FormMessage>
|
||||
{
|
||||
form.getFieldState("placeHolder.name", form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormMessage>
|
||||
</FormItem>
|
||||
<FormItem className="grow flex flex-col">
|
||||
<FormLabel>Description</FormLabel>
|
||||
<Textarea
|
||||
{...form.register("placeHolder.description")}
|
||||
className="grow"
|
||||
placeholder="Reveal on July 15th!"
|
||||
/>
|
||||
<FormMessage>
|
||||
{
|
||||
form.getFieldState("placeHolder.description", form.formState)
|
||||
.error?.message
|
||||
}
|
||||
</FormMessage>
|
||||
</FormItem>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,237 +1,183 @@
|
||||
/** biome-ignore-all lint/nursery/noNestedComponentDefinitions: FIXME */
|
||||
|
||||
import { FilePreview } from "@app/team/[team_slug]/[project_slug]/(sidebar)/tokens/create/_common/file-preview";
|
||||
import {
|
||||
Flex,
|
||||
IconButton,
|
||||
Portal,
|
||||
Select,
|
||||
Table,
|
||||
TableContainer,
|
||||
Tbody,
|
||||
Td,
|
||||
Th,
|
||||
Thead,
|
||||
Tr,
|
||||
} from "@chakra-ui/react";
|
||||
import {
|
||||
ChevronFirstIcon,
|
||||
ChevronLastIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import { type Column, usePagination, useTable } from "react-table";
|
||||
import { useState } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { NFTInput } from "thirdweb/utils";
|
||||
import { FilePreview } from "@/components/blocks/file-preview";
|
||||
import { PaginationButtons } from "@/components/blocks/pagination-buttons";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
|
||||
interface BatchTableProps {
|
||||
type BatchTableProps = {
|
||||
data: NFTInput[];
|
||||
portalRef: React.RefObject<HTMLDivElement | null>;
|
||||
nextTokenIdToMint?: bigint;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
};
|
||||
|
||||
export const BatchTable: React.FC<BatchTableProps> = ({
|
||||
export function BatchTable({
|
||||
data,
|
||||
portalRef,
|
||||
nextTokenIdToMint,
|
||||
client,
|
||||
}) => {
|
||||
const columns = useMemo(() => {
|
||||
let cols: Column<NFTInput>[] = [];
|
||||
if (nextTokenIdToMint !== undefined) {
|
||||
cols = cols.concat({
|
||||
accessor: (_row, index) => String(nextTokenIdToMint + BigInt(index)),
|
||||
Header: "Token ID",
|
||||
});
|
||||
}
|
||||
}: BatchTableProps) {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const pageSize = 10;
|
||||
|
||||
cols = cols.concat([
|
||||
{
|
||||
accessor: (row) => row.image,
|
||||
Cell: ({ cell: { value } }: { cell: { value?: string } }) => (
|
||||
<FilePreview
|
||||
className="size-24 shrink-0 rounded-lg object-contain"
|
||||
client={client}
|
||||
srcOrFile={value}
|
||||
/>
|
||||
),
|
||||
Header: "Image",
|
||||
},
|
||||
{
|
||||
accessor: (row) => row.animation_url,
|
||||
Cell: ({ cell: { value } }: { cell: { value?: string } }) => (
|
||||
<FilePreview
|
||||
className="size-24 shrink-0 rounded-lg"
|
||||
client={client}
|
||||
srcOrFile={value}
|
||||
/>
|
||||
),
|
||||
Header: "Animation Url",
|
||||
},
|
||||
{ accessor: (row) => row.name, Header: "Name" },
|
||||
{
|
||||
accessor: (row) => (
|
||||
<ToolTipLabel label={row.description}>
|
||||
<p className="line-clamp-6 whitespace-pre-wrap">
|
||||
{row.description}
|
||||
</p>
|
||||
</ToolTipLabel>
|
||||
),
|
||||
Header: "Description",
|
||||
},
|
||||
{
|
||||
accessor: (row) => row.attributes || row.properties,
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
Cell: ({ cell }: { cell: any }) =>
|
||||
cell.value ? (
|
||||
<CodeClient
|
||||
code={JSON.stringify(cell.value || {}, null, 2)}
|
||||
lang="json"
|
||||
scrollableClassName="max-w-[300px]"
|
||||
/>
|
||||
) : null,
|
||||
Header: "Attributes",
|
||||
},
|
||||
{ accessor: (row) => row.external_url, Header: "External URL" },
|
||||
{ accessor: (row) => row.background_color, Header: "Background Color" },
|
||||
]);
|
||||
return cols;
|
||||
}, [nextTokenIdToMint, client]);
|
||||
const totalPages = Math.ceil(data.length / pageSize);
|
||||
const startIndex = (currentPage - 1) * pageSize;
|
||||
const endIndex = startIndex + pageSize;
|
||||
const currentData = data.slice(startIndex, endIndex);
|
||||
|
||||
const {
|
||||
getTableProps,
|
||||
getTableBodyProps,
|
||||
headerGroups,
|
||||
prepareRow,
|
||||
// Instead of using 'rows', we'll use page,
|
||||
page,
|
||||
// which has only the rows for the active page
|
||||
const handlePageChange = (page: number) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
// The rest of these things are super handy, too ;)
|
||||
canPreviousPage,
|
||||
canNextPage,
|
||||
pageOptions,
|
||||
pageCount,
|
||||
gotoPage,
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: { pageIndex, pageSize },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
initialState: {
|
||||
pageIndex: 0,
|
||||
pageSize: 50,
|
||||
},
|
||||
},
|
||||
// will be fixed with @tanstack/react-table v8
|
||||
// eslint-disable-next-line react-compiler/react-compiler
|
||||
usePagination,
|
||||
);
|
||||
const showTokenId = nextTokenIdToMint !== undefined;
|
||||
const showExternalUrl = data.some((row) => row.external_url);
|
||||
const showBackgroundColor = data.some((row) => row.background_color);
|
||||
const showAnimationUrl = data.some((row) => row.animation_url);
|
||||
const showDescription = data.some((row) => row.description);
|
||||
const showAttributes = data.some((row) => row.attributes || row.properties);
|
||||
|
||||
const showPagination = totalPages > 1;
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<Flex flexGrow={1} overflow="auto">
|
||||
<TableContainer className="w-full" maxW="100%">
|
||||
<Table {...getTableProps()}>
|
||||
<Thead>
|
||||
{headerGroups.map((headerGroup, index) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: FIXME
|
||||
<Tr {...headerGroup.getHeaderGroupProps()} key={index}>
|
||||
{headerGroup.headers.map((column, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: FIXME
|
||||
<Th {...column.getHeaderProps()} border="none" key={i}>
|
||||
<p className="text-muted-foreground">
|
||||
{column.render("Header")}
|
||||
</p>
|
||||
</Th>
|
||||
))}
|
||||
</Tr>
|
||||
))}
|
||||
</Thead>
|
||||
<Tbody {...getTableBodyProps()}>
|
||||
{page.map((row, rowIndex) => {
|
||||
prepareRow(row);
|
||||
<div className="rounded-lg border bg-card">
|
||||
<TableContainer className="border-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{showTokenId && <TableHead>Token ID</TableHead>}
|
||||
<TableHead>Image</TableHead>
|
||||
{showAnimationUrl && <TableHead>Animation Url</TableHead>}
|
||||
<TableHead>Name</TableHead>
|
||||
{showDescription && (
|
||||
<TableHead className="min-w-[300px]">Description</TableHead>
|
||||
)}
|
||||
{showAttributes && <TableHead>Attributes</TableHead>}
|
||||
{showExternalUrl && <TableHead>External URL</TableHead>}
|
||||
{showBackgroundColor && <TableHead>Background Color</TableHead>}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{currentData.map((row, rowIndex) => {
|
||||
const actualIndex = startIndex + rowIndex;
|
||||
return (
|
||||
<Tr
|
||||
{...row.getRowProps()}
|
||||
_last={{ borderBottomWidth: 0 }}
|
||||
borderBottomWidth={1}
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: FIXME
|
||||
key={rowIndex}
|
||||
<TableRow
|
||||
className="border-b last:border-b-0"
|
||||
key={actualIndex}
|
||||
>
|
||||
{row.cells.map((cell, cellIndex) => {
|
||||
return (
|
||||
<Td
|
||||
{...cell.getCellProps()}
|
||||
borderBottomWidth="inherit"
|
||||
borderColor="borderColor"
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: FIXME
|
||||
key={cellIndex}
|
||||
>
|
||||
{cell.render("Cell")}
|
||||
</Td>
|
||||
);
|
||||
})}
|
||||
</Tr>
|
||||
{/* Token ID */}
|
||||
{showTokenId && (
|
||||
<TableCell>
|
||||
{String(nextTokenIdToMint + BigInt(actualIndex))}
|
||||
</TableCell>
|
||||
)}
|
||||
|
||||
{/* Image */}
|
||||
<TableCell className="min-w-36">
|
||||
<FilePreview
|
||||
className="size-36 shrink-0 rounded-lg object-contain"
|
||||
client={client}
|
||||
srcOrFile={
|
||||
typeof row.image === "string" ||
|
||||
row.image instanceof File
|
||||
? row.image
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
|
||||
{/* Animation Url */}
|
||||
{showAnimationUrl && (
|
||||
<TableCell className="min-w-36">
|
||||
<FilePreview
|
||||
className="size-36 shrink-0 rounded-lg"
|
||||
client={client}
|
||||
srcOrFile={
|
||||
typeof row.animation_url === "string" ||
|
||||
row.animation_url instanceof File
|
||||
? row.animation_url
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
)}
|
||||
|
||||
{/* Name */}
|
||||
<TableCell>{row.name}</TableCell>
|
||||
|
||||
{/* Description */}
|
||||
{showDescription && (
|
||||
<TableCell className="max-w-xs">
|
||||
<p className="whitespace-pre-wrap">{row.description}</p>
|
||||
</TableCell>
|
||||
)}
|
||||
|
||||
{/* Attributes */}
|
||||
{showAttributes && (
|
||||
<TableCell>
|
||||
{row.attributes || row.properties ? (
|
||||
<CodeClient
|
||||
code={JSON.stringify(
|
||||
row.attributes || row.properties || {},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
lang="json"
|
||||
scrollableClassName="max-w-[300px] max-h-[400px]"
|
||||
className="bg-background [&>*]:text-xs"
|
||||
/>
|
||||
) : null}
|
||||
</TableCell>
|
||||
)}
|
||||
|
||||
{/* External URL */}
|
||||
{showExternalUrl && (
|
||||
<TableCell>
|
||||
{typeof row.external_url === "string" ? (
|
||||
<ToolTipLabel label={row.external_url}>
|
||||
<span>
|
||||
{row.external_url.slice(0, 20) +
|
||||
(row.external_url.length > 20 ? "..." : "")}
|
||||
</span>
|
||||
</ToolTipLabel>
|
||||
) : row.external_url instanceof File ? (
|
||||
<FilePreview
|
||||
client={client}
|
||||
srcOrFile={row.external_url}
|
||||
/>
|
||||
) : null}
|
||||
</TableCell>
|
||||
)}
|
||||
|
||||
{/* Background Color */}
|
||||
{showBackgroundColor && (
|
||||
<TableCell>{row.background_color}</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</Tbody>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
<Portal containerRef={portalRef}>
|
||||
<div className="flex w-full items-center justify-center">
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<IconButton
|
||||
aria-label="first page"
|
||||
icon={<ChevronFirstIcon className="size-4" />}
|
||||
isDisabled={!canPreviousPage}
|
||||
onClick={() => gotoPage(0)}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="previous page"
|
||||
icon={<ChevronLeftIcon className="size-4" />}
|
||||
isDisabled={!canPreviousPage}
|
||||
onClick={() => previousPage()}
|
||||
/>
|
||||
<p className="whitespace-nowrap">
|
||||
Page <strong>{pageIndex + 1}</strong> of{" "}
|
||||
<strong>{pageOptions.length}</strong>
|
||||
</p>
|
||||
<IconButton
|
||||
aria-label="next page"
|
||||
icon={<ChevronRightIcon className="size-4" />}
|
||||
isDisabled={!canNextPage}
|
||||
onClick={() => nextPage()}
|
||||
/>
|
||||
<IconButton
|
||||
aria-label="last page"
|
||||
icon={<ChevronLastIcon className="size-4" />}
|
||||
isDisabled={!canNextPage}
|
||||
onClick={() => gotoPage(pageCount - 1)}
|
||||
/>
|
||||
|
||||
<Select
|
||||
onChange={(e) => {
|
||||
setPageSize(Number.parseInt(e.target.value as string, 10));
|
||||
}}
|
||||
value={pageSize}
|
||||
>
|
||||
<option value="25">25</option>
|
||||
<option value="50">50</option>
|
||||
<option value="100">100</option>
|
||||
<option value="250">250</option>
|
||||
<option value="500">500</option>
|
||||
</Select>
|
||||
</div>
|
||||
{showPagination && (
|
||||
<div className="border-t py-5">
|
||||
<PaginationButtons
|
||||
activePage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageClick={handlePageChange}
|
||||
/>
|
||||
</div>
|
||||
</Portal>
|
||||
</Flex>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -42,18 +42,18 @@ export const SelectOption: React.FC<SelectOptionProps> = ({
|
||||
disabled
|
||||
? "pointer-events-none cursor-not-allowed bg-muted"
|
||||
: "cursor-pointer",
|
||||
isActive && "border-primary",
|
||||
isActive && "bg-muted/50 border-active-border",
|
||||
className,
|
||||
)}
|
||||
onClick={onClick}
|
||||
{...divProps}
|
||||
>
|
||||
<div className="flex flex-row justify-between">
|
||||
<div className="flex flex-row items-start">
|
||||
<div className="mt-0.5 mr-2.5 flex h-4 w-4 items-center justify-center rounded-full border border-inverted text-inverted">
|
||||
<div className="flex flex-row items-start gap-4">
|
||||
<div className="flex size-5 shrink-0 items-center justify-center rounded-full border border-inverted text-inverted">
|
||||
{isActive && <div className="h-2 w-2 rounded-full bg-inverted" />}
|
||||
</div>
|
||||
<div className="ml-4 flex flex-col gap-2 self-start">
|
||||
<div>
|
||||
<h4
|
||||
className={cn(
|
||||
"font-semibold text-sm",
|
||||
@@ -62,7 +62,11 @@ export const SelectOption: React.FC<SelectOptionProps> = ({
|
||||
>
|
||||
{name}
|
||||
</h4>
|
||||
{description && <p className="mt-1 text-sm">{description}</p>}
|
||||
{description && (
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{infoText && (
|
||||
|
||||
@@ -1,137 +1,299 @@
|
||||
import { UploadIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { UnorderedList } from "@/components/ui/List/List";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { DownloadableCode } from "../blocks/code/downloadable-code";
|
||||
import { DropZone } from "../blocks/drop-zone/drop-zone";
|
||||
|
||||
interface UploadStepProps {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
getRootProps: any;
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
getInputProps: any;
|
||||
hasFailed: boolean;
|
||||
isDragActive: boolean;
|
||||
onDrop: (acceptedFiles: File[]) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
|
||||
export const UploadStep: React.FC<UploadStepProps> = ({
|
||||
getRootProps,
|
||||
hasFailed,
|
||||
isDragActive,
|
||||
getInputProps,
|
||||
}) => {
|
||||
export function UploadStep(props: UploadStepProps) {
|
||||
const [tab, setTab] = useState<"csv" | "json">("csv");
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-8 md:flex-row">
|
||||
<div className="relative aspect-square w-full md:w-1/2">
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full cursor-pointer rounded-md border border-border hover:border-blue-500",
|
||||
hasFailed ? "bg-red-200" : "bg-background",
|
||||
)}
|
||||
{...getRootProps()}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
<div className="m-auto flex flex-col p-6">
|
||||
<UploadIcon
|
||||
className={cn(
|
||||
"mx-auto mb-2 size-8",
|
||||
hasFailed ? "text-red-500" : "text-gray-600",
|
||||
)}
|
||||
<div className="container px-0 max-w-3xl">
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-4">
|
||||
Upload NFTs
|
||||
</h2>
|
||||
|
||||
<DropZone
|
||||
className="w-full py-24"
|
||||
onDrop={props.onDrop}
|
||||
isError={props.hasFailed}
|
||||
title={props.hasFailed ? "Invalid files" : "Upload files"}
|
||||
description={
|
||||
props.hasFailed
|
||||
? "Make sure the uploaded files follow the requirements mentioned below"
|
||||
: "Drag and drop the files or folder"
|
||||
}
|
||||
resetButton={{
|
||||
label: "Reset",
|
||||
onClick: props.reset,
|
||||
}}
|
||||
accept={undefined}
|
||||
/>
|
||||
|
||||
<div className="h-8" />
|
||||
|
||||
<div className="w-full">
|
||||
<TabButtons
|
||||
tabs={[
|
||||
{
|
||||
isActive: tab === "csv",
|
||||
name: "CSV",
|
||||
onClick: () => setTab("csv"),
|
||||
},
|
||||
{
|
||||
isActive: tab === "json",
|
||||
name: "JSON",
|
||||
onClick: () => setTab("json"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="h-6" />
|
||||
|
||||
<div className="space-y-8">
|
||||
<Section title="Uploading Files">
|
||||
<p>
|
||||
Make sure to drag and drop the {tab === "csv" ? "CSV" : "JSON"}{" "}
|
||||
and the assets at the same time or upload a folder with all the
|
||||
files in it.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Asset names <em>must</em> be sequential 0,1,2,3...n.[extension].
|
||||
It doesn't matter at what number you begin. Example: 131.png,
|
||||
132.png etc.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Images and other file types can be used in combination. They both
|
||||
have to follow the asset naming convention above. Example: 0.png
|
||||
and 0.mp4, 1.png and 1.glb etc.
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title={`${tab === "csv" ? "CSV" : "JSON"} File Format`}>
|
||||
<p>
|
||||
The {tab === "csv" ? "CSV" : "JSON"} file must have a{" "}
|
||||
<InlineCode code="name" /> {tab === "csv" ? "column" : "property"}
|
||||
, which defines the name of the NFT
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Other optional {tab === "csv" ? "columns" : "properties"} are{" "}
|
||||
<InlineCode code="description" />,{" "}
|
||||
<InlineCode code="background_color" />,{" "}
|
||||
<InlineCode code="external_url" />,{" "}
|
||||
<InlineCode code="animation_url" />,{" "}
|
||||
{tab === "json" && (
|
||||
<>
|
||||
,
|
||||
<InlineCode code="attributes" />
|
||||
</>
|
||||
)}{" "}
|
||||
and <InlineCode code="supply" />
|
||||
{". "}
|
||||
{tab === "csv" &&
|
||||
"All other columns will be treated as Attributes. For example: See 'eyes', 'nose' below."}
|
||||
</p>
|
||||
|
||||
<DownloadableCode
|
||||
code={tab === "csv" ? csv_example_basic : json_example_basic}
|
||||
fileNameWithExtension={
|
||||
tab === "csv" ? "example.csv" : "example.json"
|
||||
}
|
||||
lang={tab === "csv" ? "csv" : "json"}
|
||||
/>
|
||||
{isDragActive ? (
|
||||
<p className="text-center text-muted-foreground">
|
||||
Drop the files here
|
||||
</p>
|
||||
) : (
|
||||
<p
|
||||
className={cn(
|
||||
"text-center leading-[1.2]",
|
||||
hasFailed ? "text-red-500" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{hasFailed
|
||||
? `No valid CSV or JSON file found. Please make sure your NFT metadata includes at least a "name" field and try again.`
|
||||
: "Drag & Drop files or folders here, or click to select files"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Map your assets to NFTs">
|
||||
<p>
|
||||
If you want to map your media files to your NFTs, you can add the
|
||||
name of your files to the <InlineCode code="image" /> and{" "}
|
||||
<InlineCode code="animation_url" />{" "}
|
||||
{tab === "csv" ? "columns" : "properties"}.{" "}
|
||||
<DownloadableCode
|
||||
code={
|
||||
tab === "csv"
|
||||
? csv_with_image_number_example
|
||||
: json_with_image_number_example
|
||||
}
|
||||
fileNameWithExtension={
|
||||
tab === "csv"
|
||||
? "example-with-maps.csv"
|
||||
: "example-with-maps.json"
|
||||
}
|
||||
lang={tab === "csv" ? "csv" : "json"}
|
||||
/>
|
||||
</p>
|
||||
</Section>
|
||||
|
||||
<Section title="Using asset links instead of uploading assets">
|
||||
<p>
|
||||
When uploading files, assets will be uploaded and pinned to IPFS
|
||||
automatically. If you already have the files uploaded elsewhere,
|
||||
you can specify the IPFS or HTTP(s) links in the{" "}
|
||||
<InlineCode code="image" /> and/or{" "}
|
||||
<InlineCode code="animation_url" />{" "}
|
||||
{tab === "csv" ? "columns" : "properties"}. instead of uploading
|
||||
the assets and just upload a single{" "}
|
||||
{tab === "csv" ? "CSV" : "JSON"} file.
|
||||
<DownloadableCode
|
||||
code={
|
||||
tab === "csv"
|
||||
? csv_with_image_link_example
|
||||
: json_with_image_link_example
|
||||
}
|
||||
fileNameWithExtension={
|
||||
tab === "csv"
|
||||
? "example-with-ipfs.csv"
|
||||
: "example-with-ipfs.json"
|
||||
}
|
||||
lang={tab === "csv" ? "csv" : "json"}
|
||||
/>
|
||||
</p>
|
||||
</Section>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-2 md:w-1/2">
|
||||
<p className="text-lg">Requirements</p>
|
||||
<UnorderedList>
|
||||
<li>
|
||||
Files <em>must</em> contain one .csv or .json file with metadata. -{" "}
|
||||
<a
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
download
|
||||
href="/assets/examples/example.csv"
|
||||
>
|
||||
Download example.csv
|
||||
</a>
|
||||
.{" "}
|
||||
<a
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
download
|
||||
href="/assets/examples/example.json"
|
||||
>
|
||||
Download example.json
|
||||
</a>
|
||||
.
|
||||
</li>
|
||||
<li>
|
||||
The csv <em>must</em> have a <InlineCode code="name" /> column,
|
||||
which defines the name of the NFT.
|
||||
</li>
|
||||
<li>
|
||||
Asset names <em>must</em> be sequential 0,1,2,3...n.[extension]. It
|
||||
doesn't matter at what number you begin. (Example:{" "}
|
||||
<InlineCode code="131.png" />, <InlineCode code="132.png" />
|
||||
).
|
||||
</li>
|
||||
<li>
|
||||
Make sure to drag and drop the CSV/JSON and the images{" "}
|
||||
<strong>at the same time</strong>.
|
||||
</li>
|
||||
</UnorderedList>
|
||||
<p className="mt-4 text-lg">Options</p>
|
||||
<UnorderedList>
|
||||
<li>
|
||||
Images and other file types can be used in combination.
|
||||
<br />
|
||||
<small>
|
||||
They both have to follow the asset naming convention above.
|
||||
(Example: <InlineCode code="0.png" /> and{" "}
|
||||
<InlineCode code="0.mp4" />,<InlineCode code="1.png" /> and{" "}
|
||||
<InlineCode code="1.glb" />, etc.)
|
||||
</small>
|
||||
</li>
|
||||
<li>
|
||||
When uploading files, we will upload them and pin them to IPFS
|
||||
automatically for you. If you already have the files uploaded, you
|
||||
can add an <InlineCode code="image" /> and/or
|
||||
<InlineCode code="animation_url" /> column and add the IPFS hashes
|
||||
there.{" "}
|
||||
<a
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
download
|
||||
href="/assets/examples/example-with-ipfs.csv"
|
||||
>
|
||||
Download example.csv
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
If you want to make your media files map to your NFTs, you can add
|
||||
the name of your files to the <InlineCode code="image" /> and
|
||||
<InlineCode code="animation_url" /> column.{" "}
|
||||
<a
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
download
|
||||
href="/assets/examples/example-with-maps.csv"
|
||||
>
|
||||
Download example.csv
|
||||
</a>
|
||||
</li>
|
||||
</UnorderedList>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function Section(props: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section>
|
||||
<h2 className="mb-1 font-medium text-base text-foreground">
|
||||
{props.title}
|
||||
</h2>
|
||||
<div className="space-y-1.5 text-muted-foreground leading-relaxed">
|
||||
{props.children}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const csv_example_basic = `\
|
||||
name,description,background_color,eyes,nose
|
||||
Token 0 Name,Token 0 Description,#0098EE,red,green
|
||||
Token 1 Name,Token 1 Description,#0098EE,blue,yellow`;
|
||||
|
||||
const json_example_basic = `\
|
||||
[
|
||||
{
|
||||
"name": "Token 0 Name",
|
||||
"description": "Token 0 Description",
|
||||
"background_color": "#0098EE",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "red"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "green"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Token 1 Name",
|
||||
"description": "Token 1 Description",
|
||||
"background_color": "#0098EE",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "blue"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "yellow"
|
||||
}
|
||||
]
|
||||
}
|
||||
]`;
|
||||
|
||||
const csv_with_image_link_example = `\
|
||||
name,description,image,animation_url,background_color,eyes,nose
|
||||
Token 0 Name,Token 0 Description,ipfs://ipfsHash/0,ipfs://ipfsHash/0,#0098EE,red,green
|
||||
Token 1 Name,Token 1 Description,ipfs://ipfsHash/1,ipfs://ipfsHash/1,#0098EE,blue,yellow`;
|
||||
|
||||
const json_with_image_link_example = `\
|
||||
[
|
||||
{
|
||||
"name": "Token 0 Name",
|
||||
"description": "Token 0 Description",
|
||||
"image": "ipfs://ipfsHash/0",
|
||||
"animation_url": "ipfs://ipfsHash/0",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "red"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "green"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Token 1 Name",
|
||||
"description": "Token 1 Description",
|
||||
"image": "ipfs://ipfsHash/1",
|
||||
"animation_url": "ipfs://ipfsHash/1",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "blue"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "yellow"
|
||||
}
|
||||
]
|
||||
}
|
||||
]`;
|
||||
|
||||
const csv_with_image_number_example = `\
|
||||
name,description,image,animation_url,background_color,eyes,nose
|
||||
Token 0 Name,Token 0 Description,0.png,0.mp4,#0098EE,red,green
|
||||
Token 1 Name,Token 1 Description,1.png,1.mp4,#0098EE,blue,yellow`;
|
||||
|
||||
const json_with_image_number_example = `\
|
||||
[
|
||||
{
|
||||
"name": "Token 0 Name",
|
||||
"description": "Token 0 Description",
|
||||
"image": "0.png",
|
||||
"animation_url": "0.mp4",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "red"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "green"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Token 1 Name",
|
||||
"description": "Token 1 Description",
|
||||
"image": "1.png",
|
||||
"animation_url": "1.mp4",
|
||||
"attributes": [
|
||||
{
|
||||
"trait_type": "eyes",
|
||||
"value": "blue"
|
||||
},
|
||||
{
|
||||
"trait_type": "nose",
|
||||
"value": "yellow"
|
||||
}
|
||||
]
|
||||
}
|
||||
]`;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { FilePreview } from "@app/team/[team_slug]/[project_slug]/(sidebar)/tokens/create/_common/file-preview";
|
||||
import { FilePlusIcon, UploadIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import {
|
||||
@@ -8,6 +7,7 @@ import {
|
||||
useDropzone,
|
||||
} from "react-dropzone";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { FilePreview } from "@/components/blocks/file-preview";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AsteriskIcon, InfoIcon } from "lucide-react";
|
||||
import type React from "react";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { cn } from "../../lib/utils";
|
||||
|
||||
export function FormFieldSetup(props: {
|
||||
htmlFor?: string;
|
||||
@@ -10,13 +11,22 @@ export function FormFieldSetup(props: {
|
||||
children: React.ReactNode;
|
||||
tooltip?: React.ReactNode;
|
||||
isRequired: boolean;
|
||||
labelClassName?: string;
|
||||
labelContainerClassName?: string;
|
||||
helperText?: React.ReactNode;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={props.className}>
|
||||
<div className="mb-2 inline-flex items-center gap-1">
|
||||
<Label htmlFor={props.htmlFor}>{props.label}</Label>
|
||||
<div
|
||||
className={cn(
|
||||
"mb-2 inline-flex items-center gap-1",
|
||||
props.labelContainerClassName,
|
||||
)}
|
||||
>
|
||||
<Label htmlFor={props.htmlFor} className={props.labelClassName}>
|
||||
{props.label}
|
||||
</Label>
|
||||
|
||||
{props.isRequired && (
|
||||
<AsteriskIcon className="size-3.5 text-destructive-text" />
|
||||
|
||||
@@ -3,6 +3,7 @@ import type React from "react";
|
||||
import { type Dispatch, type SetStateAction, useMemo } from "react";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type CodeEnvironment =
|
||||
| "javascript"
|
||||
@@ -50,6 +51,7 @@ interface CodeSegmentProps {
|
||||
isInstallCommand?: boolean;
|
||||
hideTabs?: boolean;
|
||||
onlyTabs?: boolean;
|
||||
codeContainerClassName?: string;
|
||||
}
|
||||
|
||||
export const CodeSegment: React.FC<CodeSegmentProps> = ({
|
||||
@@ -59,6 +61,7 @@ export const CodeSegment: React.FC<CodeSegmentProps> = ({
|
||||
isInstallCommand,
|
||||
hideTabs,
|
||||
onlyTabs,
|
||||
codeContainerClassName,
|
||||
}) => {
|
||||
const activeEnvironment: CodeEnvironment = useMemo(() => {
|
||||
return (
|
||||
@@ -86,7 +89,7 @@ export const CodeSegment: React.FC<CodeSegmentProps> = ({
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
"flex flex-col overflow-hidden rounded-lg border border-border"
|
||||
"flex flex-col overflow-hidden rounded-lg border border-border grow"
|
||||
}
|
||||
>
|
||||
{!hideTabs && (
|
||||
@@ -106,7 +109,11 @@ export const CodeSegment: React.FC<CodeSegmentProps> = ({
|
||||
|
||||
{onlyTabs ? null : (
|
||||
<CodeClient
|
||||
className="rounded-none border-none"
|
||||
className={cn(
|
||||
"rounded-none border-none grow",
|
||||
codeContainerClassName,
|
||||
)}
|
||||
scrollableContainerClassName="h-full"
|
||||
code={code}
|
||||
lang={
|
||||
isInstallCommand
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
import { ArrowDownToLineIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import { handleDownload } from "../download-file-button";
|
||||
|
||||
export function DownloadableCode(props: {
|
||||
code: string;
|
||||
lang: "csv" | "json";
|
||||
fileNameWithExtension: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="!my-3 relative">
|
||||
<CodeClient
|
||||
code={props.code}
|
||||
lang={props.lang}
|
||||
scrollableClassName="max-h-[300px] bg-background"
|
||||
/>
|
||||
|
||||
<Button
|
||||
className="absolute top-3.5 right-14 mt-[1px] h-auto bg-background p-2"
|
||||
onClick={() => {
|
||||
handleDownload({
|
||||
fileContent: props.code,
|
||||
fileFormat: props.lang === "csv" ? "text/csv" : "application/json",
|
||||
fileNameWithExtension: props.fileNameWithExtension,
|
||||
});
|
||||
}}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
<ArrowDownToLineIcon className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+7
-2
@@ -1,5 +1,6 @@
|
||||
import { ArrowDownToLineIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function handleDownload(params: {
|
||||
fileContent: string;
|
||||
@@ -22,10 +23,14 @@ export function DownloadFileButton(props: {
|
||||
fileNameWithExtension: string;
|
||||
fileFormat: "text/csv" | "application/json";
|
||||
label: string;
|
||||
variant?: "default" | "outline";
|
||||
className?: string;
|
||||
iconClassName?: string;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
className="gap-2"
|
||||
className={cn("gap-2", props.className)}
|
||||
variant={props.variant}
|
||||
onClick={() => {
|
||||
handleDownload({
|
||||
fileContent: props.fileContent,
|
||||
@@ -35,7 +40,7 @@ export function DownloadFileButton(props: {
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
<ArrowDownToLineIcon className="size-4" />
|
||||
<ArrowDownToLineIcon className={cn("size-4", props.iconClassName)} />
|
||||
{props.label}
|
||||
</Button>
|
||||
);
|
||||
+10
-2
@@ -37,7 +37,12 @@ export function FilePreview(props: {
|
||||
|
||||
if (!objectUrl) {
|
||||
return (
|
||||
<div className={cn("flex items-center justify-center", props.className)}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center bg-accent",
|
||||
props.className,
|
||||
)}
|
||||
>
|
||||
<ImageOffIcon className="size-6 text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
@@ -56,7 +61,10 @@ export function FilePreview(props: {
|
||||
|
||||
return (
|
||||
<MediaRenderer
|
||||
className={cn(props.className, "[&>div]:!bg-muted")}
|
||||
className={cn(
|
||||
props.className,
|
||||
"[&>div]:!bg-accent [&_a]:!text-muted-foreground [&_a]:!no-underline [&_svg]:!size-6 [&_svg]:!text-muted-foreground relative overflow-hidden",
|
||||
)}
|
||||
client={props.client}
|
||||
src={objectUrl}
|
||||
/>
|
||||
+29
-25
@@ -1,9 +1,6 @@
|
||||
"use client";
|
||||
import { Flex, FormControl } from "@chakra-ui/react";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { verifyContract } from "app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/sources/ContractSourcesPage";
|
||||
import { FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import {
|
||||
ArrowUpFromLineIcon,
|
||||
CircleAlertIcon,
|
||||
@@ -27,6 +24,7 @@ import {
|
||||
reportContractDeployed,
|
||||
reportContractDeployFailed,
|
||||
} from "@/analytics/report";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
import { NetworkSelectorButton } from "@/components/misc/NetworkSelectorButton";
|
||||
import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import {
|
||||
@@ -932,14 +930,17 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
<Fieldset legend="Deploy Options">
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* Chain */}
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Chain</FormLabel>
|
||||
|
||||
<p className="mb-3 text-muted-foreground text-sm">
|
||||
Select a network to deploy this contract on. We recommend
|
||||
starting with a testnet
|
||||
</p>
|
||||
|
||||
<FormFieldSetup
|
||||
isRequired
|
||||
label="Chain"
|
||||
errorMessage={undefined}
|
||||
helperText={
|
||||
<span>
|
||||
Select a network to deploy this contract on. We recommend
|
||||
starting with a testnet
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-4 md:flex-row">
|
||||
<NetworkSelectorButton
|
||||
@@ -953,7 +954,6 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
: metadata?.networksForDeployment?.networksEnabled
|
||||
}
|
||||
/>
|
||||
|
||||
<Button asChild variant="outline">
|
||||
<Link
|
||||
className="gap-3"
|
||||
@@ -967,12 +967,11 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</FormControl>
|
||||
</FormFieldSetup>
|
||||
|
||||
{metadata?.deployType === "standard" && (
|
||||
<>
|
||||
{/* Deterministic deploy */}
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<CheckboxWithLabel>
|
||||
<Checkbox
|
||||
@@ -1006,16 +1005,21 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
|
||||
{/* Optional Salt Input */}
|
||||
{isCreate2Deployment && (
|
||||
<FormControl>
|
||||
<Flex alignItems="center" my={1}>
|
||||
<FormLabel display="flex" flex="1" mb={0}>
|
||||
<Flex alignItems="baseline" gap={1}>
|
||||
Optional Salt Input
|
||||
<Text size="label.sm">(saltForCreate2)</Text>
|
||||
</Flex>
|
||||
</FormLabel>
|
||||
<FormHelperText mt={0}>string</FormHelperText>
|
||||
</Flex>
|
||||
<FormFieldSetup
|
||||
isRequired={false}
|
||||
label={
|
||||
<span className="flex items-center gap-1">
|
||||
Optional Salt Input
|
||||
<span className="font-normal text-muted-foreground text-xs">
|
||||
(saltForCreate2)
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
errorMessage={
|
||||
form.getFieldState("saltForCreate2", form.formState)
|
||||
.error?.message
|
||||
}
|
||||
>
|
||||
<SolidityInput
|
||||
solidityType="string"
|
||||
{...form.register("saltForCreate2")}
|
||||
@@ -1034,7 +1038,7 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
Include deployer wallet address in salt (recommended)
|
||||
</span>
|
||||
</CheckboxWithLabel>
|
||||
</FormControl>
|
||||
</FormFieldSetup>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
+9
-15
@@ -1,8 +1,7 @@
|
||||
import { FormControl } from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormLabel } from "chakra/form";
|
||||
import { useMemo } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { FetchDeployMetadataResult } from "thirdweb/contract";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import type { CustomContractDeploymentForm } from "./custom-contract";
|
||||
import { PrimarySaleFieldset } from "./primary-sale-fieldset";
|
||||
@@ -104,14 +103,15 @@ function RenderModule(props: {
|
||||
`moduleData.${module.name}.${param.name}` as const;
|
||||
|
||||
return (
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState(formFieldKey, form.formState).error
|
||||
}
|
||||
isRequired
|
||||
<FormFieldSetup
|
||||
key={formFieldKey}
|
||||
htmlFor={formFieldKey}
|
||||
label={param.name}
|
||||
isRequired={true}
|
||||
errorMessage={
|
||||
form.getFieldState(formFieldKey, form.formState).error?.message
|
||||
}
|
||||
>
|
||||
<FormLabel> {param.name}</FormLabel>
|
||||
<SolidityInput
|
||||
client={props.client}
|
||||
// @ts-expect-error - old types, need to update
|
||||
@@ -119,13 +119,7 @@ function RenderModule(props: {
|
||||
solidityType={param.type}
|
||||
{...form.register(formFieldKey)}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState(formFieldKey, form.formState).error
|
||||
?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</FormFieldSetup>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
+27
-30
@@ -1,20 +1,24 @@
|
||||
import type { Abi } from "abitype";
|
||||
import { Select } from "chakra-react-select";
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
|
||||
interface AbiSelectorProps {
|
||||
abi: Abi;
|
||||
defaultValue: string;
|
||||
value: string;
|
||||
onChange: (fn: string) => void;
|
||||
}
|
||||
|
||||
export const AbiSelector: React.FC<AbiSelectorProps> = ({
|
||||
export function AbiSelector({
|
||||
abi,
|
||||
value,
|
||||
defaultValue,
|
||||
onChange,
|
||||
}) => {
|
||||
}: {
|
||||
abi: Abi;
|
||||
defaultValue: string;
|
||||
value: string;
|
||||
onChange: (fn: string) => void;
|
||||
}) {
|
||||
const options = useMemo(() => {
|
||||
return abi
|
||||
.filter((f) => f.type === "function")
|
||||
@@ -26,24 +30,17 @@ export const AbiSelector: React.FC<AbiSelectorProps> = ({
|
||||
}, [abi]);
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-row items-center gap-2">
|
||||
<Select
|
||||
chakraStyles={{
|
||||
container: (provided) => ({
|
||||
...provided,
|
||||
width: "full",
|
||||
}),
|
||||
}}
|
||||
defaultValue={options.find((o) => o.value === defaultValue)}
|
||||
onChange={(selectedFn) => {
|
||||
if (selectedFn) {
|
||||
onChange((selectedFn as { label: string; value: string }).value);
|
||||
}
|
||||
}}
|
||||
options={options}
|
||||
placeholder="Select function"
|
||||
value={options.find((o) => o.value === value)}
|
||||
/>
|
||||
</div>
|
||||
<Select value={value} onValueChange={onChange} defaultValue={defaultValue}>
|
||||
<SelectTrigger className="w-full bg-card">
|
||||
<SelectValue placeholder="Select function" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+25
-29
@@ -1,4 +1,3 @@
|
||||
import { FormControl, useBreakpointValue } from "@chakra-ui/react";
|
||||
import type { AbiParameter } from "abitype";
|
||||
import { useId, useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
@@ -12,6 +11,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useIsMobile } from "@/hooks/use-mobile";
|
||||
import { getTemplateValuesForType } from "@/lib/deployment/template-values";
|
||||
import { DecodedInputArrayFieldset } from "./decoded-bytes-input/decoded-input-array-fieldset";
|
||||
import { RefInputFieldset } from "./ref-contract-input/ref-input-fieldset";
|
||||
@@ -25,7 +25,7 @@ export const ContractParamsFieldset: React.FC<ContractParamsFieldsetProps> = ({
|
||||
client,
|
||||
}) => {
|
||||
const form = useFormContext();
|
||||
const isMobile = useBreakpointValue({ base: true, md: false });
|
||||
const isMobile = useIsMobile();
|
||||
const displayNameId = useId();
|
||||
const descriptionId = useId();
|
||||
const [isCustomInputEnabledArray, setIsCustomInputEnabledArray] = useState(
|
||||
@@ -70,22 +70,20 @@ export const ContractParamsFieldset: React.FC<ContractParamsFieldsetProps> = ({
|
||||
|
||||
return (
|
||||
<fieldset>
|
||||
<h2 className="font-semibold text-3xl tracking-tight">
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-1">
|
||||
Contract Parameters
|
||||
</h2>
|
||||
<p className="text-muted-foreground">
|
||||
<p className="text-muted-foreground text-sm mb-6">
|
||||
These are the parameters users will need to fill in when deploying this
|
||||
contract.
|
||||
</p>
|
||||
|
||||
<div className="h-6" />
|
||||
|
||||
<div className="flex flex-col gap-8">
|
||||
{deployParams.map((param, idx) => {
|
||||
const paramTemplateValues = getTemplateValuesForType(param.type);
|
||||
return (
|
||||
<div
|
||||
className="rounded-lg border border-border bg-card p-6"
|
||||
className="rounded-lg border border-border bg-card p-4"
|
||||
key={`implementation_${param.name}`}
|
||||
>
|
||||
{/* Title + Type */}
|
||||
@@ -100,12 +98,12 @@ export const ContractParamsFieldset: React.FC<ContractParamsFieldsetProps> = ({
|
||||
)}
|
||||
</h3>
|
||||
<InlineCode
|
||||
className="px-2 text-base text-muted-foreground"
|
||||
className="px-2 text-muted-foreground text-sm"
|
||||
code={param.type}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-5" />
|
||||
<div className="h-4" />
|
||||
|
||||
{/* Display Name */}
|
||||
<FormFieldSetup
|
||||
@@ -140,7 +138,7 @@ export const ContractParamsFieldset: React.FC<ContractParamsFieldsetProps> = ({
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<div className="h-5" />
|
||||
<div className="h-4" />
|
||||
|
||||
{/* Description */}
|
||||
<FormFieldSetup
|
||||
@@ -217,25 +215,23 @@ export const ContractParamsFieldset: React.FC<ContractParamsFieldsetProps> = ({
|
||||
|
||||
{/* Inputs */}
|
||||
{!isCustomInputEnabledArray[idx] ? (
|
||||
<FormControl>
|
||||
<SolidityInput
|
||||
className="!bg-background !text-sm placeholder:!text-sm"
|
||||
client={client}
|
||||
placeholder={
|
||||
isMobile ||
|
||||
paramTemplateValues?.[0]?.value ===
|
||||
"{{trusted_forwarders}}"
|
||||
? "Pre-filled value."
|
||||
: "This value will be pre-filled in the deploy form."
|
||||
}
|
||||
solidityType={param.type}
|
||||
{...form.register(
|
||||
`constructorParams.${
|
||||
param.name ? param.name : "*"
|
||||
}.defaultValue`,
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<SolidityInput
|
||||
className="!bg-background !text-sm placeholder:!text-sm"
|
||||
client={client}
|
||||
placeholder={
|
||||
isMobile ||
|
||||
paramTemplateValues?.[0]?.value ===
|
||||
"{{trusted_forwarders}}"
|
||||
? "Pre-filled value."
|
||||
: "This value will be pre-filled in the deploy form."
|
||||
}
|
||||
solidityType={param.type}
|
||||
{...form.register(
|
||||
`constructorParams.${
|
||||
param.name ? param.name : "*"
|
||||
}.defaultValue`,
|
||||
)}
|
||||
/>
|
||||
) : param.type === "address" || param.type === "address[]" ? (
|
||||
<RefInputFieldset client={client} param={param} />
|
||||
) : (
|
||||
|
||||
+127
-107
@@ -1,33 +1,26 @@
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
FormControl,
|
||||
IconButton,
|
||||
Input,
|
||||
ListItem,
|
||||
UnorderedList,
|
||||
} from "@chakra-ui/react";
|
||||
import type { Abi } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { PlusIcon, TrashIcon } from "lucide-react";
|
||||
import { type Dispatch, type SetStateAction, useEffect } from "react";
|
||||
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
|
||||
import { useFieldArray, useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { SingleNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useCustomFactoryAbi } from "@/hooks/contract-hooks";
|
||||
import { AbiSelector } from "./abi-selector";
|
||||
|
||||
interface CustomFactoryProps {
|
||||
export function CustomFactory(props: {
|
||||
setCustomFactoryAbi: Dispatch<SetStateAction<Abi>>;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const CustomFactory: React.FC<CustomFactoryProps> = ({
|
||||
setCustomFactoryAbi,
|
||||
client,
|
||||
}) => {
|
||||
}) {
|
||||
const { setCustomFactoryAbi, client } = props;
|
||||
const form = useFormContext();
|
||||
|
||||
const customFactoryAbi = useCustomFactoryAbi(
|
||||
@@ -35,7 +28,6 @@ export const CustomFactory: React.FC<CustomFactoryProps> = ({
|
||||
form.watch("customFactoryAddresses[0].value"),
|
||||
form.watch("customFactoryAddresses[0].key"),
|
||||
);
|
||||
|
||||
// FIXME: all of this logic needs to be reworked
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
useEffect(() => {
|
||||
@@ -58,102 +50,130 @@ export const CustomFactory: React.FC<CustomFactoryProps> = ({
|
||||
}, [fields, append]);
|
||||
|
||||
return (
|
||||
<Flex flexDir="column" gap={12} pb={0} px={0}>
|
||||
<UnorderedList>
|
||||
<Text as={ListItem}>
|
||||
<div className="space-y-12">
|
||||
{/* Description */}
|
||||
<div className="space-y-1.5 text-sm text-muted-foreground">
|
||||
<p>
|
||||
Use this if you want to invoke your own function with custom logic
|
||||
when users deploy your contract.
|
||||
</Text>
|
||||
<Text as={ListItem}>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
You need to have factory contracts pre-deployed to all networks that
|
||||
you want to support.
|
||||
</Text>
|
||||
</UnorderedList>
|
||||
<Flex flexDir="column" gap={4}>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Factory contract addresses</Heading>
|
||||
<Text>
|
||||
Paste the contract address of your factory contracts. Your contract
|
||||
can be deployed only to networks with valid factory address.
|
||||
</Text>
|
||||
</Flex>
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id}>
|
||||
<FormControl as={Flex} gap={4} isRequired>
|
||||
<Box w={{ base: "full", md: "40%" }}>
|
||||
<Controller
|
||||
control={form.control}
|
||||
name={`customFactoryAddresses[${index}].key`}
|
||||
render={({ field: _field }) => {
|
||||
return (
|
||||
<SingleNetworkSelector
|
||||
chainId={_field.value}
|
||||
client={client}
|
||||
onChange={(value) => {
|
||||
_field.onChange(value);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Box w="full">
|
||||
<Input
|
||||
isRequired
|
||||
{...form.register(`customFactoryAddresses[${index}].value`)}
|
||||
placeholder="Factory contract address"
|
||||
/>
|
||||
</Box>
|
||||
<IconButton
|
||||
aria-label="Remove row"
|
||||
icon={<TrashIcon className="size-5" />}
|
||||
isDisabled={fields.length === 1 || form.formState.isSubmitting}
|
||||
onClick={() => remove(index)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Factory contract addresses */}
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold tracking-tight mb-1">
|
||||
Factory contract addresses
|
||||
</h2>
|
||||
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Paste the contract address of your factory contracts. Your contract
|
||||
can be deployed only to networks with valid factory address.
|
||||
</p>
|
||||
|
||||
<div className="space-y-3 mb-5">
|
||||
{fields.map((field, index) => (
|
||||
<div
|
||||
key={field.id}
|
||||
className="flex flex-col lg:flex-row gap-4 lg:items-end"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`customFactoryAddresses[${index}].key`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="w-full lg:w-80 space-y-1.5">
|
||||
<FormLabel>Network</FormLabel>
|
||||
<SingleNetworkSelector
|
||||
chainId={field.value}
|
||||
disableChainId
|
||||
className="bg-card"
|
||||
client={client}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`customFactoryAddresses[${index}].value`}
|
||||
render={({ field }) => (
|
||||
<FormItem className="grow space-y-1.5">
|
||||
<FormLabel>Factory contract address</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
required
|
||||
className="bg-card"
|
||||
{...field}
|
||||
placeholder="0x..."
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="rounded-full p-0 size-10 bg-card self-end"
|
||||
aria-label="Remove row"
|
||||
disabled={fields.length === 1 || form.formState.isSubmitting}
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
<TrashIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
borderRadius="md"
|
||||
colorScheme="primary"
|
||||
leftIcon={<PlusIcon className="size-5" />}
|
||||
onClick={() => append({ key: "", value: "" })}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
type="button"
|
||||
className="rounded-full bg-card"
|
||||
onClick={() => append({ key: "", value: "" })}
|
||||
>
|
||||
Add Network
|
||||
<PlusIcon className="size-5 mr-2" /> Add Network
|
||||
</Button>
|
||||
</div>
|
||||
</Flex>
|
||||
<Flex flexDir="column" gap={4}>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Factory function</Heading>
|
||||
<Text>Choose the factory function to deploy your contracts.</Text>
|
||||
</Flex>
|
||||
<FormControl isRequired>
|
||||
{customFactoryAbi?.data ? (
|
||||
<AbiSelector
|
||||
abi={customFactoryAbi.data}
|
||||
defaultValue="deployProxyByImplementation"
|
||||
onChange={(selectedFn) =>
|
||||
form.setValue(
|
||||
"factoryDeploymentData.customFactoryInput.factoryFunction",
|
||||
selectedFn,
|
||||
)
|
||||
}
|
||||
value={form.watch(
|
||||
</div>
|
||||
|
||||
{/* Factory function */}
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold tracking-tight mb-1">
|
||||
Factory function
|
||||
</h2>
|
||||
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Choose the factory function to deploy your contracts.
|
||||
</p>
|
||||
|
||||
{customFactoryAbi?.data ? (
|
||||
<AbiSelector
|
||||
abi={customFactoryAbi.data}
|
||||
defaultValue="deployProxyByImplementation"
|
||||
onChange={(selectedFn) =>
|
||||
form.setValue(
|
||||
"factoryDeploymentData.customFactoryInput.factoryFunction",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<Text fontStyle="italic">
|
||||
Custom factory ABI not found. Please provide a valid imported
|
||||
contract on the previous step.
|
||||
</Text>
|
||||
)}
|
||||
</FormControl>
|
||||
</Flex>
|
||||
</Flex>
|
||||
selectedFn,
|
||||
)
|
||||
}
|
||||
value={form.watch(
|
||||
"factoryDeploymentData.customFactoryInput.factoryFunction",
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-red-500 font-medium">
|
||||
Custom factory ABI not found. Please provide a valid imported
|
||||
contract on the previous step.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+44
-48
@@ -1,10 +1,7 @@
|
||||
import { Flex, FormControl, ListItem, UnorderedList } from "@chakra-ui/react";
|
||||
import type { Abi } from "abitype";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { UnderlineLink } from "../../ui/UnderlineLink";
|
||||
import { AbiSelector } from "./abi-selector";
|
||||
import { NetworksFieldset } from "./networks-fieldset";
|
||||
|
||||
@@ -13,63 +10,62 @@ interface DefaultFactoryProps {
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const DefaultFactory: React.FC<DefaultFactoryProps> = ({
|
||||
abi,
|
||||
client,
|
||||
}) => {
|
||||
export function DefaultFactory({ abi, client }: DefaultFactoryProps) {
|
||||
const form = useFormContext();
|
||||
|
||||
return (
|
||||
<Flex flexDir="column" gap={12} pb={0} px={0}>
|
||||
<UnorderedList>
|
||||
<Text as={ListItem}>
|
||||
<div className="space-y-12">
|
||||
{/* Description */}
|
||||
<div className="space-y-1.5 text-sm text-muted-foreground">
|
||||
<p>
|
||||
Default factory lets users deploy your contract to{" "}
|
||||
<strong>any EVM network</strong>.
|
||||
</Text>
|
||||
<Text as={ListItem}>
|
||||
<em className="font-medium">any EVM network</em>.
|
||||
</p>
|
||||
<p>
|
||||
The factory deploys EIP-1167 minimal proxies of your contract. This
|
||||
makes it much cheaper to deploy.
|
||||
</Text>
|
||||
<Text as={ListItem}>
|
||||
</p>
|
||||
<p>
|
||||
The factory is{" "}
|
||||
<Link
|
||||
color="primary.500"
|
||||
<UnderlineLink
|
||||
href="https://github.com/thirdweb-dev/contracts/blob/main/contracts/TWStatelessFactory.sol"
|
||||
isExternal
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
open-source
|
||||
</Link>
|
||||
</UnderlineLink>
|
||||
, permissionless, and does not alter contract ownership.
|
||||
</Text>
|
||||
<Text as={ListItem}>
|
||||
</p>
|
||||
<p>
|
||||
Your contract needs to be written in the upgradeable/initializable
|
||||
pattern. It needs to contain an initializer function.
|
||||
</Text>
|
||||
</UnorderedList>
|
||||
<Flex flexDir="column" gap={4}>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Initializer function</Heading>
|
||||
<Text>
|
||||
Choose the initializer function to invoke on your proxy contracts.
|
||||
</Text>
|
||||
</Flex>
|
||||
<FormControl isRequired>
|
||||
<AbiSelector
|
||||
abi={abi}
|
||||
defaultValue="initialize"
|
||||
onChange={(selectedFn) =>
|
||||
form.setValue(
|
||||
"factoryDeploymentData.implementationInitializerFunction",
|
||||
selectedFn,
|
||||
)
|
||||
}
|
||||
value={form.watch(
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Initializer function */}
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-1">Initializer function</h3>
|
||||
<p className="text-muted-foreground text-sm mb-4">
|
||||
Choose the initializer function to invoke on your proxy contracts.
|
||||
</p>
|
||||
|
||||
<AbiSelector
|
||||
abi={abi}
|
||||
defaultValue="initialize"
|
||||
onChange={(selectedFn) =>
|
||||
form.setValue(
|
||||
"factoryDeploymentData.implementationInitializerFunction",
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
</Flex>
|
||||
selectedFn,
|
||||
)
|
||||
}
|
||||
value={form.watch(
|
||||
"factoryDeploymentData.implementationInitializerFunction",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Networks */}
|
||||
<NetworksFieldset client={client} />
|
||||
</Flex>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+12
-22
@@ -1,5 +1,4 @@
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useEffect } from "react";
|
||||
import { useFieldArray, useFormContext } from "react-hook-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ExternalLinksInput } from "./external-links-input";
|
||||
@@ -12,35 +11,26 @@ export const ExternalLinksFieldset = () => {
|
||||
name: "externalLinks",
|
||||
});
|
||||
|
||||
// FIXME: all of this logic needs to be reworked
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
useEffect(() => {
|
||||
if (fields.length === 0) {
|
||||
append(
|
||||
{
|
||||
name: "",
|
||||
url: "",
|
||||
},
|
||||
{ shouldFocus: false },
|
||||
);
|
||||
}
|
||||
}, [fields, append]);
|
||||
|
||||
return (
|
||||
<fieldset className="flex flex-col gap-8">
|
||||
<div className="flex flex-col gap-2">
|
||||
<h3 className="font-semibold text-xl tracking-tight">Resources</h3>
|
||||
<p className="text-muted-foreground">
|
||||
<fieldset>
|
||||
<div>
|
||||
<h3 className="font-semibold text-xl tracking-tight mb-1">Resources</h3>
|
||||
<p className="text-muted-foreground text-sm mb-5">
|
||||
Provide links to docs, usage guides etc. for the contract.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
{fields.map((item, index) => (
|
||||
<ExternalLinksInput index={index} key={item.id} remove={remove} />
|
||||
<ExternalLinksInput
|
||||
index={index}
|
||||
key={item.id}
|
||||
remove={remove}
|
||||
disableRemove={fields.length === 1}
|
||||
/>
|
||||
))}
|
||||
<div>
|
||||
<Button
|
||||
className="gap-2"
|
||||
className="gap-2 bg-card rounded-full"
|
||||
onClick={() =>
|
||||
append({
|
||||
name: "",
|
||||
@@ -51,7 +41,7 @@ export const ExternalLinksFieldset = () => {
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<PlusIcon className="size-5" />
|
||||
<PlusIcon className="size-4" />
|
||||
Add Resource
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
+62
-62
@@ -3,82 +3,82 @@ import { useFormContext } from "react-hook-form";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
interface ExternalLinksInputProps {
|
||||
index: number;
|
||||
remove: (index: number) => void;
|
||||
disableRemove: boolean;
|
||||
}
|
||||
|
||||
export const ExternalLinksInput: React.FC<ExternalLinksInputProps> = ({
|
||||
index,
|
||||
remove,
|
||||
disableRemove,
|
||||
}) => {
|
||||
const form = useFormContext();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex w-full flex-col gap-4 md:flex-row md:gap-2">
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<Label className="capitalize" htmlFor={`externalLinks.${index}.name`}>
|
||||
Resource Name
|
||||
</Label>
|
||||
<Input
|
||||
id={`externalLinks.${index}.name`}
|
||||
placeholder="Resource name"
|
||||
{...form.register(`externalLinks.${index}.name`)}
|
||||
/>
|
||||
{form.getFieldState(`externalLinks.${index}.name`, form.formState)
|
||||
.error?.message && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
{
|
||||
form.getFieldState(
|
||||
`externalLinks.${index}.name`,
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<Label className="capitalize" htmlFor={`externalLinks.${index}.url`}>
|
||||
Link
|
||||
</Label>
|
||||
<Input
|
||||
id={`externalLinks.${index}.url`}
|
||||
placeholder="Provide URL to the resource page"
|
||||
{...form.register(`externalLinks.${index}.url`, {
|
||||
required: true,
|
||||
validate: (value: string) => {
|
||||
if (value.match(new RegExp(/^https:\/\/[^\s/$.?#].[^\s]*$/))) {
|
||||
return true;
|
||||
}
|
||||
return "Provide a valid URL";
|
||||
},
|
||||
})}
|
||||
/>
|
||||
{form.getFieldState(`externalLinks.${index}.url`, form.formState)
|
||||
.error?.message && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
{
|
||||
form.getFieldState(`externalLinks.${index}.url`, form.formState)
|
||||
.error?.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
aria-label="Remove row"
|
||||
className="self-end"
|
||||
onClick={() => remove(index)}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
>
|
||||
<TrashIcon className="size-5" />
|
||||
<span className="sr-only">Remove row</span>
|
||||
</Button>
|
||||
<div className="flex w-full flex-col gap-3 md:flex-row">
|
||||
{/* Resource name */}
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label className="capitalize" htmlFor={`externalLinks.${index}.name`}>
|
||||
Name
|
||||
</Label>
|
||||
<Input
|
||||
id={`externalLinks.${index}.name`}
|
||||
{...form.register(`externalLinks.${index}.name`)}
|
||||
className="bg-card"
|
||||
/>
|
||||
{form.getFieldState(`externalLinks.${index}.name`, form.formState).error
|
||||
?.message && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
{
|
||||
form.getFieldState(`externalLinks.${index}.name`, form.formState)
|
||||
.error?.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
|
||||
{/* Resource URL */}
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label className="capitalize" htmlFor={`externalLinks.${index}.url`}>
|
||||
Link
|
||||
</Label>
|
||||
<Input
|
||||
id={`externalLinks.${index}.url`}
|
||||
className="bg-card"
|
||||
{...form.register(`externalLinks.${index}.url`, {
|
||||
required: true,
|
||||
validate: (value: string) => {
|
||||
if (value.match(new RegExp(/^https:\/\/[^\s/$.?#].[^\s]*$/))) {
|
||||
return true;
|
||||
}
|
||||
return "Provide a valid URL";
|
||||
},
|
||||
})}
|
||||
/>
|
||||
{form.getFieldState(`externalLinks.${index}.url`, form.formState).error
|
||||
?.message && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
{
|
||||
form.getFieldState(`externalLinks.${index}.url`, form.formState)
|
||||
.error?.message
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className="self-end rounded-full p-0 bg-card"
|
||||
disabled={disableRemove}
|
||||
onClick={() => remove(index)}
|
||||
size="icon"
|
||||
variant="outline"
|
||||
aria-label="Remove resource"
|
||||
>
|
||||
<TrashIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+39
-43
@@ -1,10 +1,8 @@
|
||||
import { ButtonGroup, Flex } from "@chakra-ui/react";
|
||||
import type { Abi } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { TabButtons } from "../../ui/tabs";
|
||||
import { CustomFactory } from "./custom-factory";
|
||||
import { DefaultFactory } from "./default-factory";
|
||||
|
||||
@@ -20,47 +18,45 @@ export const FactoryFieldset: React.FC<FactoryFieldsetProps> = ({
|
||||
client,
|
||||
}) => {
|
||||
const form = useFormContext();
|
||||
const tab = form.watch("deployType");
|
||||
|
||||
return (
|
||||
<Flex as="fieldset" direction="column" gap={12}>
|
||||
<Flex direction="column" gap={6}>
|
||||
<Heading size="title.lg">Factory deploy settings</Heading>
|
||||
<ButtonGroup size="sm" spacing={{ base: 0.5, md: 2 }} variant="ghost">
|
||||
<Button
|
||||
_active={{
|
||||
bg: "bgBlack",
|
||||
color: "bgWhite",
|
||||
}}
|
||||
isActive={form.watch("deployType") === "autoFactory"}
|
||||
onClick={() => form.setValue("deployType", "autoFactory")}
|
||||
rounded="lg"
|
||||
type="button"
|
||||
>
|
||||
Default Factory
|
||||
</Button>
|
||||
<Button
|
||||
_active={{
|
||||
bg: "bgBlack",
|
||||
color: "bgWhite",
|
||||
}}
|
||||
isActive={form.watch("deployType") === "customFactory"}
|
||||
onClick={() => form.setValue("deployType", "customFactory")}
|
||||
rounded="lg"
|
||||
type="button"
|
||||
>
|
||||
Custom Factory (Advanced)
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
{form.watch("deployType") === "autoFactory" && (
|
||||
<DefaultFactory abi={abi} client={client} />
|
||||
)}
|
||||
{form.watch("deployType") === "customFactory" && (
|
||||
<CustomFactory
|
||||
client={client}
|
||||
setCustomFactoryAbi={setCustomFactoryAbi}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-1">
|
||||
Factory deploy settings
|
||||
</h2>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
Choose how you want to deploy your contract
|
||||
</p>
|
||||
|
||||
<TabButtons
|
||||
tabClassName="!text-sm font-semibold"
|
||||
tabs={[
|
||||
{
|
||||
name: "Default Factory",
|
||||
onClick: () => form.setValue("deployType", "autoFactory"),
|
||||
isActive: tab === "autoFactory",
|
||||
},
|
||||
{
|
||||
name: "Custom Factory (Advanced)",
|
||||
onClick: () => form.setValue("deployType", "customFactory"),
|
||||
isActive: tab === "customFactory",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="h-4" />
|
||||
|
||||
{form.watch("deployType") === "autoFactory" && (
|
||||
<DefaultFactory abi={abi} client={client} />
|
||||
)}
|
||||
|
||||
{form.watch("deployType") === "customFactory" && (
|
||||
<CustomFactory
|
||||
client={client}
|
||||
setCustomFactoryAbi={setCustomFactoryAbi}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+19
-21
@@ -1,4 +1,3 @@
|
||||
import { FormControl, useBreakpointValue } from "@chakra-ui/react";
|
||||
import type { AbiParameter } from "abitype";
|
||||
import { useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
@@ -7,6 +6,7 @@ import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import { Checkbox, CheckboxWithLabel } from "@/components/ui/checkbox";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useIsMobile } from "@/hooks/use-mobile";
|
||||
import { getTemplateValuesForType } from "@/lib/deployment/template-values";
|
||||
import { RefInputImplFieldset } from "./ref-contract-impl-input/ref-input-impl-fieldset";
|
||||
|
||||
@@ -19,7 +19,7 @@ export const ImplementationParamsFieldset: React.FC<
|
||||
> = ({ implParams, client }) => {
|
||||
const form = useFormContext();
|
||||
|
||||
const isMobile = useBreakpointValue({ base: true, md: false });
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const [isCustomInputEnabled, setIsCustomInputEnabled] = useState(
|
||||
Array(implParams.length).fill(false),
|
||||
@@ -119,25 +119,23 @@ export const ImplementationParamsFieldset: React.FC<
|
||||
</div>
|
||||
|
||||
{!isCustomInputEnabled[idx] ? (
|
||||
<FormControl>
|
||||
<SolidityInput
|
||||
className="!bg-background !text-sm placeholder:!text-sm"
|
||||
client={client}
|
||||
placeholder={
|
||||
isMobile ||
|
||||
paramTemplateValues?.[0]?.value ===
|
||||
"{{trusted_forwarders}}"
|
||||
? "Pre-filled value."
|
||||
: "This value will be pre-filled in the deploy form."
|
||||
}
|
||||
solidityType={param.type}
|
||||
{...form.register(
|
||||
`implConstructorParams.${
|
||||
param.name ? param.name : "*"
|
||||
}.defaultValue`,
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
<SolidityInput
|
||||
className="!bg-background !text-sm placeholder:!text-sm"
|
||||
client={client}
|
||||
placeholder={
|
||||
isMobile ||
|
||||
paramTemplateValues?.[0]?.value ===
|
||||
"{{trusted_forwarders}}"
|
||||
? "Pre-filled value."
|
||||
: "This value will be pre-filled in the deploy form."
|
||||
}
|
||||
solidityType={param.type}
|
||||
{...form.register(
|
||||
`implConstructorParams.${
|
||||
param.name ? param.name : "*"
|
||||
}.defaultValue`,
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<RefInputImplFieldset client={client} param={param} />
|
||||
)}
|
||||
|
||||
+222
-270
@@ -1,9 +1,6 @@
|
||||
"use client";
|
||||
import { Box, Divider, Flex, IconButton } from "@chakra-ui/react";
|
||||
import type { Abi } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Text } from "chakra/text";
|
||||
import { ChevronFirstIcon } from "lucide-react";
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||
import { useId, useMemo, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
@@ -15,6 +12,8 @@ import {
|
||||
import { useActiveAccount, useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { reportContractPublished } from "@/analytics/report";
|
||||
import { CustomConnectWallet } from "@/components/connect-wallet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import {
|
||||
DASHBOARD_ENGINE_RELAYER_URL,
|
||||
DASHBOARD_FORWARDER_ADDRESS,
|
||||
@@ -22,7 +21,6 @@ import {
|
||||
import { useEns, useFunctionParamsFromABI } from "@/hooks/contract-hooks";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
import { useIsomorphicLayoutEffect } from "@/lib/useIsomorphicLayoutEffect";
|
||||
import { ContractParamsFieldset } from "./contract-params-fieldset";
|
||||
import { FactoryFieldset } from "./factory-fieldset";
|
||||
import { ImplementationParamsFieldset } from "./impl-params-fieldset";
|
||||
@@ -183,284 +181,238 @@ export function ContractPublishForm(props: {
|
||||
// during loading and after success we should stay in loading state
|
||||
const isPending = sendTx.isPending || sendTx.isSuccess;
|
||||
|
||||
useIsomorphicLayoutEffect(() => {
|
||||
window?.scrollTo({
|
||||
behavior: "smooth",
|
||||
top: 0,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const formId = useId();
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<div className="w-full">
|
||||
<Flex
|
||||
as="form"
|
||||
direction="column"
|
||||
gap={6}
|
||||
id={formId}
|
||||
onSubmit={form.handleSubmit((data) => {
|
||||
if (!account) {
|
||||
// no account, do nothing
|
||||
return;
|
||||
}
|
||||
const addressArray =
|
||||
Object.keys(data?.customFactoryAddresses || {}).length > 0
|
||||
? (data?.customFactoryAddresses as unknown as {
|
||||
key: number;
|
||||
value: string;
|
||||
}[])
|
||||
: [];
|
||||
<form
|
||||
className="flex flex-col gap-6"
|
||||
id={formId}
|
||||
onSubmit={form.handleSubmit((data) => {
|
||||
if (!account) {
|
||||
// no account, do nothing
|
||||
return;
|
||||
}
|
||||
const addressArray =
|
||||
Object.keys(data?.customFactoryAddresses || {}).length > 0
|
||||
? (data?.customFactoryAddresses as unknown as {
|
||||
key: number;
|
||||
value: string;
|
||||
}[])
|
||||
: [];
|
||||
|
||||
const addressObj = addressArray.reduce<Record<number, string>>(
|
||||
(obj, item) => {
|
||||
obj[item.key] = item.value;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
const addressObj = addressArray.reduce<Record<number, string>>(
|
||||
(obj, item) => {
|
||||
obj[item.key] = item.value;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
const metadata = {
|
||||
...data,
|
||||
factoryDeploymentData: {
|
||||
...data.factoryDeploymentData,
|
||||
customFactoryInput: {
|
||||
customFactoryAddresses:
|
||||
addressObj ||
|
||||
data.factoryDeploymentData?.customFactoryInput
|
||||
?.customFactoryAddresses,
|
||||
factoryFunction:
|
||||
data.factoryDeploymentData?.customFactoryInput
|
||||
?.factoryFunction || "deployProxyByImplementation",
|
||||
params:
|
||||
data.factoryDeploymentData?.customFactoryInput?.params ||
|
||||
[],
|
||||
},
|
||||
implementationAddresses:
|
||||
data.factoryDeploymentData?.implementationAddresses || {},
|
||||
implementationInitializerFunction:
|
||||
data.factoryDeploymentData
|
||||
?.implementationInitializerFunction || "initialize",
|
||||
const metadata = {
|
||||
...data,
|
||||
factoryDeploymentData: {
|
||||
...data.factoryDeploymentData,
|
||||
customFactoryInput: {
|
||||
customFactoryAddresses:
|
||||
addressObj ||
|
||||
data.factoryDeploymentData?.customFactoryInput
|
||||
?.customFactoryAddresses,
|
||||
factoryFunction:
|
||||
data.factoryDeploymentData?.customFactoryInput
|
||||
?.factoryFunction || "deployProxyByImplementation",
|
||||
params:
|
||||
data.factoryDeploymentData?.customFactoryInput?.params || [],
|
||||
},
|
||||
networksForDeployment: {
|
||||
allNetworks:
|
||||
data.deployType === "customFactory"
|
||||
? false
|
||||
: data.networksForDeployment?.allNetworks,
|
||||
networksEnabled:
|
||||
addressArray.length > 0
|
||||
? Object.keys(addressObj).map((val) => Number(val))
|
||||
: data.networksForDeployment?.networksEnabled,
|
||||
},
|
||||
} satisfies FetchDeployMetadataResult & {
|
||||
name: string;
|
||||
version: string;
|
||||
};
|
||||
implementationAddresses:
|
||||
data.factoryDeploymentData?.implementationAddresses || {},
|
||||
implementationInitializerFunction:
|
||||
data.factoryDeploymentData?.implementationInitializerFunction ||
|
||||
"initialize",
|
||||
},
|
||||
networksForDeployment: {
|
||||
allNetworks:
|
||||
data.deployType === "customFactory"
|
||||
? false
|
||||
: data.networksForDeployment?.allNetworks,
|
||||
networksEnabled:
|
||||
addressArray.length > 0
|
||||
? Object.keys(addressObj).map((val) => Number(val))
|
||||
: data.networksForDeployment?.networksEnabled,
|
||||
},
|
||||
} satisfies FetchDeployMetadataResult & {
|
||||
name: string;
|
||||
version: string;
|
||||
};
|
||||
|
||||
const tx = publishContract({
|
||||
account,
|
||||
contract: getContractPublisher(props.client),
|
||||
metadata,
|
||||
previousMetadata: props.publishMetadata,
|
||||
});
|
||||
const tx = publishContract({
|
||||
account,
|
||||
contract: getContractPublisher(props.client),
|
||||
metadata,
|
||||
previousMetadata: props.publishMetadata,
|
||||
});
|
||||
|
||||
sendTx.mutate(tx, {
|
||||
onError: (err) => {
|
||||
console.error("Failed to publish contract", err);
|
||||
onError(err);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
onSuccess();
|
||||
sendTx.mutate(tx, {
|
||||
onError: (err) => {
|
||||
console.error("Failed to publish contract", err);
|
||||
onError(err);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
onSuccess();
|
||||
|
||||
reportContractPublished({
|
||||
contractName: props.publishMetadata.name,
|
||||
deployType: data.deployType,
|
||||
publisher: ensNameOrAddress ?? "",
|
||||
version: data.version,
|
||||
});
|
||||
await props.onPublishSuccess().catch((err) => {
|
||||
console.error("Failed to run onPublishSuccess", err);
|
||||
});
|
||||
if (successRedirectUrl) {
|
||||
router.push(successRedirectUrl, { scroll: true });
|
||||
}
|
||||
},
|
||||
});
|
||||
})}
|
||||
>
|
||||
{fieldsetToShow !== "landing" && (
|
||||
<div>
|
||||
<IconButton
|
||||
aria-label="Back"
|
||||
icon={<ChevronFirstIcon className="size-6" />}
|
||||
onClick={() =>
|
||||
fieldsetToShow === "contractParams" &&
|
||||
(form.watch("deployType") === "autoFactory" ||
|
||||
form.watch("deployType") === "customFactory")
|
||||
? setFieldsetToShow("factory")
|
||||
: fieldsetToShow === "contractParams" &&
|
||||
form.watch("deployType") === "standard"
|
||||
? setFieldsetToShow("networks")
|
||||
: fieldsetToShow === "implParams"
|
||||
? setFieldsetToShow("contractParams")
|
||||
: setFieldsetToShow("landing")
|
||||
}
|
||||
variant="ghost"
|
||||
w="inherit"
|
||||
reportContractPublished({
|
||||
contractName: props.publishMetadata.name,
|
||||
deployType: data.deployType,
|
||||
publisher: ensNameOrAddress ?? "",
|
||||
version: data.version,
|
||||
});
|
||||
await props.onPublishSuccess().catch((err) => {
|
||||
console.error("Failed to run onPublishSuccess", err);
|
||||
});
|
||||
if (successRedirectUrl) {
|
||||
router.push(successRedirectUrl, { scroll: true });
|
||||
}
|
||||
},
|
||||
});
|
||||
})}
|
||||
>
|
||||
{fieldsetToShow !== "landing" && (
|
||||
<div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="-translate-x-3"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
fieldsetToShow === "contractParams" &&
|
||||
(form.watch("deployType") === "autoFactory" ||
|
||||
form.watch("deployType") === "customFactory")
|
||||
? setFieldsetToShow("factory")
|
||||
: fieldsetToShow === "contractParams" &&
|
||||
form.watch("deployType") === "standard"
|
||||
? setFieldsetToShow("networks")
|
||||
: fieldsetToShow === "implParams"
|
||||
? setFieldsetToShow("contractParams")
|
||||
: setFieldsetToShow("landing")
|
||||
}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4 mr-2" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "landing" && (
|
||||
<LandingFieldset
|
||||
client={props.client}
|
||||
latestVersion={latestVersion}
|
||||
placeholderVersion={placeholderVersion}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "contractParams" && (
|
||||
<ContractParamsFieldset
|
||||
client={props.client}
|
||||
deployParams={deployParams}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "implParams" && implDeployParams?.length > 0 && (
|
||||
<ImplementationParamsFieldset
|
||||
client={props.client}
|
||||
implParams={implDeployParams}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "factory" && (
|
||||
<div className="flex flex-col gap-24">
|
||||
<FactoryFieldset
|
||||
abi={props.publishMetadata.abi || []}
|
||||
client={props.client}
|
||||
setCustomFactoryAbi={setCustomFactoryAbi}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "networks" && (
|
||||
<NetworksFieldset client={props.client} />
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-4 justify-end border-t py-6 mt-6">
|
||||
{!account ? (
|
||||
<CustomConnectWallet
|
||||
client={props.client}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
/>
|
||||
) : fieldsetToShow === "landing" &&
|
||||
form.watch("deployType") === "standard" ? (
|
||||
<NextButton
|
||||
disabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("networks")}
|
||||
/>
|
||||
) : fieldsetToShow === "landing" &&
|
||||
(form.watch("deployType") === "autoFactory" ||
|
||||
form.watch("deployType") === "customFactory") ? (
|
||||
<NextButton
|
||||
disabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("factory")}
|
||||
/>
|
||||
) : fieldsetToShow !== "contractParams" &&
|
||||
fieldsetToShow !== "implParams" &&
|
||||
deployParams?.length > 0 ? (
|
||||
<NextButton
|
||||
disabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("contractParams")}
|
||||
/>
|
||||
) : fieldsetToShow !== "contractParams" &&
|
||||
fieldsetToShow !== "implParams" &&
|
||||
deployParams?.length === 0 &&
|
||||
implDeployParams?.length > 0 ? (
|
||||
<NextButton
|
||||
disabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("implParams")}
|
||||
/>
|
||||
) : fieldsetToShow === "contractParams" &&
|
||||
implDeployParams?.length > 0 ? (
|
||||
<NextButton
|
||||
disabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("implParams")}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-start justify-between gap-4 w-full">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Publishing your contract is free, we cover all gas costs
|
||||
</span>
|
||||
|
||||
<Button
|
||||
className="gap-2"
|
||||
form={formId}
|
||||
disabled={isDisabled}
|
||||
type="submit"
|
||||
>
|
||||
Back
|
||||
</IconButton>
|
||||
{isPending && <Spinner className="size-4" />}
|
||||
{sendTx.isSuccess
|
||||
? "Preparing page"
|
||||
: sendTx.isPending
|
||||
? "Publishing contract"
|
||||
: "Publish Contract"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "landing" && (
|
||||
<LandingFieldset
|
||||
client={props.client}
|
||||
latestVersion={latestVersion}
|
||||
placeholderVersion={placeholderVersion}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "contractParams" && (
|
||||
<ContractParamsFieldset
|
||||
client={props.client}
|
||||
deployParams={deployParams}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "implParams" && implDeployParams?.length > 0 && (
|
||||
<ImplementationParamsFieldset
|
||||
client={props.client}
|
||||
implParams={implDeployParams}
|
||||
/>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "factory" && (
|
||||
<Flex flexDir="column" gap={24}>
|
||||
<FactoryFieldset
|
||||
abi={props.publishMetadata.abi || []}
|
||||
client={props.client}
|
||||
setCustomFactoryAbi={setCustomFactoryAbi}
|
||||
/>
|
||||
</Flex>
|
||||
)}
|
||||
|
||||
{fieldsetToShow === "networks" && (
|
||||
<Flex flexDir="column" gap={24}>
|
||||
<NetworksFieldset client={props.client} fromStandard />
|
||||
</Flex>
|
||||
)}
|
||||
|
||||
<Flex flexDir="column" gap={6}>
|
||||
<Divider />
|
||||
<Flex
|
||||
alignItems="center"
|
||||
flexDir={{ base: "column", md: "row" }}
|
||||
gap={4}
|
||||
justifyContent="space-between"
|
||||
>
|
||||
{!account ? (
|
||||
<>
|
||||
<Box />
|
||||
<CustomConnectWallet
|
||||
client={props.client}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
/>
|
||||
</>
|
||||
) : fieldsetToShow === "landing" &&
|
||||
form.watch("deployType") === "standard" ? (
|
||||
<>
|
||||
<Box />
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("networks")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</>
|
||||
) : fieldsetToShow === "landing" &&
|
||||
(form.watch("deployType") === "autoFactory" ||
|
||||
form.watch("deployType") === "customFactory") ? (
|
||||
<>
|
||||
<Box />
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("factory")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</>
|
||||
) : fieldsetToShow !== "contractParams" &&
|
||||
fieldsetToShow !== "implParams" &&
|
||||
deployParams?.length > 0 ? (
|
||||
<>
|
||||
<Box />
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("contractParams")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</>
|
||||
) : fieldsetToShow !== "contractParams" &&
|
||||
fieldsetToShow !== "implParams" &&
|
||||
deployParams?.length === 0 &&
|
||||
implDeployParams?.length > 0 ? (
|
||||
<>
|
||||
<Box />
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("implParams")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</>
|
||||
) : fieldsetToShow === "contractParams" &&
|
||||
implDeployParams?.length > 0 ? (
|
||||
<>
|
||||
<Box />
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={disableNext}
|
||||
onClick={() => setFieldsetToShow("implParams")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Text fontStyle="italic">
|
||||
Publishing your contract is free, we cover all gas costs.
|
||||
</Text>
|
||||
<Button
|
||||
// differentiate this from the edit button
|
||||
borderRadius="md"
|
||||
colorScheme="blue"
|
||||
form={formId}
|
||||
isDisabled={isDisabled}
|
||||
isLoading={isPending}
|
||||
key="submit-button"
|
||||
loadingText={
|
||||
sendTx.isSuccess
|
||||
? "Preparing page"
|
||||
: "Publishing contract"
|
||||
}
|
||||
position="relative"
|
||||
type="submit"
|
||||
>
|
||||
Publish Contract
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function NextButton(props: { disabled: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<Button
|
||||
disabled={props.disabled}
|
||||
onClick={props.onClick}
|
||||
className="gap-2 w-32"
|
||||
>
|
||||
Next
|
||||
<ArrowRightIcon className="size-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
+189
-170
@@ -1,41 +1,30 @@
|
||||
import {
|
||||
Box,
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
Textarea,
|
||||
} from "@chakra-ui/react";
|
||||
import { Card } from "chakra/card";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import { compare, validate } from "compare-versions";
|
||||
import { useState } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { ExtendedMetadata } from "thirdweb/utils";
|
||||
import { SelectOption } from "@/components/batch-upload/lazy-mint-form/select-option";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { MarkdownRenderer } from "../../blocks/markdown-renderer";
|
||||
import { TabButtons } from "../../ui/tabs";
|
||||
import { UnderlineLink } from "../../ui/UnderlineLink";
|
||||
import { ExternalLinksFieldset } from "./external-links-fieldset";
|
||||
|
||||
interface LandingFieldsetProps {
|
||||
type LandingFieldsetProps = {
|
||||
latestVersion: string | undefined;
|
||||
placeholderVersion: string;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
};
|
||||
|
||||
export const LandingFieldset: React.FC<LandingFieldsetProps> = ({
|
||||
export function LandingFieldset({
|
||||
latestVersion,
|
||||
placeholderVersion,
|
||||
client,
|
||||
}) => {
|
||||
}: LandingFieldsetProps) {
|
||||
const form = useFormContext<ExtendedMetadata>();
|
||||
const logoUrl = form.watch("logo");
|
||||
|
||||
@@ -66,205 +55,235 @@ export const LandingFieldset: React.FC<LandingFieldsetProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const [readmeTab, setReadmeTab] = useState<"write" | "preview">("write");
|
||||
const [changelogTab, setChangelogTab] = useState<"write" | "preview">(
|
||||
"write",
|
||||
);
|
||||
|
||||
return (
|
||||
<Flex as="fieldset" direction="column" gap={16} mt={{ base: 4, md: 12 }}>
|
||||
<Flex direction="column" gap={2}>
|
||||
<Heading size="title.lg">
|
||||
<fieldset className="space-y-12">
|
||||
{/* header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight mb-1">
|
||||
{!latestVersion ? "Publish" : "Edit"} your contract
|
||||
</Heading>
|
||||
<Text fontStyle="normal">
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Publishing your contract makes it shareable, discoverable, and
|
||||
deployable in a single click.{" "}
|
||||
<Link
|
||||
color="blue.500"
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/contracts/publish/overview"
|
||||
isExternal
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Learn more
|
||||
</Link>
|
||||
</Text>
|
||||
</Flex>
|
||||
<Flex gap={6} w="full">
|
||||
<FormControl isInvalid={!!form.formState.errors.logo} w="auto">
|
||||
<FormLabel>Image</FormLabel>
|
||||
<Box width="141px">
|
||||
</UnderlineLink>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* logo, name, description */}
|
||||
<div className="flex flex-col md:flex-row gap-6 w-full">
|
||||
<FormFieldSetup
|
||||
label="Image"
|
||||
errorMessage={form.formState.errors?.logo?.message as string}
|
||||
isRequired={false}
|
||||
className="w-auto"
|
||||
>
|
||||
<div className="w-[200px]">
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border border-border transition-all duration-200"
|
||||
className="rounded-lg border bg-card transition-all duration-200"
|
||||
client={client}
|
||||
helperText="Image"
|
||||
// @ts-expect-error - we upload the file later this is fine
|
||||
setValue={(file) => form.setValue("logo", file)}
|
||||
value={logoUrl}
|
||||
/>
|
||||
</Box>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.logo?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<Flex flexDir="column" gap={4} w="full">
|
||||
<FormControl
|
||||
isInvalid={!!form.formState.errors.displayName}
|
||||
isRequired
|
||||
</div>
|
||||
</FormFieldSetup>
|
||||
|
||||
<div className="flex flex-col gap-4 w-full grow">
|
||||
<FormFieldSetup
|
||||
htmlFor="displayName"
|
||||
label="Contract Name"
|
||||
errorMessage={form.formState.errors?.displayName?.message}
|
||||
isRequired={true}
|
||||
>
|
||||
<FormLabel>Contract Name</FormLabel>
|
||||
<Input
|
||||
id="displayName"
|
||||
onChange={(e) => form.setValue("displayName", e.target.value)}
|
||||
placeholder="Ex. MyContract"
|
||||
className="bg-card"
|
||||
value={form.watch("displayName")}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.displayName?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!form.formState.errors.description}>
|
||||
<FormLabel>Description</FormLabel>
|
||||
</FormFieldSetup>
|
||||
|
||||
<FormFieldSetup
|
||||
htmlFor="description"
|
||||
label="Description"
|
||||
errorMessage={form.formState.errors?.description?.message}
|
||||
isRequired={false}
|
||||
className="grow flex flex-col"
|
||||
>
|
||||
<Textarea
|
||||
id="description"
|
||||
onChange={(e) => form.setValue("description", e.target.value)}
|
||||
placeholder="Briefly describe what your contract does."
|
||||
rows={2}
|
||||
className="bg-card grow"
|
||||
value={form.watch("description")}
|
||||
/>
|
||||
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.description?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Heading mb={2} size="title.md">
|
||||
README
|
||||
</Heading>
|
||||
<Text mb={4} size="body.md">
|
||||
<h2 className="text-xl font-semibold mb-1 tracking-tight">README</h2>
|
||||
<p className="text-muted-foreground text-sm mb-5">
|
||||
Describe what your contract does and how it should be used. Markdown
|
||||
formatting is supported.
|
||||
</Text>
|
||||
<FormControl isInvalid={!!form.formState.errors.readme}>
|
||||
<Tabs colorScheme="gray" isLazy lazyBehavior="keepMounted">
|
||||
<TabList
|
||||
borderBottomColor="borderColor"
|
||||
borderBottomWidth="1px"
|
||||
px={0}
|
||||
>
|
||||
<Tab gap={2}>
|
||||
<Heading size="label.lg">Write</Heading>
|
||||
</Tab>
|
||||
<Tab gap={2}>
|
||||
<Heading size="label.lg">Preview</Heading>
|
||||
</Tab>
|
||||
</TabList>
|
||||
<TabPanels pt={2}>
|
||||
<TabPanel pb={0} px={0}>
|
||||
<Textarea
|
||||
{...form.register("readme")}
|
||||
placeholder="Describe how users can use this contract. Add links if relevant."
|
||||
rows={12}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.readme?.message}
|
||||
</FormErrorMessage>
|
||||
</TabPanel>
|
||||
<TabPanel pb={0} px={0}>
|
||||
<Card>
|
||||
<MarkdownRenderer markdownText={form.watch("readme") || ""} />
|
||||
</Card>
|
||||
</TabPanel>
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
</FormControl>
|
||||
</p>
|
||||
|
||||
<TabButtons
|
||||
tabClassName="!text-sm"
|
||||
tabs={[
|
||||
{
|
||||
name: "Write",
|
||||
onClick: () => setReadmeTab("write"),
|
||||
isActive: readmeTab === "write",
|
||||
},
|
||||
{
|
||||
name: "Preview",
|
||||
onClick: () => setReadmeTab("preview"),
|
||||
isActive: readmeTab === "preview",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="mt-2">
|
||||
{readmeTab === "write" && (
|
||||
<Textarea
|
||||
{...form.register("readme")}
|
||||
placeholder="Describe how users can use this contract. Add links if relevant."
|
||||
rows={12}
|
||||
className="bg-card"
|
||||
/>
|
||||
)}
|
||||
|
||||
{readmeTab === "preview" && (
|
||||
<div className="p-4 rounded-lg border border-border bg-card">
|
||||
<MarkdownRenderer markdownText={form.watch("readme") || ""} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{form.formState.errors.readme && (
|
||||
<p className="text-red-500 text-sm mt-2">
|
||||
{form.formState.errors.readme.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ExternalLinksFieldset />
|
||||
|
||||
<div>
|
||||
<Heading mb={2} size="title.md">
|
||||
Version information
|
||||
</Heading>
|
||||
<Text mb={4} size="body.md">
|
||||
<h2 className="text-xl font-semibold mb-1">Version information</h2>
|
||||
<p className="text-muted-foreground text-sm mb-5">
|
||||
Set your contract version number, add release notes, and link to your
|
||||
contract's audit report.
|
||||
</Text>
|
||||
<Flex flexDir="column" gap={6}>
|
||||
<FormControl isInvalid={!!form.formState.errors.version} isRequired>
|
||||
<Flex alignItems="center" mb={1}>
|
||||
<FormLabel flex="1" mb={0}>
|
||||
Version
|
||||
</FormLabel>
|
||||
{latestVersion && (
|
||||
<Text size="body.md">latest version: {latestVersion}</Text>
|
||||
)}
|
||||
</Flex>
|
||||
</p>
|
||||
|
||||
<div className="space-y-6">
|
||||
<FormFieldSetup
|
||||
htmlFor="version"
|
||||
label={
|
||||
<div className="flex items-center justify-between w-full">
|
||||
<span>Version</span>
|
||||
{latestVersion && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
latest version: {latestVersion}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
errorMessage={form.formState.errors?.version?.message}
|
||||
isRequired={true}
|
||||
>
|
||||
<Input
|
||||
id="version"
|
||||
onChange={handleVersionChange}
|
||||
className="bg-card"
|
||||
placeholder={placeholderVersion}
|
||||
value={form.watch("version")}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.version?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</FormFieldSetup>
|
||||
|
||||
{latestVersion && (
|
||||
<FormControl isInvalid={!!form.formState.errors.changelog}>
|
||||
<FormLabel>Release notes</FormLabel>
|
||||
<Tabs colorScheme="gray" isLazy lazyBehavior="keepMounted">
|
||||
<TabList
|
||||
borderBottomColor="borderColor"
|
||||
borderBottomWidth="1px"
|
||||
px={0}
|
||||
>
|
||||
<Tab gap={2}>
|
||||
<Heading size="label.lg">Write</Heading>
|
||||
</Tab>
|
||||
<Tab gap={2}>
|
||||
<Heading size="label.lg">Preview</Heading>
|
||||
</Tab>
|
||||
</TabList>
|
||||
<TabPanels pt={2}>
|
||||
<TabPanel pb={0} px={0}>
|
||||
<Textarea
|
||||
{...form.register("changelog")}
|
||||
placeholder="Mention what is new in this version of your contract."
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-2">Release notes</h3>
|
||||
{form.formState.errors?.changelog?.message && (
|
||||
<p className="text-red-500 text-sm mt-2">
|
||||
{form.formState.errors.changelog.message}
|
||||
</p>
|
||||
)}
|
||||
<TabButtons
|
||||
tabClassName="!text-sm"
|
||||
tabs={[
|
||||
{
|
||||
name: "Write",
|
||||
onClick: () => setChangelogTab("write"),
|
||||
isActive: changelogTab === "write",
|
||||
},
|
||||
{
|
||||
name: "Preview",
|
||||
onClick: () => setChangelogTab("preview"),
|
||||
isActive: changelogTab === "preview",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="mt-2">
|
||||
{changelogTab === "write" && (
|
||||
<Textarea
|
||||
{...form.register("changelog")}
|
||||
placeholder="Mention what is new in this version of your contract."
|
||||
className="bg-card"
|
||||
/>
|
||||
)}
|
||||
|
||||
{changelogTab === "preview" && (
|
||||
<div className="p-4 rounded-lg border bg-card">
|
||||
<MarkdownRenderer
|
||||
markdownText={form.watch("changelog") || ""}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.changelog?.message}
|
||||
</FormErrorMessage>
|
||||
</TabPanel>
|
||||
<TabPanel pb={0} px={0}>
|
||||
<Card>
|
||||
<MarkdownRenderer
|
||||
markdownText={form.watch("changelog") || ""}
|
||||
/>
|
||||
</Card>
|
||||
</TabPanel>
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
</FormControl>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<FormControl isInvalid={!!form.formState.errors.audit}>
|
||||
<FormLabel>Audit report</FormLabel>
|
||||
|
||||
<FormFieldSetup
|
||||
label="Audit report"
|
||||
errorMessage={form.formState.errors?.audit?.message}
|
||||
isRequired={false}
|
||||
helperText="You can add a IPFS hash or URL pointing to an audit report, or add a file and we'll upload it to IPFS."
|
||||
>
|
||||
<SolidityInput
|
||||
client={client}
|
||||
solidityType="string"
|
||||
{...form.register("audit")}
|
||||
placeholder="ipfs://... or https://..."
|
||||
className="bg-card"
|
||||
/>
|
||||
<FormHelperText>
|
||||
<Text size="body.sm">
|
||||
You can add a IPFS hash or URL pointing to an audit report, or
|
||||
add a file and we'll upload it to IPFS.
|
||||
</Text>
|
||||
</FormHelperText>
|
||||
</FormControl>
|
||||
</Flex>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Heading mb={2} size="title.md">
|
||||
Deployment options
|
||||
</Heading>
|
||||
<Text mb={4} size="body.md">
|
||||
<h2 className="text-xl font-semibold mb-1">Deployment options</h2>
|
||||
<p className="text-muted-foreground text-sm mb-3">
|
||||
Choose how users will deploy your published contract.
|
||||
</Text>
|
||||
<Flex flexDir="column" gap={2} width="full">
|
||||
</p>
|
||||
<div className="flex flex-col md:flex-row gap-4 w-full">
|
||||
<SelectOption
|
||||
className="w-full"
|
||||
description="Users will directly deploy the full contract."
|
||||
@@ -282,8 +301,8 @@ export const LandingFieldset: React.FC<LandingFieldsetProps> = ({
|
||||
name="Deploy via factory"
|
||||
onClick={() => form.setValue("deployType", "autoFactory")}
|
||||
/>
|
||||
</Flex>
|
||||
</div>
|
||||
</div>
|
||||
</Flex>
|
||||
</fieldset>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+36
-40
@@ -1,5 +1,3 @@
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { MultiNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
||||
@@ -10,57 +8,55 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface NetworksFieldsetProps {
|
||||
fromStandard?: boolean;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const NetworksFieldset: React.FC<NetworksFieldsetProps> = ({
|
||||
fromStandard,
|
||||
client,
|
||||
}) => {
|
||||
const form = useFormContext();
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col", fromStandard ? "gap-6" : "gap-4")}>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size={fromStandard ? "title.lg" : "title.md"}>
|
||||
Networks that your contract can be deployed to
|
||||
</Heading>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2" data-required>
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
form.setValue("networksForDeployment.allNetworks", value === "all")
|
||||
}
|
||||
value={
|
||||
form.watch("networksForDeployment.allNetworks") ? "all" : "specific"
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All networks</SelectItem>
|
||||
<SelectItem value="specific">Specific networks</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold tracking-tight mb-1">
|
||||
Select networks
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm mb-4">
|
||||
Select the networks that your contract can be deployed to
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
form.setValue("networksForDeployment.allNetworks", value === "all")
|
||||
}
|
||||
value={
|
||||
form.watch("networksForDeployment.allNetworks") ? "all" : "specific"
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full bg-card">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All networks</SelectItem>
|
||||
<SelectItem value="specific">Specific networks</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{!form.watch("networksForDeployment.allNetworks") && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Text>Please select the networks you want to enable:</Text>
|
||||
<MultiNetworkSelector
|
||||
client={client}
|
||||
onChange={(chainIds) =>
|
||||
form.setValue("networksForDeployment.networksEnabled", chainIds)
|
||||
}
|
||||
selectedChainIds={
|
||||
form.watch("networksForDeployment.networksEnabled") || []
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<MultiNetworkSelector
|
||||
className="bg-card"
|
||||
client={client}
|
||||
onChange={(chainIds) =>
|
||||
form.setValue("networksForDeployment.networksEnabled", chainIds)
|
||||
}
|
||||
selectedChainIds={
|
||||
form.watch("networksForDeployment.networksEnabled") || []
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
+5
-9
@@ -1,20 +1,16 @@
|
||||
import type { AbiParameter } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useFieldArray, useFormContext } from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { RefContractImplInput } from "./ref-input-impl";
|
||||
|
||||
interface RefInputImplFieldsetProps {
|
||||
export function RefInputImplFieldset(props: {
|
||||
param: AbiParameter;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const RefInputImplFieldset: React.FC<RefInputImplFieldsetProps> = ({
|
||||
param,
|
||||
client,
|
||||
}) => {
|
||||
}) {
|
||||
const { param, client } = props;
|
||||
const form = useFormContext();
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
@@ -63,4 +59,4 @@ export const RefInputImplFieldset: React.FC<RefInputImplFieldsetProps> = ({
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,32 +1,11 @@
|
||||
"use client";
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertIcon,
|
||||
AlertTitle,
|
||||
Flex,
|
||||
GridItem,
|
||||
List,
|
||||
ListItem,
|
||||
SimpleGrid,
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
useBreakpointValue,
|
||||
} from "@chakra-ui/react";
|
||||
import {
|
||||
type Abi,
|
||||
type AbiEvent,
|
||||
type AbiFunction,
|
||||
formatAbiItem,
|
||||
} from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Card } from "chakra/card";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
import * as ERC20Ext from "thirdweb/extensions/erc20";
|
||||
@@ -35,23 +14,19 @@ import * as ERC1155Ext from "thirdweb/extensions/erc1155";
|
||||
import * as ERC4337Ext from "thirdweb/extensions/erc4337";
|
||||
import { useActiveAccount } from "thirdweb/react";
|
||||
import { toFunctionSelector } from "thirdweb/utils";
|
||||
|
||||
import {
|
||||
type CodeEnvironment,
|
||||
CodeSegment,
|
||||
} from "@/components/blocks/code/code-segment.client";
|
||||
import { getContractFunctionsFromAbi } from "@/components/contract-components/getContractFunctionsFromAbi";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { useAllChainsData } from "@/hooks/chains/allChains";
|
||||
import { useContractEvents } from "@/hooks/contract-hooks";
|
||||
|
||||
interface CodeOverviewProps {
|
||||
abi?: Abi;
|
||||
contractAddress?: string;
|
||||
onlyInstall?: boolean;
|
||||
chainId: number;
|
||||
noSidebar?: boolean;
|
||||
}
|
||||
import { useIsMobile } from "@/hooks/use-mobile";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const COMMANDS = {
|
||||
events: {
|
||||
@@ -434,7 +409,7 @@ const EXTENSION_NAMESPACE_FUNCTION_MAPPING = {
|
||||
>
|
||||
>;
|
||||
|
||||
interface SnippetOptions {
|
||||
type SnippetOptions = {
|
||||
contractAddress?: string;
|
||||
fn?: AbiFunction | AbiEvent;
|
||||
args?: string[];
|
||||
@@ -442,7 +417,7 @@ interface SnippetOptions {
|
||||
clientId?: string;
|
||||
chainId?: number;
|
||||
extensionNamespace?: string;
|
||||
}
|
||||
};
|
||||
|
||||
export function formatSnippet(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
@@ -537,13 +512,21 @@ export function formatSnippet(
|
||||
return code;
|
||||
}
|
||||
|
||||
export const CodeOverview: React.FC<CodeOverviewProps> = ({
|
||||
abi,
|
||||
contractAddress = "0x...",
|
||||
onlyInstall = false,
|
||||
noSidebar = false,
|
||||
chainId,
|
||||
}) => {
|
||||
export function CodeOverview(props: {
|
||||
abi?: Abi;
|
||||
contractAddress?: string;
|
||||
onlyInstall?: boolean;
|
||||
chainId: number;
|
||||
noSidebar?: boolean;
|
||||
}) {
|
||||
const {
|
||||
abi,
|
||||
contractAddress = "0x...",
|
||||
onlyInstall = false,
|
||||
noSidebar = false,
|
||||
chainId,
|
||||
} = props;
|
||||
|
||||
const searchParams = useSearchParams();
|
||||
const defaultEnvironment = searchParams?.get("environment") as
|
||||
| CodeEnvironment
|
||||
@@ -556,7 +539,7 @@ export const CodeOverview: React.FC<CodeOverviewProps> = ({
|
||||
const [tab, setTab] = useState("write");
|
||||
|
||||
const address = useActiveAccount()?.address;
|
||||
const isMobile = useBreakpointValue({ base: true, md: false });
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
const functionSelectors = useMemo(() => {
|
||||
return (abi || [])
|
||||
@@ -626,340 +609,306 @@ export const CodeOverview: React.FC<CodeOverviewProps> = ({
|
||||
events && events.length > 0 ? events[0] : undefined,
|
||||
);
|
||||
|
||||
const tabList = useMemo(() => {
|
||||
const _tablist: Array<{
|
||||
name: string;
|
||||
onClick: () => void;
|
||||
isActive: boolean;
|
||||
}> = [];
|
||||
|
||||
if (writeFunctions && writeFunctions.length > 0) {
|
||||
_tablist.push({
|
||||
name: "Write",
|
||||
onClick: () => setTab("write"),
|
||||
isActive: tab === "write",
|
||||
});
|
||||
}
|
||||
|
||||
if (readFunctions && readFunctions.length > 0) {
|
||||
_tablist.push({
|
||||
name: "Read",
|
||||
onClick: () => setTab("read"),
|
||||
isActive: tab === "read",
|
||||
});
|
||||
}
|
||||
|
||||
if (events && events.length > 0) {
|
||||
_tablist.push({
|
||||
name: "Events",
|
||||
onClick: () => setTab("events"),
|
||||
isActive: tab === "events",
|
||||
});
|
||||
}
|
||||
|
||||
return _tablist;
|
||||
}, [writeFunctions, readFunctions, events, tab]);
|
||||
|
||||
return (
|
||||
<SimpleGrid
|
||||
columns={12}
|
||||
display={{ base: "block", md: "grid" }}
|
||||
gap={16}
|
||||
justifyContent="space-between"
|
||||
maxW="full"
|
||||
overflowX={{ base: "scroll", md: "hidden" }}
|
||||
>
|
||||
<GridItem as={Flex} colSpan={12} flexDir="column" gap={12}>
|
||||
{isAccountFactory && (
|
||||
<Flex flexDirection="column" gap={4}>
|
||||
<Flex flexDir="column" gap={6}>
|
||||
<Heading size="title.md">Integrate your account factory</Heading>
|
||||
<Alert
|
||||
alignItems="start"
|
||||
as={Flex}
|
||||
borderRadius="md"
|
||||
flexDir="column"
|
||||
gap={2}
|
||||
status="info"
|
||||
>
|
||||
<Flex justifyContent="start">
|
||||
<AlertIcon />
|
||||
<AlertTitle>Account Factory</AlertTitle>
|
||||
</Flex>
|
||||
<AlertDescription>
|
||||
The recommended way to use account factories is to integrate
|
||||
the{" "}
|
||||
<UnderlineLink
|
||||
className="text-primary-500"
|
||||
href="https://portal.thirdweb.com/connect/account-abstraction/overview"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
thirdweb SDK
|
||||
</UnderlineLink>{" "}
|
||||
in your applications. This will ensure account contracts are
|
||||
deployed for your users only when they need it.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
hideTabs
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={formatSnippet(
|
||||
(WALLETS_SNIPPETS.find((w) => w.id === "smart-wallet")
|
||||
?.supportedLanguages || {}) as Record<
|
||||
CodeEnvironment,
|
||||
string
|
||||
>,
|
||||
{
|
||||
address,
|
||||
chainId,
|
||||
contractAddress,
|
||||
},
|
||||
)}
|
||||
/>
|
||||
</Flex>
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div className="space-y-12">
|
||||
{isAccountFactory && (
|
||||
<AccountFactorySection
|
||||
address={address}
|
||||
chainId={chainId}
|
||||
contractAddress={contractAddress}
|
||||
environment={environment}
|
||||
setEnvironment={setEnvironment}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold tracking-tight">
|
||||
{isAccountFactory
|
||||
? "Direct contract interaction (advanced)"
|
||||
: chainInfo
|
||||
? "Interact with this contract from your app"
|
||||
: "Getting Started"}
|
||||
</h2>
|
||||
</div>
|
||||
{(noSidebar || isMobile) && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-sm text-muted-foreground">Choose a language:</p>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
onlyTabs
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={COMMANDS.install}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Flex flexDirection="column" gap={4}>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">
|
||||
{isAccountFactory
|
||||
? "Direct contract interaction (advanced)"
|
||||
: chainInfo
|
||||
? "Interact with this contract from your app"
|
||||
: "Getting Started"}
|
||||
</Heading>
|
||||
</Flex>
|
||||
{(noSidebar || isMobile) && (
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Text>Choose a language:</Text>
|
||||
<div className="flex flex-col gap-2">
|
||||
{environment === "react-native" || environment === "unity" ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install the latest version of the SDK.{" "}
|
||||
<UnderlineLink
|
||||
className="text-primary-500"
|
||||
href={`https://portal.thirdweb.com/${environment}`}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Learn how in the{" "}
|
||||
{environment === "react-native" ? "React Native" : "Unity"}{" "}
|
||||
documentation
|
||||
</UnderlineLink>
|
||||
.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install the latest version of the SDK:
|
||||
</p>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
onlyTabs
|
||||
hideTabs
|
||||
isInstallCommand
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={COMMANDS.install}
|
||||
/>
|
||||
</Flex>
|
||||
</>
|
||||
)}
|
||||
<Flex flexDir="column" gap={2}>
|
||||
{environment === "react-native" || environment === "unity" ? (
|
||||
<Text>
|
||||
Install the latest version of the SDK. <br />
|
||||
<UnderlineLink
|
||||
className="text-primary-500"
|
||||
href={`https://portal.thirdweb.com/${environment}`}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Learn how in the{" "}
|
||||
{environment === "react-native" ? "React Native" : "Unity"}{" "}
|
||||
documentation
|
||||
</UnderlineLink>
|
||||
.
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text>Install the latest version of the SDK:</Text>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
hideTabs
|
||||
isInstallCommand
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={COMMANDS.install}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Flex>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Text>Initialize the SDK and contract on your project:</Text>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Initialize the SDK and contract on your project:
|
||||
</p>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
hideTabs
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={formatSnippet(COMMANDS.setup, {
|
||||
chainId,
|
||||
contractAddress,
|
||||
})}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You will need to pass a client ID/secret key to use thirdweb's
|
||||
infrastructure services. If you don't have any API keys yet you
|
||||
can create one by creating a project for free from the{" "}
|
||||
<UnderlineLink href="/team">dashboard</UnderlineLink>.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!onlyInstall && (
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold tracking-tight mb-3">
|
||||
All Functions & Events
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[1fr_2fr] gap-4">
|
||||
<div className="border bg-card rounded-lg overflow-hidden ">
|
||||
{(writeFunctions || []).length > 0 ||
|
||||
(readFunctions || []).length > 0 ? (
|
||||
<div>
|
||||
{/* tabs */}
|
||||
<div className="bg-background">
|
||||
<TabButtons
|
||||
tabs={tabList}
|
||||
tabClassName="!text-sm"
|
||||
tabContainerClassName="px-3 pt-2"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{tab === "write" && (
|
||||
<AccentButtonListContainer>
|
||||
{writeFunctions?.map((fn) => (
|
||||
<AccentButton
|
||||
isActive={write?.signature === fn.signature}
|
||||
key={fn.signature}
|
||||
label={fn.name}
|
||||
onClick={() => {
|
||||
setTab("write");
|
||||
setWrite(fn);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</AccentButtonListContainer>
|
||||
)}
|
||||
|
||||
{tab === "read" && (
|
||||
<AccentButtonListContainer>
|
||||
{readFunctions?.map((fn) => (
|
||||
<AccentButton
|
||||
isActive={read?.signature === fn.signature}
|
||||
key={fn.signature}
|
||||
onClick={() => {
|
||||
setTab("read");
|
||||
setRead(fn);
|
||||
}}
|
||||
label={fn.name}
|
||||
/>
|
||||
))}
|
||||
</AccentButtonListContainer>
|
||||
)}
|
||||
|
||||
{tab === "events" && (
|
||||
<AccentButtonListContainer>
|
||||
{events?.map((ev) => (
|
||||
<AccentButton
|
||||
isActive={event?.name === ev.name}
|
||||
key={ev.name}
|
||||
onClick={() => {
|
||||
setTab("events");
|
||||
setEvent(ev);
|
||||
}}
|
||||
label={ev.name}
|
||||
/>
|
||||
))}
|
||||
</AccentButtonListContainer>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
hideTabs
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={formatSnippet(COMMANDS.setup, {
|
||||
chainId,
|
||||
contractAddress,
|
||||
})}
|
||||
/>
|
||||
<Text>
|
||||
You will need to pass a client ID/secret key to use
|
||||
thirdweb's infrastructure services. If you don't have
|
||||
any API keys yet you can create one by creating a project for free
|
||||
from the{" "}
|
||||
<Link color="primary.500" href="/team">
|
||||
dashboard
|
||||
</Link>
|
||||
.
|
||||
</Text>
|
||||
</Flex>
|
||||
</Flex>
|
||||
{!onlyInstall && (
|
||||
<Flex flexDirection="column" gap={6}>
|
||||
<Heading size="title.md">All Functions & Events</Heading>
|
||||
<SimpleGrid columns={12} gap={3} height="100%">
|
||||
<GridItem
|
||||
as={Card}
|
||||
colSpan={{ base: 12, md: 4 }}
|
||||
height="100%"
|
||||
overflow="auto"
|
||||
overflowY="auto"
|
||||
pt={0}
|
||||
px={0}
|
||||
>
|
||||
<List height="100%" overflowX="hidden">
|
||||
{((writeFunctions || []).length > 0 ||
|
||||
(readFunctions || []).length > 0) && (
|
||||
<Tabs
|
||||
colorScheme="gray"
|
||||
display="flex"
|
||||
flexDir="column"
|
||||
h="100%"
|
||||
position="relative"
|
||||
>
|
||||
<TabList as={Flex}>
|
||||
{(writeFunctions || []).length > 0 && (
|
||||
<Tab flex="1 1 0" gap={2}>
|
||||
<Heading color="inherit" my={1} size="label.md">
|
||||
Write
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
{(readFunctions || []).length > 0 && (
|
||||
<Tab flex="1 1 0" gap={2}>
|
||||
<Heading color="inherit" my={1} size="label.md">
|
||||
Read
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
{(events || []).length > 0 && (
|
||||
<Tab flex="1 1 0" gap={2}>
|
||||
<Heading color="inherit" my={1} size="label.md">
|
||||
Events
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
</TabList>
|
||||
<TabPanels h="auto" overflow="auto">
|
||||
<TabPanel>
|
||||
{writeFunctions?.map((fn) => (
|
||||
<ListItem key={fn.signature} my={0.5}>
|
||||
<Button
|
||||
_hover={{
|
||||
opacity: 1,
|
||||
textDecor: "underline",
|
||||
}}
|
||||
color="heading"
|
||||
fontFamily="mono"
|
||||
fontWeight={
|
||||
tab === "write" &&
|
||||
write?.signature === fn.signature
|
||||
? 600
|
||||
: 400
|
||||
}
|
||||
onClick={() => {
|
||||
setTab("write");
|
||||
setWrite(fn);
|
||||
}}
|
||||
opacity={
|
||||
tab === "write" &&
|
||||
write?.signature === fn.signature
|
||||
? 1
|
||||
: 0.65
|
||||
}
|
||||
size="sm"
|
||||
variant="link"
|
||||
>
|
||||
{fn.name}
|
||||
</Button>
|
||||
</ListItem>
|
||||
))}
|
||||
</TabPanel>
|
||||
<TabPanel>
|
||||
{readFunctions?.map((fn) => (
|
||||
<ListItem key={fn.signature} my={0.5}>
|
||||
<Button
|
||||
_hover={{
|
||||
opacity: 1,
|
||||
textDecor: "underline",
|
||||
}}
|
||||
color="heading"
|
||||
fontFamily="mono"
|
||||
fontWeight={
|
||||
tab === "read" &&
|
||||
read?.signature === fn.signature
|
||||
? 600
|
||||
: 400
|
||||
}
|
||||
onClick={() => {
|
||||
setTab("read");
|
||||
setRead(fn);
|
||||
}}
|
||||
opacity={
|
||||
tab === "read" &&
|
||||
read?.signature === fn.signature
|
||||
? 1
|
||||
: 0.65
|
||||
}
|
||||
size="sm"
|
||||
variant="link"
|
||||
>
|
||||
{fn.name}
|
||||
</Button>
|
||||
</ListItem>
|
||||
))}
|
||||
</TabPanel>
|
||||
<TabPanel>
|
||||
{events?.map((ev) => (
|
||||
<ListItem key={ev.name} my={0.5}>
|
||||
<Button
|
||||
_hover={{
|
||||
opacity: 1,
|
||||
textDecor: "underline",
|
||||
}}
|
||||
color="heading"
|
||||
fontFamily="mono"
|
||||
fontWeight={
|
||||
tab === "events" &&
|
||||
(event as AbiEvent).name ===
|
||||
(ev as AbiEvent).name
|
||||
? 600
|
||||
: 400
|
||||
}
|
||||
onClick={() => {
|
||||
setTab("events");
|
||||
setEvent(ev);
|
||||
}}
|
||||
opacity={
|
||||
tab === "events" &&
|
||||
(event as AbiEvent).name ===
|
||||
(ev as AbiEvent).name
|
||||
? 1
|
||||
: 0.65
|
||||
}
|
||||
size="sm"
|
||||
variant="link"
|
||||
>
|
||||
{ev.name}
|
||||
</Button>
|
||||
</ListItem>
|
||||
))}
|
||||
</TabPanel>
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
)}
|
||||
</List>
|
||||
</GridItem>
|
||||
<GridItem
|
||||
as={Card}
|
||||
colSpan={{ base: 12, md: 8 }}
|
||||
height="100%"
|
||||
overflow="auto"
|
||||
>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={formatSnippet(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
COMMANDS[tab as keyof typeof COMMANDS] as any,
|
||||
{
|
||||
args:
|
||||
abi
|
||||
?.filter(
|
||||
(f) => f.type === "function" || f.type === "event",
|
||||
)
|
||||
?.find(
|
||||
(f) =>
|
||||
f.name ===
|
||||
(tab === "read"
|
||||
? read?.name
|
||||
: tab === "write"
|
||||
? write?.name
|
||||
: event?.name),
|
||||
)
|
||||
?.inputs.map((i) => i.name || "") || [],
|
||||
snippet={formatSnippet(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
COMMANDS[tab as keyof typeof COMMANDS] as any,
|
||||
{
|
||||
args:
|
||||
abi
|
||||
?.filter(
|
||||
(f) => f.type === "function" || f.type === "event",
|
||||
)
|
||||
?.find(
|
||||
(f) =>
|
||||
f.name ===
|
||||
(tab === "read"
|
||||
? read?.name
|
||||
: tab === "write"
|
||||
? write?.name
|
||||
: event?.name),
|
||||
)
|
||||
?.inputs.map((i) => i.name || "") || [],
|
||||
|
||||
chainId,
|
||||
contractAddress,
|
||||
extensionNamespace,
|
||||
fn:
|
||||
tab === "read" ? read : tab === "write" ? write : event,
|
||||
},
|
||||
)}
|
||||
/>
|
||||
</GridItem>
|
||||
</SimpleGrid>
|
||||
</Flex>
|
||||
)}
|
||||
</GridItem>
|
||||
</SimpleGrid>
|
||||
chainId,
|
||||
contractAddress,
|
||||
extensionNamespace,
|
||||
fn: tab === "read" ? read : tab === "write" ? write : event,
|
||||
},
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function AccentButtonListContainer(props: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5 px-2 py-3 max-h-[300px] lg:max-h-[700px] overflow-y-auto">
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AccentButton(props: {
|
||||
isActive: boolean;
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"text-sm justify-start h-auto py-1 px-2 text-muted-foreground",
|
||||
props.isActive && "text-foreground bg-accent",
|
||||
)}
|
||||
onClick={props.onClick}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
{props.label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountFactorySection(props: {
|
||||
environment: CodeEnvironment;
|
||||
setEnvironment: (environment: CodeEnvironment) => void;
|
||||
address?: string;
|
||||
chainId: number;
|
||||
contractAddress: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold tracking-tight">
|
||||
Integrate your account factory
|
||||
</h2>
|
||||
<Alert variant="info">
|
||||
<CircleAlertIcon className="w-5 h-5 text-blue-500" />
|
||||
<AlertTitle>Account Factory</AlertTitle>
|
||||
<AlertDescription>
|
||||
The recommended way to use account factories is to integrate the{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/transactions/sponsor"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
thirdweb SDK
|
||||
</UnderlineLink>{" "}
|
||||
in your applications. This will ensure account contracts are
|
||||
deployed for your users only when they need it.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<CodeSegment
|
||||
environment={props.environment}
|
||||
hideTabs
|
||||
setEnvironment={props.setEnvironment}
|
||||
snippet={formatSnippet(
|
||||
(WALLETS_SNIPPETS.find((w) => w.id === "smart-wallet")
|
||||
?.supportedLanguages || {}) as Record<CodeEnvironment, string>,
|
||||
{
|
||||
address: props.address,
|
||||
chainId: props.chainId,
|
||||
contractAddress: props.contractAddress,
|
||||
},
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,15 +22,16 @@ export default function ContractFunctionComment({
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<p className="mt-6">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold mt-6 mb-3">
|
||||
About this function <Badge>Beta</Badge>
|
||||
</p>
|
||||
</h3>
|
||||
<CodeClient
|
||||
code={query.data}
|
||||
copyButtonClassName="hidden"
|
||||
lang="wikitext"
|
||||
lang="solidity"
|
||||
className="bg-background"
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,32 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Box,
|
||||
Divider,
|
||||
Flex,
|
||||
GridItem,
|
||||
Image,
|
||||
List,
|
||||
SimpleGrid,
|
||||
Tab,
|
||||
TabList,
|
||||
Table,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
Tbody,
|
||||
Td,
|
||||
Th,
|
||||
Thead,
|
||||
Tr,
|
||||
} from "@chakra-ui/react";
|
||||
import type { AbiEvent, AbiFunction } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Card } from "chakra/card";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import {
|
||||
type Dispatch,
|
||||
lazy,
|
||||
@@ -45,12 +20,21 @@ import {
|
||||
type CodeEnvironment,
|
||||
CodeSegment,
|
||||
} from "@/components/blocks/code/code-segment.client";
|
||||
import { camelToTitle } from "@/components/solidity-inputs/helpers";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { useContractFunctionSelectors } from "@/hooks/contract-ui/useContractFunctionSelectors";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { COMMANDS, formatSnippet } from "../code-overview";
|
||||
import { InteractiveAbiFunction } from "./interactive-abi-function";
|
||||
@@ -137,25 +121,21 @@ function ContractFunctionInner(props: ContractFunctionProps) {
|
||||
});
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap={1.5}>
|
||||
<Flex alignItems="center" direction="row" flexWrap="wrap" gap={2}>
|
||||
<Flex alignItems="baseline" flexWrap="wrap" gap={1}>
|
||||
<Heading size="subtitle.md">{camelToTitle(fn.name)}</Heading>
|
||||
<Heading className="text-muted-foreground" size="subtitle.sm">
|
||||
({fn.name})
|
||||
</Heading>
|
||||
</Flex>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center flex-wrap gap-2 border-b pb-3 mb-3">
|
||||
<h3 className="text-lg font-semibold">{fn.name}</h3>
|
||||
{isFunction && <Badge variant="success">{fn.stateMutability}</Badge>}
|
||||
{functionSelector && (
|
||||
<CopyTextButton
|
||||
className="ml-auto text-xs"
|
||||
className="ml-auto text-xs font-mono py-1"
|
||||
copyIconPosition="right"
|
||||
textToCopy={functionSelector}
|
||||
textToShow={functionSelector}
|
||||
tooltip="The selector of this function"
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
</div>
|
||||
|
||||
{isFunction && (
|
||||
<InteractiveAbiFunction
|
||||
abiFunction={fn}
|
||||
@@ -166,20 +146,20 @@ function ContractFunctionInner(props: ContractFunctionProps) {
|
||||
)}
|
||||
|
||||
{codeSnippet && (
|
||||
<>
|
||||
<Heading mt={6} size="subtitle.md">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold mt-6 mb-3">
|
||||
Use this function in your app
|
||||
</Heading>
|
||||
<Divider mb={2} />
|
||||
</h3>
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={codeSnippet}
|
||||
codeContainerClassName="bg-background"
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
<ContractFunctionComment contract={contract} functionName={fn.name} />
|
||||
</Flex>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -188,84 +168,46 @@ function ContractFunctionInputs(props: { fn: AbiFunction | AbiEvent }) {
|
||||
const isFunction = "stateMutability" in fn;
|
||||
|
||||
return (
|
||||
<Flex direction="column" gap={1.5}>
|
||||
<Flex
|
||||
alignItems={{ base: "start", md: "center" }}
|
||||
direction={{ base: "column", md: "row" }}
|
||||
gap={2}
|
||||
>
|
||||
<Flex alignItems="baseline" flexWrap="wrap" gap={1}>
|
||||
<Heading size="subtitle.md">{camelToTitle(fn.name)}</Heading>
|
||||
<Heading className="text-muted-foreground" size="subtitle.sm">
|
||||
({fn.name})
|
||||
</Heading>
|
||||
</Flex>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center flex-wrap gap-2 border-b pb-3 mb-3">
|
||||
<h3 className="text-lg font-semibold">{fn.name}</h3>
|
||||
{isFunction && <Badge variant="success">{fn.stateMutability}</Badge>}
|
||||
</Flex>
|
||||
</div>
|
||||
|
||||
{fn.inputs?.length ? (
|
||||
<>
|
||||
<Divider my={2} />
|
||||
<Flex flexDir="column" gap={3}>
|
||||
<Heading size="label.lg">Inputs</Heading>
|
||||
<Box
|
||||
borderTopRadius="lg"
|
||||
overflowX="auto"
|
||||
p={0}
|
||||
position="relative"
|
||||
>
|
||||
<Table size="sm">
|
||||
<Thead>
|
||||
<Tr>
|
||||
<Th border="none">
|
||||
<Heading as="label" color="faded" size="label.sm">
|
||||
Name
|
||||
</Heading>
|
||||
</Th>
|
||||
<Th border="none">
|
||||
<Heading as="label" color="faded" size="label.sm">
|
||||
Type
|
||||
</Heading>
|
||||
</Th>
|
||||
</Tr>
|
||||
</Thead>
|
||||
<Tbody>
|
||||
{fn.inputs.map((input, idx) => (
|
||||
<Tr
|
||||
_last={{ borderBottomWidth: 0 }}
|
||||
borderBottomWidth={1}
|
||||
key={`${input.name}+${idx}}`}
|
||||
>
|
||||
<Td
|
||||
borderBottomColor="borderColor"
|
||||
borderBottomWidth="inherit"
|
||||
>
|
||||
{input?.name ? (
|
||||
<Text fontFamily="mono">{input.name}</Text>
|
||||
) : (
|
||||
<Text
|
||||
className="text-muted-foreground"
|
||||
fontStyle="italic"
|
||||
>
|
||||
No name defined
|
||||
</Text>
|
||||
)}
|
||||
</Td>
|
||||
<Td
|
||||
borderBottomColor="borderColor"
|
||||
borderBottomWidth="inherit"
|
||||
>
|
||||
<Text fontFamily="mono">{input.type}</Text>
|
||||
</Td>
|
||||
</Tr>
|
||||
))}
|
||||
</Tbody>
|
||||
</Table>
|
||||
</Box>
|
||||
</Flex>
|
||||
</>
|
||||
<div>
|
||||
<h4 className="text-base font-semibold mb-3">Inputs</h4>
|
||||
<TableContainer>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{fn.inputs.map((input, idx) => (
|
||||
<TableRow key={`${input.name}+${idx}}`}>
|
||||
<TableCell className="font-medium py-3">
|
||||
{input?.name ? (
|
||||
<span className="font-mono">{input.name}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">
|
||||
No name defined
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3">
|
||||
<span className="font-mono">{input.type}</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
</div>
|
||||
) : null}
|
||||
</Flex>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -296,6 +238,7 @@ export const ContractFunctionsPanel: React.FC<ContractFunctionsPanelProps> = ({
|
||||
});
|
||||
return results;
|
||||
}, [fnsOrEvents]);
|
||||
|
||||
const writeFunctions: ExtensionFunctions[] = useMemo(() => {
|
||||
return functionsWithExtension
|
||||
.map((e) => {
|
||||
@@ -313,6 +256,7 @@ export const ContractFunctionsPanel: React.FC<ContractFunctionsPanelProps> = ({
|
||||
})
|
||||
.filter((e) => e !== undefined) as ExtensionFunctions[];
|
||||
}, [functionsWithExtension]);
|
||||
|
||||
const viewFunctions: ExtensionFunctions[] = useMemo(() => {
|
||||
return functionsWithExtension
|
||||
.map((e) => {
|
||||
@@ -336,166 +280,109 @@ export const ContractFunctionsPanel: React.FC<ContractFunctionsPanelProps> = ({
|
||||
return fnsOrEvents.filter((fn) => !("stateMutability" in fn)) as AbiEvent[];
|
||||
}, [fnsOrEvents]);
|
||||
|
||||
// Load state from the URL
|
||||
const searchParams = useSearchParams();
|
||||
const _selector = searchParams?.get("selector");
|
||||
const _item = _selector
|
||||
? fnsOrEvents.find((o) => {
|
||||
if (o.type === "function") {
|
||||
const selector = toFunctionSelector(o as AbiFunction);
|
||||
return selector === _selector;
|
||||
}
|
||||
return null;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
const [selectedFunction, setSelectedFunction] = useState<
|
||||
AbiFunction | AbiEvent | undefined
|
||||
>(_item ?? fnsOrEvents[0]);
|
||||
// Set the active tab to Write or Read depends on the `_item`
|
||||
const _defaultTabIndex =
|
||||
_item &&
|
||||
"stateMutability" in _item &&
|
||||
(_item.stateMutability === "view" || _item.stateMutability === "pure")
|
||||
? 1
|
||||
: 0;
|
||||
>(fnsOrEvents[0]);
|
||||
|
||||
const [_keywordSearch, setKeywordSearch] = useState<string>("");
|
||||
const [keywordSearch] = useDebounce(_keywordSearch, 150);
|
||||
|
||||
const [activeTab, setActiveTab] = useState<number>(0);
|
||||
|
||||
const functionSection = (e: ExtensionFunctions) => {
|
||||
const filteredFunctions = keywordSearch
|
||||
? e.functions.filter((o) =>
|
||||
o.name.toLowerCase().includes(keywordSearch.toLowerCase()),
|
||||
)
|
||||
: e.functions;
|
||||
|
||||
return (
|
||||
<Flex flexDir="column" key={e.extension} mb={6}>
|
||||
{e.extension ? (
|
||||
<>
|
||||
<Flex alignContent="center" alignItems="center" gap={2}>
|
||||
<Image
|
||||
alt="Extension detected"
|
||||
mb="2px"
|
||||
objectFit="contain"
|
||||
src="/assets/dashboard/extension-check.svg"
|
||||
<div key={e.extension} className="pb-6">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{selectedFunction &&
|
||||
filteredFunctions.map((fn) => (
|
||||
<FunctionsOrEventsListItem
|
||||
fn={fn}
|
||||
key={`${fn.name}_${fn.type}_${fn.inputs.length}`}
|
||||
selectedFunction={selectedFunction}
|
||||
setSelectedFunction={setSelectedFunction}
|
||||
/>
|
||||
<Heading as="label" size="label.md">
|
||||
{e.extension}
|
||||
</Heading>
|
||||
</Flex>
|
||||
<Divider my={2} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Flex alignContent="center" alignItems="center" gap={2}>
|
||||
<Heading as="label" size="label.md">
|
||||
Other Functions
|
||||
</Heading>
|
||||
</Flex>
|
||||
<Divider my={2} />
|
||||
</>
|
||||
)}
|
||||
{selectedFunction &&
|
||||
filteredFunctions.map((fn) => (
|
||||
<FunctionsOrEventsListItem
|
||||
fn={fn}
|
||||
key={`${fn.name}_${fn.type}_${fn.inputs.length}`}
|
||||
selectedFunction={selectedFunction}
|
||||
setSelectedFunction={setSelectedFunction}
|
||||
/>
|
||||
))}
|
||||
</Flex>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SimpleGrid columns={12} gap={5} height="100%">
|
||||
<GridItem
|
||||
as={Card}
|
||||
className="bg-card"
|
||||
colSpan={{ base: 12, md: 4 }}
|
||||
height="100%"
|
||||
overflow="auto"
|
||||
overflowY="auto"
|
||||
pt={0}
|
||||
px={0}
|
||||
>
|
||||
<List height="100%" overflowX="hidden">
|
||||
{(writeFunctions.length > 0 || viewFunctions.length > 0) && (
|
||||
<Tabs
|
||||
colorScheme="gray"
|
||||
defaultIndex={_defaultTabIndex}
|
||||
display="flex"
|
||||
flexDir="column"
|
||||
h="100%"
|
||||
position="relative"
|
||||
>
|
||||
<TabList as={Flex}>
|
||||
{writeFunctions.length > 0 && (
|
||||
<Tab flex="1 1 0" gap={2}>
|
||||
<Heading color="inherit" my={1} size="label.md">
|
||||
Write
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
{viewFunctions.length > 0 && (
|
||||
<Tab flex="1 1 0" gap={2}>
|
||||
<Heading color="inherit" my={1} size="label.md">
|
||||
Read
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
</TabList>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[1fr_2fr] gap-4 h-full">
|
||||
{/* left */}
|
||||
<div className="bg-card rounded-lg border overflow-auto">
|
||||
{(writeFunctions.length > 0 || viewFunctions.length > 0) && (
|
||||
<div className="flex flex-col h-full relative">
|
||||
<TabButtons
|
||||
tabContainerClassName="px-3 pt-2"
|
||||
tabClassName="!text-sm"
|
||||
tabs={[
|
||||
...(writeFunctions.length > 0
|
||||
? [
|
||||
{
|
||||
name: "Write",
|
||||
onClick: () => setActiveTab(0),
|
||||
isActive: activeTab === 0,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(viewFunctions.length > 0
|
||||
? [
|
||||
{
|
||||
name: "Read",
|
||||
onClick: () => setActiveTab(1),
|
||||
isActive: activeTab === 1,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="sticky top-0 z-[1]">
|
||||
<div className="relative w-full">
|
||||
<SearchIcon className="-translate-y-1/2 absolute top-[50%] left-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-auto rounded-none border-x-0 bg-card py-3 pl-9 focus-visible:ring-0 focus-visible:ring-offset-0"
|
||||
onChange={(e) => setKeywordSearch(e.target.value)}
|
||||
placeholder="Search"
|
||||
value={_keywordSearch}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TabPanels h="auto" overflow="auto">
|
||||
{writeFunctions.length > 0 && (
|
||||
<TabPanel>
|
||||
{writeFunctions.map((e) => functionSection(e))}
|
||||
</TabPanel>
|
||||
)}
|
||||
{viewFunctions.length > 0 && (
|
||||
<TabPanel>
|
||||
{viewFunctions.map((e) => functionSection(e))}
|
||||
</TabPanel>
|
||||
)}
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{events.length > 0 && selectedFunction && (
|
||||
<Box overflowX="hidden" pt={2} px={4}>
|
||||
{events.map((fn) => (
|
||||
<FunctionsOrEventsListItem
|
||||
fn={fn}
|
||||
key={`${fn.name}_${fn.type}_${fn.inputs.length}`}
|
||||
selectedFunction={selectedFunction}
|
||||
setSelectedFunction={setSelectedFunction}
|
||||
<div className="sticky top-0 z-[1]">
|
||||
<div className="relative w-full">
|
||||
<SearchIcon className="-translate-y-1/2 absolute top-[50%] left-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-auto rounded-none border-x-0 border-t-0 bg-card py-3 pl-9 focus-visible:ring-0 focus-visible:ring-offset-0"
|
||||
onChange={(e) => setKeywordSearch(e.target.value)}
|
||||
placeholder="Search"
|
||||
value={_keywordSearch}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</List>
|
||||
</GridItem>
|
||||
<GridItem
|
||||
as={Card}
|
||||
className="bg-card"
|
||||
colSpan={{ base: 12, md: 8 }}
|
||||
height="100%"
|
||||
overflow="auto"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-auto overflow-auto pt-2 px-2">
|
||||
{activeTab === 0 &&
|
||||
writeFunctions.length > 0 &&
|
||||
writeFunctions.map((e) => functionSection(e))}
|
||||
|
||||
{activeTab === 1 &&
|
||||
viewFunctions.length > 0 &&
|
||||
viewFunctions.map((e) => functionSection(e))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{events.length > 0 && selectedFunction && (
|
||||
<div className="pt-2 px-4">
|
||||
{events.map((fn) => (
|
||||
<FunctionsOrEventsListItem
|
||||
fn={fn}
|
||||
key={`${fn.name}_${fn.type}_${fn.inputs.length}`}
|
||||
selectedFunction={selectedFunction}
|
||||
setSelectedFunction={setSelectedFunction}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* right */}
|
||||
<div className="bg-card rounded-lg border p-4 overflow-auto">
|
||||
{selectedFunction && (
|
||||
<ContractFunction
|
||||
contract={contract}
|
||||
@@ -503,8 +390,8 @@ export const ContractFunctionsPanel: React.FC<ContractFunctionsPanelProps> = ({
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
)}
|
||||
</GridItem>
|
||||
</SimpleGrid>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -524,31 +411,19 @@ const FunctionsOrEventsListItem: React.FC<FunctionsOrEventsListItemProps> = ({
|
||||
const isActive =
|
||||
selectedFunction?.name === fn.name &&
|
||||
selectedFunction.inputs?.length === fn.inputs?.length;
|
||||
const pathname = usePathname();
|
||||
const router = useDashboardRouter();
|
||||
return (
|
||||
<li className="my-1">
|
||||
<Button
|
||||
className={cn(
|
||||
"!font-medium !text-muted-foreground hover:!text-foreground font-mono",
|
||||
{
|
||||
"!text-foreground": isActive,
|
||||
},
|
||||
)}
|
||||
onClick={() => {
|
||||
setSelectedFunction(fn);
|
||||
|
||||
// Only apply to the Explorer page
|
||||
if (pathname?.endsWith("/explorer") && fn.type === "function") {
|
||||
const selector = toFunctionSelector(fn);
|
||||
router.push(`${pathname}?selector=${selector}`);
|
||||
}
|
||||
}}
|
||||
size="sm"
|
||||
variant="link"
|
||||
>
|
||||
{fn.name}
|
||||
</Button>
|
||||
</li>
|
||||
<Button
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground font-mono w-full justify-start h-auto px-2 py-1",
|
||||
isActive && "text-foreground bg-accent",
|
||||
)}
|
||||
onClick={() => {
|
||||
setSelectedFunction(fn);
|
||||
}}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
>
|
||||
{fn.name}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,19 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Flex,
|
||||
Tab,
|
||||
TabList,
|
||||
TabPanel,
|
||||
TabPanels,
|
||||
Tabs,
|
||||
} from "@chakra-ui/react";
|
||||
import type { Abi, AbiEvent, AbiFunction } from "abitype";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { useState } from "react";
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import { SourcesPanel } from "@/components/contract-components/shared/sources-panel";
|
||||
import type { SourceFile } from "@/components/contract-components/types";
|
||||
import { CodeOverview } from "@/components/contracts/code-overview";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { ContractFunctionsPanel } from "./contract-function";
|
||||
|
||||
interface ContractFunctionsOverview {
|
||||
@@ -26,6 +19,8 @@ interface ContractFunctionsOverview {
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
type Tab = "functions" | "events" | "code" | "sources";
|
||||
|
||||
export const ContractFunctionsOverview: React.FC<ContractFunctionsOverview> = ({
|
||||
functions,
|
||||
events,
|
||||
@@ -35,90 +30,94 @@ export const ContractFunctionsOverview: React.FC<ContractFunctionsOverview> = ({
|
||||
onlyFunctions,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
const [activeTab, setActiveTab] = useState<Tab | undefined>(() => {
|
||||
if (functions && functions.length > 0) return "functions";
|
||||
if (events && events.length > 0) return "events";
|
||||
if (abi) return "code";
|
||||
if (sources && sources.length > 0) return "sources";
|
||||
return undefined;
|
||||
});
|
||||
|
||||
if (onlyFunctions) {
|
||||
return (
|
||||
<Flex flexDir="column" gap={2} height="100%">
|
||||
{functions && functions.length > 0 && (
|
||||
if (functions && functions.length > 0) {
|
||||
return (
|
||||
<ContractFunctionsPanel
|
||||
contract={contract}
|
||||
fnsOrEvents={functions}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Tab index: 0 = Functions, 1 = Events, 2 = Code, 3 = Sources
|
||||
const tabOptions = [
|
||||
...(functions && functions.length > 0
|
||||
? [
|
||||
{
|
||||
name: "Functions",
|
||||
onClick: () => setActiveTab("functions"),
|
||||
isActive: activeTab === "functions",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(events && events.length > 0
|
||||
? [
|
||||
{
|
||||
name: "Events",
|
||||
onClick: () => setActiveTab("events"),
|
||||
isActive: activeTab === "events",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(abi
|
||||
? [
|
||||
{
|
||||
name: "Code",
|
||||
onClick: () => setActiveTab("code"),
|
||||
isActive: activeTab === "code",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(sources && sources.length > 0
|
||||
? [
|
||||
{
|
||||
name: "Sources",
|
||||
onClick: () => setActiveTab("sources"),
|
||||
isActive: activeTab === "sources",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<TabButtons tabs={tabOptions} />
|
||||
<div className="pt-4">
|
||||
{functions && functions.length > 0 && activeTab === "functions" && (
|
||||
<div className="h-[70vh]">
|
||||
<ContractFunctionsPanel
|
||||
contract={contract}
|
||||
fnsOrEvents={functions}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{events && events.length > 0 && activeTab === "events" && (
|
||||
<ContractFunctionsPanel
|
||||
contract={contract}
|
||||
fnsOrEvents={functions}
|
||||
fnsOrEvents={events}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Flex flexDir="column" gap={2} w="100%">
|
||||
<Tabs colorScheme="gray" isLazy lazyBehavior="keepMounted">
|
||||
<TabList borderBottomColor="borderColor" borderBottomWidth="1px" px={0}>
|
||||
{functions && functions.length > 0 ? (
|
||||
<Tab>
|
||||
<Heading color="inherit" my={1} size="label.lg">
|
||||
Functions
|
||||
</Heading>
|
||||
</Tab>
|
||||
) : null}
|
||||
{events?.length ? (
|
||||
<Tab>
|
||||
<Heading color="inherit" my={1} size="label.lg">
|
||||
Events
|
||||
</Heading>
|
||||
</Tab>
|
||||
) : null}
|
||||
{abi && (
|
||||
<Tab>
|
||||
<Heading color="inherit" my={1} size="label.lg">
|
||||
Code
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
{sources && sources?.length > 0 && (
|
||||
<Tab>
|
||||
<Heading color="inherit" my={1} size="label.lg">
|
||||
Sources
|
||||
</Heading>
|
||||
</Tab>
|
||||
)}
|
||||
</TabList>
|
||||
<TabPanels py={2}>
|
||||
{functions && functions.length > 0 ? (
|
||||
<TabPanel h="40rem">
|
||||
<ContractFunctionsPanel
|
||||
contract={contract}
|
||||
fnsOrEvents={functions}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
</TabPanel>
|
||||
) : null}
|
||||
{events && events?.length > 0 ? (
|
||||
<TabPanel>
|
||||
<ContractFunctionsPanel
|
||||
contract={contract}
|
||||
fnsOrEvents={events}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
</TabPanel>
|
||||
) : null}
|
||||
{abi && (
|
||||
<TabPanel>
|
||||
<div className="flex flex-col gap-6">
|
||||
<CodeOverview
|
||||
abi={abi}
|
||||
chainId={contract?.chain.id || 1}
|
||||
noSidebar
|
||||
/>
|
||||
</div>
|
||||
</TabPanel>
|
||||
)}
|
||||
{(sources || abi) && (
|
||||
<TabPanel>
|
||||
<SourcesPanel abi={abi} sources={sources} />
|
||||
</TabPanel>
|
||||
)}
|
||||
</TabPanels>
|
||||
</Tabs>
|
||||
</Flex>
|
||||
{abi && activeTab === "code" && (
|
||||
<CodeOverview abi={abi} chainId={contract?.chain.id || 1} noSidebar />
|
||||
)}
|
||||
{sources && sources.length > 0 && activeTab === "sources" && (
|
||||
<SourcesPanel abi={abi} sources={sources} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+112
-130
@@ -1,20 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ButtonGroup,
|
||||
Divider,
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
} from "@chakra-ui/react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { type AbiFunction, type AbiParameter, formatAbiItem } from "abitype";
|
||||
import { Button } from "chakra/button";
|
||||
import { Card } from "chakra/card";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { ExternalLinkIcon, InfoIcon, PlayIcon } from "lucide-react";
|
||||
import {
|
||||
ExternalLinkIcon,
|
||||
InfoIcon,
|
||||
PlayIcon,
|
||||
RefreshCcwIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useId, useMemo, useState } from "react";
|
||||
import { FormProvider, useFieldArray, useForm } from "react-hook-form";
|
||||
@@ -29,16 +22,19 @@ import {
|
||||
} from "thirdweb";
|
||||
import { useActiveAccount, useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { parseAbiParams, stringify, toFunctionSelector } from "thirdweb/utils";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import { camelToTitle } from "@/components/solidity-inputs/helpers";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import { PlainTextCodeBlock } from "@/components/ui/code/plaintext-code";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { replaceIpfsUrl } from "@/lib/sdk";
|
||||
|
||||
function formatResponseData(data: unknown): {
|
||||
type: "json" | "text";
|
||||
@@ -122,11 +118,11 @@ function formatContractCall(
|
||||
return parsedParams;
|
||||
}
|
||||
|
||||
interface InteractiveAbiFunctionProps {
|
||||
type InteractiveAbiFunctionProps = {
|
||||
abiFunction: AbiFunction;
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
};
|
||||
|
||||
function useAsyncRead(contract: ThirdwebContract, abiFunction: AbiFunction) {
|
||||
const formattedAbi = formatAbiItem({
|
||||
@@ -366,97 +362,72 @@ export const InteractiveAbiFunction: React.FC<InteractiveAbiFunctionProps> = (
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<Card
|
||||
as={Flex}
|
||||
bg="transparent"
|
||||
border="none"
|
||||
borderRadius="none"
|
||||
boxShadow="none"
|
||||
flexDirection="column"
|
||||
flexGrow={1}
|
||||
gap={4}
|
||||
gridColumn={{ base: "span 12", md: "span 9" }}
|
||||
p={0}
|
||||
w="100%"
|
||||
>
|
||||
<Flex
|
||||
as="form"
|
||||
direction="column"
|
||||
gap={2}
|
||||
id={formId}
|
||||
position="relative"
|
||||
w="100%"
|
||||
>
|
||||
{fields.length > 0 && (
|
||||
<>
|
||||
<Divider mb="8px" />
|
||||
{fields.map((item, index) => {
|
||||
return (
|
||||
<FormControl
|
||||
isInvalid={
|
||||
!!form.getFieldState(
|
||||
`params.${index}.value`,
|
||||
form.formState,
|
||||
).error
|
||||
}
|
||||
key={item.id}
|
||||
mb="8px"
|
||||
>
|
||||
<Flex justify="space-between">
|
||||
<FormLabel>{camelToTitle(item.key)}</FormLabel>
|
||||
<Text fontSize="12px">{item.key}</Text>
|
||||
</Flex>
|
||||
<SolidityInput
|
||||
// @ts-expect-error - old types, need to update
|
||||
solidityComponents={item.components}
|
||||
solidityName={item.key}
|
||||
solidityType={item.type}
|
||||
{...form.register(`params.${index}.value`)}
|
||||
functionName={abiFunction.name}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{
|
||||
form.getFieldState(
|
||||
`params.${index}.value`,
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
<div className="space-y-6">
|
||||
<form className="space-y-5 relative w-full" id={formId}>
|
||||
{fields.length > 0 &&
|
||||
fields.map((item, index) => {
|
||||
const fieldError = form.getFieldState(
|
||||
`params.${index}.value`,
|
||||
form.formState,
|
||||
).error;
|
||||
|
||||
return (
|
||||
<FormFieldSetup
|
||||
key={item.id}
|
||||
htmlFor={`params.${index}.value`}
|
||||
labelClassName="w-full"
|
||||
labelContainerClassName="flex w-full"
|
||||
label={
|
||||
<div className="flex justify-between items-center w-full gap-3">
|
||||
<span>{camelToTitle(item.key)}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{item.key}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
errorMessage={fieldError?.message}
|
||||
isRequired={false}
|
||||
className="mb-2"
|
||||
>
|
||||
<SolidityInput
|
||||
// @ts-expect-error - old types, need to update
|
||||
solidityComponents={item.components}
|
||||
solidityName={item.key}
|
||||
solidityType={item.type}
|
||||
{...form.register(`params.${index}.value`)}
|
||||
functionName={abiFunction.name}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
);
|
||||
})}
|
||||
|
||||
{abiFunction.stateMutability === "payable" && (
|
||||
<>
|
||||
<Divider mb="8px" />
|
||||
<FormControl gap={0.5}>
|
||||
<FormLabel>Native Token Value</FormLabel>
|
||||
<Input {...form.register("value")} />
|
||||
<FormHelperText>
|
||||
The native currency value (in Ether) to send with this
|
||||
transaction (ex: 0.01 to send 0.01 native currency).
|
||||
</FormHelperText>
|
||||
</FormControl>
|
||||
</>
|
||||
<FormFieldSetup
|
||||
htmlFor="value"
|
||||
label="Native Token Value"
|
||||
errorMessage={undefined}
|
||||
isRequired={false}
|
||||
helperText="The native currency value (in Ether) to send with this transaction (ex: 0.01 to send 0.01 native currency)."
|
||||
>
|
||||
<Input {...form.register("value")} className="bg-background" />
|
||||
</FormFieldSetup>
|
||||
)}
|
||||
|
||||
{error ? (
|
||||
<>
|
||||
<Divider />
|
||||
<Heading size="label.sm">Error</Heading>
|
||||
<h3 className="text-sm font-medium">Error</h3>
|
||||
<InlineCode
|
||||
className="relative w-full whitespace-pre-wrap rounded-md border border-border p-4 text-red-500"
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
code={formatError(error as any)}
|
||||
/>
|
||||
</>
|
||||
) : readLoading ? (
|
||||
<Skeleton className="h-20 w-full rounded-lg" />
|
||||
) : formattedResponseData ? (
|
||||
<>
|
||||
<Divider />
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<Heading size="label.sm">Output</Heading>
|
||||
<h3 className="text-sm font-medium">Output</h3>
|
||||
{/* Show the Solidity type of the function's output */}
|
||||
{abiFunction.outputs.length > 0 && (
|
||||
<Badge variant="default">
|
||||
@@ -466,30 +437,32 @@ export const InteractiveAbiFunction: React.FC<InteractiveAbiFunctionProps> = (
|
||||
</div>
|
||||
|
||||
{formattedResponseData.type === "text" ? (
|
||||
<PlainTextCodeBlock code={formattedResponseData.data} />
|
||||
<PlainTextCodeBlock
|
||||
code={formattedResponseData.data}
|
||||
className="bg-background"
|
||||
/>
|
||||
) : (
|
||||
<CodeClient
|
||||
code={formattedResponseData.data}
|
||||
lang={formattedResponseData.type}
|
||||
className="bg-background"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* If the result is an IPFS URI, show a handy link so that users can open it in a new tab */}
|
||||
{formattedResponseData.type === "text" &&
|
||||
formattedResponseData.data.startsWith("ipfs://") && (
|
||||
<Text size="label.sm">
|
||||
<UnderlineLink
|
||||
href={replaceIpfsUrl(
|
||||
formattedResponseData.data,
|
||||
contract.client,
|
||||
)}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Open in gateway
|
||||
</UnderlineLink>
|
||||
</Text>
|
||||
<Link
|
||||
href={`https://ipfs.io/ipfs/${formattedResponseData.data.split("ipfs://")[1]}`}
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-2 mt-1"
|
||||
target="_blank"
|
||||
>
|
||||
Open In IPFS Gateway
|
||||
<ExternalLinkIcon className="size-3.5" />
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{/* Same with the logic above but this time it's applied to traditional urls */}
|
||||
{((formattedResponseData.type === "text" &&
|
||||
formattedResponseData.data.startsWith("https://")) ||
|
||||
@@ -506,37 +479,46 @@ export const InteractiveAbiFunction: React.FC<InteractiveAbiFunctionProps> = (
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</Flex>
|
||||
</form>
|
||||
|
||||
<Divider mt="auto" />
|
||||
<ButtonGroup ml="auto">
|
||||
<div className="flex gap-3 justify-end">
|
||||
{isView ? (
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
form={formId}
|
||||
isDisabled={!abiFunction}
|
||||
isLoading={readLoading}
|
||||
disabled={!abiFunction}
|
||||
onClick={handleContractRead}
|
||||
rightIcon={<PlayIcon className="size-4" />}
|
||||
className="gap-2 bg-background rounded-full"
|
||||
variant="outline"
|
||||
>
|
||||
Run
|
||||
{/* run / rerun */}
|
||||
{readLoading ? (
|
||||
<Spinner className="size-4" />
|
||||
) : readData ? (
|
||||
<RefreshCcwIcon className="size-4 text-muted-foreground" />
|
||||
) : (
|
||||
<PlayIcon className="size-4 text-muted-foreground" />
|
||||
)}
|
||||
{readData ? "Run again" : readLoading ? "Running" : "Run"}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
isDisabled={
|
||||
!abiFunction || txSimulation.isPending || mutationLoading
|
||||
}
|
||||
isLoading={txSimulation.isPending}
|
||||
onClick={handleContractSimulation}
|
||||
>
|
||||
<ToolTipLabel label="Simulate the transaction to see its potential outcome without actually sending it to the network. This action doesn't cost gas.">
|
||||
<span className="mr-3">
|
||||
<InfoIcon className="size-5" />
|
||||
</span>
|
||||
</ToolTipLabel>
|
||||
Simulate
|
||||
</Button>
|
||||
<ToolTipLabel label="Simulate the transaction to see its potential outcome without actually sending it to the network. This action doesn't cost gas.">
|
||||
<Button
|
||||
className="gap-2 bg-background"
|
||||
variant="outline"
|
||||
disabled={
|
||||
!abiFunction || txSimulation.isPending || mutationLoading
|
||||
}
|
||||
onClick={handleContractSimulation}
|
||||
>
|
||||
{txSimulation.isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<InfoIcon className="size-4 text-muted-foreground" />
|
||||
)}
|
||||
Simulate
|
||||
</Button>
|
||||
</ToolTipLabel>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={
|
||||
@@ -553,8 +535,8 @@ export const InteractiveAbiFunction: React.FC<InteractiveAbiFunctionProps> = (
|
||||
</TransactionButton>
|
||||
</>
|
||||
)}
|
||||
</ButtonGroup>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,15 +1,4 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
IconButton,
|
||||
Input,
|
||||
InputGroup,
|
||||
InputRightElement,
|
||||
Tooltip,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormErrorMessage, FormLabel } from "chakra/form";
|
||||
import { BanIcon, PlusIcon, TrashIcon, UploadIcon, XIcon } from "lucide-react";
|
||||
import { PlusIcon, TrashIcon, XIcon } from "lucide-react";
|
||||
import { useEffect } from "react";
|
||||
import {
|
||||
type ArrayPath,
|
||||
@@ -25,7 +14,16 @@ import {
|
||||
type WatchObserver,
|
||||
} from "react-hook-form";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type OptionalPropertiesInput = {
|
||||
[key: string]: string | number;
|
||||
@@ -46,17 +44,15 @@ interface IPropertiesFormControlProps<
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const PropertiesFormControl = <
|
||||
export function PropertiesFormControl<
|
||||
TFieldValues extends IPropertyFieldValues,
|
||||
>({
|
||||
control,
|
||||
register,
|
||||
watch,
|
||||
errors,
|
||||
setValue,
|
||||
client,
|
||||
}: React.PropsWithChildren<IPropertiesFormControlProps<TFieldValues>>) => {
|
||||
const { fields, append, remove, replace } = useFieldArray({
|
||||
}: React.PropsWithChildren<IPropertiesFormControlProps<TFieldValues>>) {
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control,
|
||||
name: "attributes" as ArrayPath<TFieldValues>,
|
||||
});
|
||||
@@ -72,19 +68,7 @@ export const PropertiesFormControl = <
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Flex align="center" direction="row" justify="space-between">
|
||||
<FormLabel m={0}>Attributes</FormLabel>
|
||||
<Button
|
||||
colorScheme="red"
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
onClick={() => replace([{ trait_type: "", value: "" } as any])}
|
||||
rightIcon={<BanIcon className="size-4" />}
|
||||
size="xs"
|
||||
variant="outline"
|
||||
>
|
||||
Reset
|
||||
</Button>
|
||||
</Flex>
|
||||
<FormLabel>Attributes</FormLabel>
|
||||
{fields.map((field, index) => {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
const keyError = (errors as any)?.attributes?.[index]?.trait_type
|
||||
@@ -92,102 +76,108 @@ export const PropertiesFormControl = <
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
const valueError = (errors as any)?.attributes?.[index]?.value
|
||||
?.message as string | undefined;
|
||||
const isInvalid = !!(keyError || valueError);
|
||||
const _isInvalid = !!(keyError || valueError);
|
||||
|
||||
return (
|
||||
<div className="flex flex-row items-center gap-2" key={field.id}>
|
||||
<FormControl
|
||||
className="flex flex-row items-start gap-3"
|
||||
isInvalid={isInvalid}
|
||||
>
|
||||
<FormControl isInvalid={!!keyError}>
|
||||
<Input
|
||||
{...register(
|
||||
`attributes.${index}.trait_type` as Path<TFieldValues>,
|
||||
)}
|
||||
placeholder="trait_type"
|
||||
/>
|
||||
<FormErrorMessage>{keyError}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!valueError}>
|
||||
{watch(
|
||||
`attributes.${index}.value` as unknown as WatchObserver<TFieldValues>,
|
||||
) instanceof File ? (
|
||||
<InputGroup>
|
||||
<Input
|
||||
isDisabled
|
||||
value={
|
||||
watch(`attributes.${index}.value` as Path<TFieldValues>)
|
||||
.name
|
||||
}
|
||||
/>
|
||||
<InputRightElement>
|
||||
<TrashIcon
|
||||
className="size-4 cursor-pointer text-red-300 hover:text-red-200"
|
||||
onClick={() =>
|
||||
setValue(
|
||||
`attributes.${index}.value` as Path<TFieldValues>,
|
||||
"" as PathValue<TFieldValues, Path<TFieldValues>>,
|
||||
)
|
||||
}
|
||||
<div className="flex flex-row items-start gap-3 flex-1">
|
||||
<FormField
|
||||
control={control}
|
||||
name={`attributes.${index}.trait_type` as Path<TFieldValues>}
|
||||
render={({ field: traitField }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
<Input
|
||||
{...traitField}
|
||||
placeholder="trait_type"
|
||||
className={cn(
|
||||
"bg-card",
|
||||
keyError && "border-destructive",
|
||||
)}
|
||||
/>
|
||||
</InputRightElement>
|
||||
</InputGroup>
|
||||
) : (
|
||||
<InputGroup>
|
||||
<Input
|
||||
{...register(
|
||||
`attributes.${index}.value` as Path<TFieldValues>,
|
||||
)}
|
||||
placeholder="value"
|
||||
/>
|
||||
<InputRightElement>
|
||||
<Tooltip label="Upload file" shouldWrapChildren>
|
||||
<FileInput
|
||||
client={client}
|
||||
setValue={(file) => {
|
||||
setValue(
|
||||
`attributes.${index}.value` as Path<TFieldValues>,
|
||||
file as PathValue<
|
||||
TFieldValues,
|
||||
Path<TFieldValues>
|
||||
>,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<UploadIcon className="size-4 text-muted-foreground" />
|
||||
</FileInput>
|
||||
</Tooltip>
|
||||
</InputRightElement>
|
||||
</InputGroup>
|
||||
</FormControl>
|
||||
{keyError && <FormMessage>{keyError}</FormMessage>}
|
||||
</FormItem>
|
||||
)}
|
||||
<FormErrorMessage>{valueError}</FormErrorMessage>
|
||||
</FormControl>
|
||||
</FormControl>
|
||||
<IconButton
|
||||
aria-label="remove key value pair"
|
||||
colorScheme="red"
|
||||
icon={<XIcon />}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name={`attributes.${index}.value` as Path<TFieldValues>}
|
||||
render={({ field: valueField }) => (
|
||||
<FormItem className="flex-1">
|
||||
<FormControl>
|
||||
{watch(
|
||||
`attributes.${index}.value` as unknown as WatchObserver<TFieldValues>,
|
||||
) instanceof File ? (
|
||||
<div className="relative">
|
||||
<Input
|
||||
disabled
|
||||
value={
|
||||
watch(
|
||||
`attributes.${index}.value` as Path<TFieldValues>,
|
||||
).name
|
||||
}
|
||||
className="pr-10 bg-card"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
|
||||
onClick={() =>
|
||||
setValue(
|
||||
`attributes.${index}.value` as Path<TFieldValues>,
|
||||
"" as PathValue<
|
||||
TFieldValues,
|
||||
Path<TFieldValues>
|
||||
>,
|
||||
)
|
||||
}
|
||||
>
|
||||
<TrashIcon className="size-4 text-muted-foreground hover:text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative">
|
||||
<Input
|
||||
{...valueField}
|
||||
placeholder="value"
|
||||
className={`pr-10 bg-card ${valueError ? "border-destructive" : ""}`}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</FormControl>
|
||||
{valueError && <FormMessage>{valueError}</FormMessage>}
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="rounded-full p-0 size-10 bg-card"
|
||||
onClick={() => remove(index)}
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
/>
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div className="flex flex-row gap-2">
|
||||
<Button
|
||||
colorScheme="purple"
|
||||
leftIcon={<PlusIcon className="size-5" />}
|
||||
className="rounded-full"
|
||||
onClick={() =>
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
append({ trait_type: undefined, value: undefined } as any)
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
<PlusIcon className="size-4 mr-2" />
|
||||
Add Row
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -144,15 +144,13 @@ export const PublishedContract: React.FC<PublishedContractProps> = ({
|
||||
</Card>
|
||||
)}
|
||||
{contractFunctions && (
|
||||
<Card p={0}>
|
||||
<ContractFunctionsOverview
|
||||
abi={publishedContract?.abi}
|
||||
events={contractEvents}
|
||||
functions={contractFunctions}
|
||||
isLoggedIn={isLoggedIn}
|
||||
sources={sources.data}
|
||||
/>
|
||||
</Card>
|
||||
<ContractFunctionsOverview
|
||||
abi={publishedContract?.abi}
|
||||
events={contractEvents}
|
||||
functions={contractFunctions}
|
||||
isLoggedIn={isLoggedIn}
|
||||
sources={sources.data}
|
||||
/>
|
||||
)}
|
||||
</Flex>
|
||||
</GridItem>
|
||||
|
||||
@@ -10,9 +10,9 @@ export const SolidityBoolInput: React.FC<SolidityInputProps> = ({
|
||||
const watchInput = form.watch(inputName);
|
||||
return (
|
||||
<div className="flex flex-row">
|
||||
<div className="inline-flex overflow-hidden rounded-md border border-border">
|
||||
<div className="inline-flex">
|
||||
<Button
|
||||
className="rounded-none border-r-0"
|
||||
className="border-r-0 rounded-r-none"
|
||||
onClick={() => form.setValue(inputName, "true")}
|
||||
size="sm"
|
||||
variant={watchInput === "true" ? "default" : "outline"}
|
||||
@@ -20,7 +20,7 @@ export const SolidityBoolInput: React.FC<SolidityInputProps> = ({
|
||||
True
|
||||
</Button>
|
||||
<Button
|
||||
className="rounded-none rounded-l-none"
|
||||
className="rounded-l-none"
|
||||
onClick={() => form.setValue(inputName, "false")}
|
||||
size="sm"
|
||||
variant={watchInput === "false" ? "default" : "outline"}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { UseMutationResult } from "@tanstack/react-query";
|
||||
import { Button, type ButtonProps } from "chakra/button";
|
||||
import { UploadIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { Button, type ButtonProps } from "@/components/ui/button";
|
||||
import { useErrorHandler } from "@/contexts/error-handler";
|
||||
import type { ComponentWithChildren } from "@/types/component-with-children";
|
||||
|
||||
@@ -39,12 +39,13 @@ export const IpfsUploadButton: ComponentWithChildren<IpfsUploadButtonProps> = ({
|
||||
<FileInput client={client} setValue={handleUpload}>
|
||||
<Button
|
||||
aria-label="Upload to IPFS"
|
||||
isLoading={storageUpload.isPending}
|
||||
rightIcon={<UploadIcon className="size-4" />}
|
||||
variant="secondary"
|
||||
disabled={storageUpload.isPending}
|
||||
size="sm"
|
||||
variant="solid"
|
||||
className="h-auto py-1.5 text-xs -translate-x-0.5 rounded-sm"
|
||||
{...buttonProps}
|
||||
>
|
||||
<UploadIcon className="size-3 mr-2 text-muted-foreground" />
|
||||
{children}
|
||||
</Button>
|
||||
</FileInput>
|
||||
|
||||
@@ -1223,7 +1223,7 @@ export function useEngineUpdateAccessToken(params: {
|
||||
});
|
||||
}
|
||||
|
||||
export type CreateWebhookInput = {
|
||||
type CreateWebhookInput = {
|
||||
url: string;
|
||||
name: string;
|
||||
eventType: string;
|
||||
|
||||
@@ -89,6 +89,10 @@ export function teamStub(id: string, billingPlan: Team["billingPlan"]): Team {
|
||||
enabled: true,
|
||||
rateLimit: 10,
|
||||
},
|
||||
gateway: {
|
||||
enabled: true,
|
||||
rateLimit: 1000,
|
||||
},
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
dedicatedSupportChannel: null,
|
||||
|
||||
@@ -74,7 +74,7 @@ export default async function RoutesPage(props: {
|
||||
</div>
|
||||
<a
|
||||
className="inline-flex items-center gap-2 rounded-md bg-green-600 px-4 py-2 font-medium text-sm text-white transition-all hover:bg-green-600/90 hover:shadow-sm"
|
||||
href="https://portal.thirdweb.com/pay"
|
||||
href="https://portal.thirdweb.com/payments"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ export const ContractExplorerPage: React.FC<ContractExplorePageProps> = ({
|
||||
|
||||
const functions = getContractFunctionsFromAbi(abi);
|
||||
return (
|
||||
<div className="flex h-[70vh] flex-col ">
|
||||
<div className="flex h-[70vh] flex-col">
|
||||
{functions && functions.length > 0 ? (
|
||||
<ContractFunctionsOverview
|
||||
contract={contract}
|
||||
|
||||
-1
@@ -110,7 +110,6 @@ const AirdropTab: React.FC<AirdropTabProps> = ({
|
||||
</SheetHeader>
|
||||
<AirdropUpload
|
||||
client={contract.client}
|
||||
onClose={() => setOpen(false)}
|
||||
setAirdrop={(value) =>
|
||||
setValue("addresses", value, { shouldDirty: true })
|
||||
}
|
||||
|
||||
+311
-231
@@ -1,18 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Accordion,
|
||||
AccordionButton,
|
||||
AccordionIcon,
|
||||
AccordionItem,
|
||||
AccordionPanel,
|
||||
FormControl,
|
||||
Input,
|
||||
Textarea,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { type Dispatch, type SetStateAction, useMemo } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
@@ -31,6 +18,24 @@ import { OpenSeaPropertyBadge } from "@/components/badges/opensea";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { PropertiesFormControl } from "@/components/contracts/properties.shared";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import type { NFTMetadataInputLimited } from "@/types/modified-types";
|
||||
import { parseAttributes } from "@/utils/parseAttributes";
|
||||
@@ -53,13 +58,13 @@ type UpdateNftMetadataForm = {
|
||||
isLoggedIn: boolean;
|
||||
};
|
||||
|
||||
export const UpdateNftMetadata: React.FC<UpdateNftMetadataForm> = ({
|
||||
export function UpdateNftMetadata({
|
||||
contract,
|
||||
nft,
|
||||
useUpdateMetadata,
|
||||
setOpen,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
}: UpdateNftMetadataForm) {
|
||||
const address = useActiveAccount()?.address;
|
||||
|
||||
const transformedQueryData = useMemo(() => {
|
||||
@@ -90,7 +95,7 @@ export const UpdateNftMetadata: React.FC<UpdateNftMetadataForm> = ({
|
||||
register,
|
||||
watch,
|
||||
handleSubmit,
|
||||
formState: { errors, isDirty },
|
||||
formState: { errors },
|
||||
} = form;
|
||||
|
||||
const setFile = (file: File) => {
|
||||
@@ -112,229 +117,304 @@ export const UpdateNftMetadata: React.FC<UpdateNftMetadataForm> = ({
|
||||
);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-6"
|
||||
id={UPDATE_METADATA_FORM_ID}
|
||||
onSubmit={handleSubmit(async (data) => {
|
||||
if (!address) {
|
||||
toast.error("Please connect your wallet to update metadata.");
|
||||
return;
|
||||
}
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="flex flex-col gap-6"
|
||||
id={UPDATE_METADATA_FORM_ID}
|
||||
onSubmit={handleSubmit(async (data) => {
|
||||
if (!address) {
|
||||
toast.error("Please connect your wallet to update metadata.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const newMetadata = parseAttributes({
|
||||
...data,
|
||||
animation_url: data.animation_url || nft.metadata.animation_url,
|
||||
image: data.image || nft.metadata.image,
|
||||
});
|
||||
try {
|
||||
const newMetadata = parseAttributes({
|
||||
...data,
|
||||
animation_url: data.animation_url || nft.metadata.animation_url,
|
||||
image: data.image || nft.metadata.image,
|
||||
});
|
||||
|
||||
const transaction = useUpdateMetadata
|
||||
? // For Drop contracts, we need to call the `updateBatchBaseURI` method
|
||||
nft.type === "ERC721"
|
||||
? updateMetadata721({
|
||||
contract,
|
||||
newMetadata,
|
||||
targetTokenId: BigInt(nft.id),
|
||||
})
|
||||
: updateMetadata1155({
|
||||
contract,
|
||||
newMetadata,
|
||||
targetTokenId: BigInt(nft.id),
|
||||
})
|
||||
: // For Collection contracts, we need to call the `setTokenURI` method
|
||||
nft.type === "ERC721"
|
||||
? updateTokenURI721({
|
||||
contract,
|
||||
newMetadata,
|
||||
tokenId: BigInt(nft.id),
|
||||
})
|
||||
: updateTokenURI1155({
|
||||
contract,
|
||||
newMetadata,
|
||||
tokenId: BigInt(nft.id),
|
||||
});
|
||||
await sendAndConfirmTx.mutateAsync(transaction, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
const transaction = useUpdateMetadata
|
||||
? // For Drop contracts, we need to call the `updateBatchBaseURI` method
|
||||
nft.type === "ERC721"
|
||||
? updateMetadata721({
|
||||
contract,
|
||||
newMetadata,
|
||||
targetTokenId: BigInt(nft.id),
|
||||
})
|
||||
: updateMetadata1155({
|
||||
contract,
|
||||
newMetadata,
|
||||
targetTokenId: BigInt(nft.id),
|
||||
})
|
||||
: // For Collection contracts, we need to call the `setTokenURI` method
|
||||
nft.type === "ERC721"
|
||||
? updateTokenURI721({
|
||||
contract,
|
||||
newMetadata,
|
||||
tokenId: BigInt(nft.id),
|
||||
})
|
||||
: updateTokenURI1155({
|
||||
contract,
|
||||
newMetadata,
|
||||
tokenId: BigInt(nft.id),
|
||||
});
|
||||
await sendAndConfirmTx.mutateAsync(transaction, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
updateMetadataNotifications.onSuccess();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
updateMetadataNotifications.onError(err);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<FormControl isInvalid={!!errors.name} isRequired>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input autoFocus {...register("name")} />
|
||||
<FormErrorMessage>{errors?.name?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
|
||||
<FormControl isInvalid={!!mediaFileError}>
|
||||
<FormLabel>Media</FormLabel>
|
||||
<div className="flex flex-row flex-wrap gap-3">
|
||||
<FileInput
|
||||
className="shrink-0 rounded border border-border transition-all duration-200"
|
||||
client={contract.client}
|
||||
helperText={nft?.metadata ? "New Media" : "Media"}
|
||||
previewMaxWidth="200px"
|
||||
selectOrUpload="Upload"
|
||||
setValue={setFile}
|
||||
showPreview
|
||||
showUploadButton
|
||||
value={media}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormHelperText>
|
||||
You can upload image, audio, video, html, text, pdf, and 3d model
|
||||
files here.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{mediaFileError?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
|
||||
{showCoverImageUpload && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) => setValue("image", file)}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
<FormHelperText>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.image?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
)}
|
||||
<FormControl isInvalid={!!errors.description}>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<Textarea {...register("description")} />
|
||||
<FormErrorMessage>{errors?.description?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<PropertiesFormControl
|
||||
client={contract.client}
|
||||
control={control}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
errors={errors as any}
|
||||
register={register}
|
||||
setValue={setValue}
|
||||
watch={watch}
|
||||
/>
|
||||
|
||||
<Accordion
|
||||
allowToggle={!(errors.background_color || errors.external_url)}
|
||||
index={errors.background_color || errors.external_url ? [0] : undefined}
|
||||
updateMetadataNotifications.onSuccess();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
updateMetadataNotifications.onError(err);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<AccordionItem>
|
||||
<AccordionButton justifyContent="space-between" px={0}>
|
||||
<Heading size="subtitle.md">Advanced Options</Heading>
|
||||
<AccordionIcon />
|
||||
</AccordionButton>
|
||||
<AccordionPanel className="!px-0 flex flex-col gap-6">
|
||||
<FormControl isInvalid={!!errors.background_color}>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input max="6" {...register("background_color")} />
|
||||
<FormHelperText>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.background_color?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
|
||||
{!(external_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.external_url}>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input {...register("external_url")} />
|
||||
<FormHelperText>
|
||||
This is the URL that will appear below the asset's image
|
||||
on OpenSea and will allow users to leave OpenSea and view the
|
||||
item on your site.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.external_url?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
<FormField
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input autoFocus {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
)}
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!(image instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={typeof image === "string" ? image : ""}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT image pre-uploaded to a URL, you
|
||||
can specify it here instead of uploading the media file
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>{errors?.image?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
)}
|
||||
<FormItem>
|
||||
<FormLabel>Media</FormLabel>
|
||||
<div className="flex flex-row flex-wrap gap-3">
|
||||
<FileInput
|
||||
className="shrink-0 rounded border border-border transition-all duration-200"
|
||||
client={contract.client}
|
||||
helperText={nft?.metadata ? "New Media" : "Media"}
|
||||
previewMaxWidth="200px"
|
||||
selectOrUpload="Upload"
|
||||
setValue={setFile}
|
||||
showPreview
|
||||
showUploadButton
|
||||
value={media}
|
||||
/>
|
||||
</div>
|
||||
<FormDescription>
|
||||
You can upload image, audio, video, html, text, pdf, and 3d model
|
||||
files here.
|
||||
</FormDescription>
|
||||
{mediaFileError && (
|
||||
<FormMessage>
|
||||
{mediaFileError.message as unknown as string}
|
||||
</FormMessage>
|
||||
)}
|
||||
</FormItem>
|
||||
|
||||
{!(animation_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.animation_url}>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={typeof animation_url === "string" ? animation_url : ""}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT Animation URL pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the media
|
||||
file
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.animation_url?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
{showCoverImageUpload && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FormControl>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) => {
|
||||
setValue("image", file);
|
||||
}}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
isDisabled={sendAndConfirmTx.isPending}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
/>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<PropertiesFormControl
|
||||
client={contract.client}
|
||||
disabled={!isDirty}
|
||||
form={UPDATE_METADATA_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
control={control}
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
errors={errors as any}
|
||||
register={register}
|
||||
setValue={setValue}
|
||||
watch={watch}
|
||||
/>
|
||||
|
||||
<Accordion
|
||||
type="single"
|
||||
className="-mx-1 border-t border-border"
|
||||
collapsible
|
||||
defaultValue={
|
||||
errors.background_color || errors.external_url
|
||||
? "advanced"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
Update NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
<AccordionItem value="advanced">
|
||||
<AccordionTrigger className="justify-between px-1">
|
||||
<h3 className="text-base font-medium">Advanced Options</h3>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="flex flex-col gap-6 px-1">
|
||||
<FormField
|
||||
control={control}
|
||||
name="background_color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input max="6" {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!(external_url instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="external_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
className="bg-card"
|
||||
value={
|
||||
typeof field.value === "string" ? field.value : ""
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
This is the URL that will appear below the asset's
|
||||
image on OpenSea and will allow users to leave OpenSea
|
||||
and view the item on your site.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!(image instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={typeof image === "string" ? image : ""}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT image pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the
|
||||
media file
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!(animation_url instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="animation_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={
|
||||
typeof animation_url === "string"
|
||||
? animation_url
|
||||
: ""
|
||||
}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT Animation URL pre-uploaded
|
||||
to a URL, you can specify it here instead of uploading
|
||||
the media file
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
disabled={sendAndConfirmTx.isPending}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
form={UPDATE_METADATA_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Update NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+51
-49
@@ -60,59 +60,61 @@ export const BatchLazyMintButton: React.FC<BatchLazyMintButtonProps> = ({
|
||||
Batch Upload
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="min-w-full overflow-y-auto">
|
||||
<SheetHeader>
|
||||
<SheetTitle className="text-left">Upload NFTs</SheetTitle>
|
||||
<SheetContent className="!w-full !max-w-full overflow-y-auto p-0">
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Upload NFTs</SheetTitle>
|
||||
</SheetHeader>
|
||||
<BatchLazyMint
|
||||
canCreateDelayedRevealBatch={canCreateDelayedRevealBatch}
|
||||
chainId={contract.chain.id}
|
||||
client={contract.client}
|
||||
isLoggedIn={isLoggedIn}
|
||||
nextTokenIdToMint={nextTokenIdToMintQuery.data || 0n}
|
||||
onSubmit={async ({ revealType, data }) => {
|
||||
try {
|
||||
const tx = (() => {
|
||||
switch (true) {
|
||||
// lazy mint erc721
|
||||
case revealType === "instant" && isErc721: {
|
||||
return ERC721Ext.lazyMint({
|
||||
contract,
|
||||
nfts: data.metadatas,
|
||||
});
|
||||
<div className="p-4 lg:p-6">
|
||||
<BatchLazyMint
|
||||
canCreateDelayedRevealBatch={canCreateDelayedRevealBatch}
|
||||
chainId={contract.chain.id}
|
||||
client={contract.client}
|
||||
isLoggedIn={isLoggedIn}
|
||||
nextTokenIdToMint={nextTokenIdToMintQuery.data || 0n}
|
||||
onSubmit={async ({ revealType, data }) => {
|
||||
try {
|
||||
const tx = (() => {
|
||||
switch (true) {
|
||||
// lazy mint erc721
|
||||
case revealType === "instant" && isErc721: {
|
||||
return ERC721Ext.lazyMint({
|
||||
contract,
|
||||
nfts: data.metadatas,
|
||||
});
|
||||
}
|
||||
// lazy mint erc1155
|
||||
case revealType === "instant" && !isErc721: {
|
||||
return ERC1155Ext.lazyMint({
|
||||
contract,
|
||||
nfts: data.metadatas,
|
||||
});
|
||||
}
|
||||
// delayed reveal erc721
|
||||
case revealType === "delayed": {
|
||||
return ERC721Ext.createDelayedRevealBatch({
|
||||
contract,
|
||||
metadata: data.metadata,
|
||||
password: data.password,
|
||||
placeholderMetadata: data.placeholderMetadata,
|
||||
});
|
||||
}
|
||||
default: {
|
||||
throw new Error("Invalid reveal type");
|
||||
}
|
||||
}
|
||||
// lazy mint erc1155
|
||||
case revealType === "instant" && !isErc721: {
|
||||
return ERC1155Ext.lazyMint({
|
||||
contract,
|
||||
nfts: data.metadatas,
|
||||
});
|
||||
}
|
||||
// delayed reveal erc721
|
||||
case revealType === "delayed": {
|
||||
return ERC721Ext.createDelayedRevealBatch({
|
||||
contract,
|
||||
metadata: data.metadata,
|
||||
password: data.password,
|
||||
placeholderMetadata: data.placeholderMetadata,
|
||||
});
|
||||
}
|
||||
default: {
|
||||
throw new Error("Invalid reveal type");
|
||||
}
|
||||
}
|
||||
})();
|
||||
})();
|
||||
|
||||
await sendTxMutation.mutateAsync(tx);
|
||||
await sendTxMutation.mutateAsync(tx);
|
||||
|
||||
txNotifications.onSuccess();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
txNotifications.onError(error);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
txNotifications.onSuccess();
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
txNotifications.onError(error);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</MinterOnly>
|
||||
|
||||
+224
-148
@@ -1,18 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Accordion,
|
||||
AccordionButton,
|
||||
AccordionIcon,
|
||||
AccordionItem,
|
||||
AccordionPanel,
|
||||
Divider,
|
||||
FormControl,
|
||||
Input,
|
||||
Textarea,
|
||||
} from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
@@ -24,7 +11,24 @@ import { OpenSeaPropertyBadge } from "@/components/badges/opensea";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { PropertiesFormControl } from "@/components/contracts/properties.shared";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import type { NFTMetadataInputLimited } from "@/types/modified-types";
|
||||
import { parseAttributes } from "@/utils/parseAttributes";
|
||||
@@ -42,12 +46,12 @@ type LazyMintNftFormParams = {
|
||||
isLoggedIn: boolean;
|
||||
};
|
||||
|
||||
export const LazyMintNftForm: React.FC<LazyMintNftFormParams> = ({
|
||||
export function LazyMintNftForm({
|
||||
contract,
|
||||
isErc721,
|
||||
setOpen,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
}: LazyMintNftFormParams) {
|
||||
const address = useActiveAccount()?.address;
|
||||
const sendAndConfirmTx = useSendAndConfirmTransaction();
|
||||
|
||||
@@ -81,7 +85,7 @@ export const LazyMintNftForm: React.FC<LazyMintNftFormParams> = ({
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="mt-6 flex flex-col gap-6"
|
||||
id={LAZY_MINT_FORM_ID}
|
||||
@@ -112,16 +116,21 @@ export const LazyMintNftForm: React.FC<LazyMintNftFormParams> = ({
|
||||
}
|
||||
})}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="subtitle.md">Metadata </Heading>
|
||||
<Divider />
|
||||
</div>
|
||||
<FormControl isInvalid={!!errors.name} isRequired>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input autoFocus {...register("name")} />
|
||||
<FormErrorMessage>{errors?.name?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!mediaFileError}>
|
||||
<FormField
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input autoFocus {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormItem>
|
||||
<FormLabel>Media</FormLabel>
|
||||
<div>
|
||||
<FileInput
|
||||
@@ -136,39 +145,62 @@ export const LazyMintNftForm: React.FC<LazyMintNftFormParams> = ({
|
||||
value={media}
|
||||
/>
|
||||
</div>
|
||||
<FormHelperText>
|
||||
<FormDescription>
|
||||
You can upload image, audio, video, html, text, pdf, and 3d model
|
||||
files here.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{mediaFileError?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</FormDescription>
|
||||
{mediaFileError && (
|
||||
<FormMessage>
|
||||
{mediaFileError.message as unknown as string}
|
||||
</FormMessage>
|
||||
)}
|
||||
</FormItem>
|
||||
|
||||
{showCoverImageUpload && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) => setValue("image", file)}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
<FormHelperText>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.image?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FormControl>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="rounded-lg bg-card border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) =>
|
||||
setValue("image", file, {
|
||||
shouldValidate: true,
|
||||
})
|
||||
}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<FormControl isInvalid={!!errors.description}>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<Textarea {...register("description")} />
|
||||
<FormErrorMessage>{errors?.description?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<PropertiesFormControl
|
||||
client={contract.client}
|
||||
control={control}
|
||||
@@ -178,112 +210,156 @@ export const LazyMintNftForm: React.FC<LazyMintNftFormParams> = ({
|
||||
setValue={setValue}
|
||||
watch={watch}
|
||||
/>
|
||||
|
||||
<Accordion
|
||||
allowToggle={!(errors.background_color || errors.external_url)}
|
||||
index={
|
||||
errors.background_color || errors.external_url ? [0] : undefined
|
||||
type="single"
|
||||
collapsible
|
||||
className="-mx-1 border-t border-border"
|
||||
defaultValue={
|
||||
errors.background_color || errors.external_url
|
||||
? "advanced"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<AccordionItem>
|
||||
<AccordionButton justifyContent="space-between" px={0}>
|
||||
<Heading size="subtitle.md">Advanced Options</Heading>
|
||||
<AccordionIcon />
|
||||
</AccordionButton>
|
||||
<AccordionPanel className="!px-0 flex flex-col gap-6">
|
||||
<FormControl isInvalid={!!errors.background_color}>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input max="6" {...register("background_color")} />
|
||||
<FormHelperText>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.background_color?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<AccordionItem value="advanced">
|
||||
<AccordionTrigger className="justify-between px-1">
|
||||
<h3 className="text-base font-medium">Advanced Options</h3>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="flex flex-col gap-6 px-1">
|
||||
<FormField
|
||||
control={control}
|
||||
name="background_color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input max="6" {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!(external_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.external_url}>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input {...register("external_url")} />
|
||||
<FormHelperText>
|
||||
This is the URL that will appear below the asset's
|
||||
image on OpenSea and will allow users to leave OpenSea and
|
||||
view the item on your site.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.external_url?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="external_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
className="bg-card"
|
||||
value={
|
||||
typeof field.value === "string" ? field.value : ""
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
This is the URL that will appear below the asset's
|
||||
image on OpenSea and will allow users to leave OpenSea
|
||||
and view the item on your site.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!(image instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<Input
|
||||
{...register("image")}
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={image}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT image pre-uploaded to a URL,
|
||||
you can specify it here instead of uploading the media file
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>{errors?.image?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={typeof image === "string" ? image : ""}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT image pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the
|
||||
media file
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!(animation_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.animation_url}>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<Input
|
||||
{...register("animation_url")}
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={animation_url}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT Animation URL pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the media
|
||||
file
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.animation_url?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="animation_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={
|
||||
typeof animation_url === "string"
|
||||
? animation_url
|
||||
: ""
|
||||
}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT Animation URL pre-uploaded
|
||||
to a URL, you can specify it here instead of uploading
|
||||
the media file
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</AccordionPanel>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
className="mr-3"
|
||||
disabled={sendAndConfirmTx.isPending}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!isDirty}
|
||||
form={LAZY_MINT_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Lazy Mint NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
className="mr-3"
|
||||
disabled={sendAndConfirmTx.isPending}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!isDirty}
|
||||
form={LAZY_MINT_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Lazy Mint NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+244
-161
@@ -1,19 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Accordion,
|
||||
AccordionButton,
|
||||
AccordionIcon,
|
||||
AccordionItem,
|
||||
AccordionPanel,
|
||||
Divider,
|
||||
FormControl,
|
||||
Input,
|
||||
Textarea,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Heading } from "chakra/heading";
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
@@ -25,6 +11,24 @@ import { OpenSeaPropertyBadge } from "@/components/badges/opensea";
|
||||
import { FileInput } from "@/components/blocks/FileInput";
|
||||
import { PropertiesFormControl } from "@/components/contracts/properties.shared";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import type { NFTMetadataInputLimited } from "@/types/modified-types";
|
||||
import { parseAttributes } from "@/utils/parseAttributes";
|
||||
@@ -42,12 +46,12 @@ type NFTMintForm = {
|
||||
isLoggedIn: boolean;
|
||||
};
|
||||
|
||||
export const NFTMintForm: React.FC<NFTMintForm> = ({
|
||||
export function NFTMintForm({
|
||||
contract,
|
||||
isErc721,
|
||||
setOpen,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
}: NFTMintForm) {
|
||||
const address = useActiveAccount()?.address;
|
||||
const form = useForm<
|
||||
NFTMetadataInputLimited & {
|
||||
@@ -84,7 +88,7 @@ export const NFTMintForm: React.FC<NFTMintForm> = ({
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="mt-6 flex flex-col gap-6"
|
||||
id={MINT_FORM_ID}
|
||||
@@ -126,16 +130,21 @@ export const NFTMintForm: React.FC<NFTMintForm> = ({
|
||||
}
|
||||
})}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="subtitle.md">Metadata xx</Heading>
|
||||
<Divider />
|
||||
</div>
|
||||
<FormControl isInvalid={!!errors.name} isRequired>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input autoFocus {...register("name")} />
|
||||
<FormErrorMessage>{errors?.name?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!mediaFileError}>
|
||||
<FormField
|
||||
control={control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input autoFocus {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormItem>
|
||||
<FormLabel>Media</FormLabel>
|
||||
<div>
|
||||
<FileInput
|
||||
@@ -150,51 +159,80 @@ export const NFTMintForm: React.FC<NFTMintForm> = ({
|
||||
value={media}
|
||||
/>
|
||||
</div>
|
||||
<FormHelperText>
|
||||
<FormDescription>
|
||||
You can upload image, audio, video, html, text, pdf, and 3d model
|
||||
files here.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{mediaFileError?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</FormDescription>
|
||||
{mediaFileError && (
|
||||
<FormMessage>
|
||||
{mediaFileError.message as unknown as string}
|
||||
</FormMessage>
|
||||
)}
|
||||
</FormItem>
|
||||
|
||||
{showCoverImageUpload && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="shrink-0 rounded border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) => setValue("image", file)}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
<FormHelperText>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.image?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>Cover Image</FormLabel>
|
||||
<FormControl>
|
||||
<FileInput
|
||||
accept={{ "image/*": [] }}
|
||||
className="shrink-0 rounded border border-border transition-all"
|
||||
client={contract.client}
|
||||
previewMaxWidth="200px"
|
||||
setValue={(file) => setValue("image", file)}
|
||||
showUploadButton
|
||||
value={image}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
You can optionally upload an image as the cover of your NFT.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<FormControl isInvalid={!!errors.description}>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<Textarea {...register("description")} />
|
||||
<FormErrorMessage>{errors?.description?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
|
||||
<FormField
|
||||
control={control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!isErc721 && (
|
||||
<FormControl isInvalid={!!errors.supply} isRequired>
|
||||
<FormLabel>Initial Supply</FormLabel>
|
||||
<Input
|
||||
pattern="[0-9]"
|
||||
step="1"
|
||||
type="number"
|
||||
{...register("supply")}
|
||||
/>
|
||||
<FormErrorMessage>{errors?.supply?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormField
|
||||
control={control}
|
||||
name="supply"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Initial Supply</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
pattern="[0-9]"
|
||||
step="1"
|
||||
type="number"
|
||||
{...field}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PropertiesFormControl
|
||||
client={contract.client}
|
||||
control={control}
|
||||
@@ -204,109 +242,154 @@ export const NFTMintForm: React.FC<NFTMintForm> = ({
|
||||
setValue={setValue}
|
||||
watch={watch}
|
||||
/>
|
||||
|
||||
<Accordion
|
||||
allowToggle={!(errors.background_color || errors.external_url)}
|
||||
index={
|
||||
errors.background_color || errors.external_url ? [0] : undefined
|
||||
type="single"
|
||||
className="-mx-1 border-t border-border"
|
||||
collapsible
|
||||
defaultValue={
|
||||
errors.background_color || errors.external_url
|
||||
? "advanced"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<AccordionItem>
|
||||
<AccordionButton justifyContent="space-between" px={0}>
|
||||
<Heading size="subtitle.md">Advanced Options</Heading>
|
||||
<AccordionIcon />
|
||||
</AccordionButton>
|
||||
<AccordionPanel className="!px-0 flex flex-col gap-6">
|
||||
<FormControl isInvalid={!!errors.background_color}>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input max="6" {...register("background_color")} />
|
||||
<FormHelperText>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.background_color?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<AccordionItem value="advanced">
|
||||
<AccordionTrigger className="justify-between px-1">
|
||||
<h3 className="text-base font-medium">Advanced Options</h3>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="flex flex-col gap-6 px-1">
|
||||
<FormField
|
||||
control={control}
|
||||
name="background_color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
Background Color <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input max="6" {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Must be a six-character hexadecimal with a pre-pended #.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{!(external_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.external_url}>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<Input {...register("external_url")} />
|
||||
<FormHelperText>
|
||||
This is the URL that will appear below the asset's
|
||||
image on OpenSea and will allow users to leave OpenSea and
|
||||
view the item on your site.
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.external_url?.message as unknown as string}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
)}
|
||||
|
||||
{!(image instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.image}>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={image}
|
||||
{!(external_url instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="external_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>
|
||||
External URL <OpenSeaPropertyBadge />
|
||||
</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
className="bg-card"
|
||||
value={
|
||||
typeof field.value === "string" ? field.value : ""
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
This is the URL that will appear below the
|
||||
asset's image on OpenSea and will allow users to
|
||||
leave OpenSea and view the item on your site.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT image pre-uploaded to a URL,
|
||||
you can specify it here instead of uploading the asset
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>{errors?.image?.message}</FormErrorMessage>
|
||||
</FormControl>
|
||||
)}
|
||||
)}
|
||||
|
||||
{!(animation_url instanceof File) && (
|
||||
<FormControl isInvalid={!!errors.animation_url}>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={animation_url}
|
||||
{!(image instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="image"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Image URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("image", e.target.value);
|
||||
}}
|
||||
value={image}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT image pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the
|
||||
asset
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>
|
||||
If you already have your NFT Animation URL pre-uploaded to a
|
||||
URL, you can specify it here instead of uploading the asset
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{errors?.animation_url?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
)}
|
||||
</AccordionPanel>
|
||||
)}
|
||||
|
||||
{!(animation_url instanceof File) && (
|
||||
<FormField
|
||||
control={control}
|
||||
name="animation_url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Animation URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(e) => {
|
||||
setValue("animation_url", e.target.value);
|
||||
}}
|
||||
value={animation_url}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
If you already have your NFT Animation URL
|
||||
pre-uploaded to a URL, you can specify it here instead
|
||||
of uploading the asset
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
disabled={sendAndConfirmTx.isPending}
|
||||
className="mr-3"
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!isDirty}
|
||||
form={MINT_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Mint NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
<div className="mt-8 flex flex-row justify-end gap-3">
|
||||
<Button
|
||||
isDisabled={sendAndConfirmTx.isPending}
|
||||
mr={3}
|
||||
onClick={() => setOpen(false)}
|
||||
variant="outline"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!isDirty}
|
||||
form={MINT_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTx.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Mint NFT
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+1
-2
@@ -22,13 +22,12 @@ export function ContractTokensPageClient(props: {
|
||||
return <ErrorPage />;
|
||||
}
|
||||
|
||||
const { supportedERCs, functionSelectors } = metadataQuery.data;
|
||||
const { functionSelectors } = metadataQuery.data;
|
||||
|
||||
return (
|
||||
<ContractTokensPage
|
||||
contract={props.contract}
|
||||
isClaimToSupported={isClaimToSupported(functionSelectors)}
|
||||
isERC20={supportedERCs.isERC20}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isMintToSupported={isMintToSupported(functionSelectors)}
|
||||
/>
|
||||
|
||||
+4
-31
@@ -1,8 +1,5 @@
|
||||
"use client";
|
||||
import { LinkButton } from "chakra/button";
|
||||
import { Card } from "chakra/card";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import { TokenAirdropButton } from "./components/airdrop-button";
|
||||
import { TokenBurnButton } from "./components/burn-button";
|
||||
@@ -13,41 +10,17 @@ import { TokenTransferButton } from "./components/transfer-button";
|
||||
|
||||
interface ContractTokenPageProps {
|
||||
contract: ThirdwebContract;
|
||||
isERC20: boolean;
|
||||
isMintToSupported: boolean;
|
||||
isClaimToSupported: boolean;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
export const ContractTokensPage: React.FC<ContractTokenPageProps> = ({
|
||||
export function ContractTokensPage({
|
||||
contract,
|
||||
isERC20,
|
||||
isMintToSupported,
|
||||
isClaimToSupported,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
if (!isERC20) {
|
||||
return (
|
||||
<Card className="flex flex-col gap-3">
|
||||
{/* TODO extract this out into it's own component and make it better */}
|
||||
<Heading size="subtitle.md">No Token extension enabled</Heading>
|
||||
<Text>
|
||||
To enable Token features you will have to extend an ERC20 interface in
|
||||
your contract.
|
||||
</Text>
|
||||
<div>
|
||||
<LinkButton
|
||||
colorScheme="purple"
|
||||
href="https://portal.thirdweb.com/contracts/build/extensions/erc-20/ERC20"
|
||||
isExternal
|
||||
>
|
||||
Learn more
|
||||
</LinkButton>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
}: ContractTokenPageProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
||||
@@ -68,4 +41,4 @@ export const ContractTokensPage: React.FC<ContractTokenPageProps> = ({
|
||||
<TokenDetailsCard contract={contract} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+12
-31
@@ -1,10 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { DropletIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import { balanceOf } from "thirdweb/extensions/erc20";
|
||||
import { useActiveAccount, useReadContract } from "thirdweb/react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Sheet,
|
||||
@@ -15,42 +12,26 @@ import {
|
||||
} from "@/components/ui/sheet";
|
||||
import { TokenAirdropForm } from "./airdrop-form";
|
||||
|
||||
interface TokenAirdropButtonProps {
|
||||
export function TokenAirdropButton(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
export const TokenAirdropButton: React.FC<TokenAirdropButtonProps> = ({
|
||||
contract,
|
||||
isLoggedIn,
|
||||
...restButtonProps
|
||||
}) => {
|
||||
const address = useActiveAccount()?.address;
|
||||
const tokenBalanceQuery = useReadContract(balanceOf, {
|
||||
address: address || "",
|
||||
contract,
|
||||
queryOptions: { enabled: !!address },
|
||||
});
|
||||
const hasBalance = tokenBalanceQuery.data && tokenBalanceQuery.data > 0n;
|
||||
const [open, setOpen] = useState(false);
|
||||
}) {
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
variant="primary"
|
||||
{...restButtonProps}
|
||||
className="gap-2"
|
||||
disabled={!hasBalance}
|
||||
>
|
||||
<DropletIcon size={16} /> Airdrop
|
||||
<Button className="gap-2">
|
||||
<DropletIcon className="size-4" /> Airdrop
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent className="w-full overflow-y-auto sm:min-w-[540px] lg:min-w-[700px]">
|
||||
<SheetHeader>
|
||||
<SheetContent className="!w-full lg:!max-w-3xl flex flex-col gap-0">
|
||||
<SheetHeader className="mb-4">
|
||||
<SheetTitle className="text-left">Airdrop tokens</SheetTitle>
|
||||
</SheetHeader>
|
||||
<TokenAirdropForm contract={contract} isLoggedIn={isLoggedIn} />
|
||||
<TokenAirdropForm
|
||||
contract={props.contract}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { AlertCircleIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { PaginationButtons } from "@/components/blocks/pagination-buttons";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function AirdropCSVTable(props: {
|
||||
data: { address: string; quantity: string; isValid?: boolean }[];
|
||||
}) {
|
||||
const pageSize = 10;
|
||||
const [page, setPage] = useState(1);
|
||||
const totalPages = Math.ceil(props.data.length / pageSize);
|
||||
const paginatedData = props.data.slice(
|
||||
(page - 1) * pageSize,
|
||||
page * pageSize,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="border rounded-lg">
|
||||
<TableContainer className="border-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Address</TableHead>
|
||||
<TableHead>Quantity</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedData.map((row) => (
|
||||
<TableRow key={row.address}>
|
||||
<TableCell>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2",
|
||||
!row.isValid && "text-red-500",
|
||||
)}
|
||||
>
|
||||
{row.address}
|
||||
{!row.isValid && (
|
||||
<AlertCircleIcon className="size-4 text-red-500" />
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>{row.quantity}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
{totalPages > 1 && (
|
||||
<div className="border-t py-4">
|
||||
<PaginationButtons
|
||||
activePage={page}
|
||||
totalPages={totalPages}
|
||||
onPageClick={setPage}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+74
-110
@@ -1,134 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { Button } from "chakra/button";
|
||||
import { Text } from "chakra/text";
|
||||
import { CircleCheckIcon, UploadIcon } from "lucide-react";
|
||||
import { type Dispatch, type SetStateAction, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import { transferBatch } from "thirdweb/extensions/erc20";
|
||||
import { useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
import { type AirdropAddressInput, AirdropUpload } from "./airdrop-upload";
|
||||
|
||||
interface TokenAirdropFormProps {
|
||||
contract: ThirdwebContract;
|
||||
toggle?: Dispatch<SetStateAction<boolean>>;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
const GAS_COST_PER_ERC20_TRANSFER = 21000;
|
||||
|
||||
export const TokenAirdropForm: React.FC<TokenAirdropFormProps> = ({
|
||||
contract,
|
||||
toggle,
|
||||
isLoggedIn,
|
||||
}) => {
|
||||
const { handleSubmit, setValue, watch } = useForm<{
|
||||
addresses: AirdropAddressInput[];
|
||||
}>({
|
||||
type FormValues = {
|
||||
addresses: AirdropAddressInput[];
|
||||
};
|
||||
|
||||
export function TokenAirdropForm(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}) {
|
||||
const { contract, isLoggedIn } = props;
|
||||
const form = useForm<FormValues>({
|
||||
defaultValues: { addresses: [] },
|
||||
});
|
||||
|
||||
const sendTransaction = useSendAndConfirmTransaction();
|
||||
const addresses = watch("addresses");
|
||||
const [airdropFormOpen, setAirdropFormOpen] = useState(false);
|
||||
const addresses = form.watch("addresses");
|
||||
// The real number should be slightly higher since there's a lil bit of overhead cost
|
||||
const estimateGasCost =
|
||||
GAS_COST_PER_ERC20_TRANSFER * (addresses || []).length;
|
||||
|
||||
const airdropNotifications = useTxNotifications(
|
||||
"Tokens airdropped successfully",
|
||||
"Failed to airdrop tokens",
|
||||
);
|
||||
async function onSubmit(data: FormValues) {
|
||||
const tx = transferBatch({
|
||||
batch: data.addresses
|
||||
.filter((address) => address.quantity !== undefined)
|
||||
.map((address) => ({
|
||||
amount: address.quantity,
|
||||
to: address.address,
|
||||
})),
|
||||
contract,
|
||||
});
|
||||
|
||||
const sendTxPromise = sendTransaction.mutateAsync(tx);
|
||||
toast.promise(sendTxPromise, {
|
||||
success: "Tokens airdropped successfully",
|
||||
error: (err) => ({
|
||||
message: "Failed to airdrop tokens",
|
||||
description: parseError(err),
|
||||
}),
|
||||
});
|
||||
|
||||
await sendTxPromise;
|
||||
}
|
||||
|
||||
if (addresses.length === 0) {
|
||||
return (
|
||||
<AirdropUpload
|
||||
client={contract.client}
|
||||
setAirdrop={(value) =>
|
||||
form.setValue("addresses", value, { shouldDirty: true })
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="pt-3">
|
||||
<form
|
||||
onSubmit={handleSubmit(async (data) => {
|
||||
try {
|
||||
const tx = transferBatch({
|
||||
batch: data.addresses
|
||||
.filter((address) => address.quantity !== undefined)
|
||||
.map((address) => ({
|
||||
amount: address.quantity,
|
||||
to: address.address,
|
||||
})),
|
||||
contract,
|
||||
});
|
||||
await sendTransaction.mutateAsync(tx, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Close the sheet/modal on success
|
||||
if (toggle) {
|
||||
toggle(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
airdropNotifications.onSuccess();
|
||||
} catch (err) {
|
||||
airdropNotifications.onError(err);
|
||||
console.error(err);
|
||||
}
|
||||
})}
|
||||
>
|
||||
<div className="mb-3 flex w-full flex-col gap-6 md:flex-row">
|
||||
{airdropFormOpen ? (
|
||||
<AirdropUpload
|
||||
client={contract.client}
|
||||
onClose={() => setAirdropFormOpen(false)}
|
||||
setAirdrop={(value) =>
|
||||
setValue("addresses", value, { shouldDirty: true })
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex flex-col gap-4 md:flex-row">
|
||||
<Button
|
||||
borderRadius="md"
|
||||
colorScheme="primary"
|
||||
onClick={() => setAirdropFormOpen(true)}
|
||||
rightIcon={<UploadIcon className="size-4" />}
|
||||
>
|
||||
Upload addresses
|
||||
</Button>
|
||||
{addresses.length > 0 && (
|
||||
<div className="flex flex-row items-center justify-center gap-2 text-green-500">
|
||||
<CircleCheckIcon className="text-green-500" size={16} />
|
||||
<Text color="inherit" size="body.sm">
|
||||
<strong>{addresses.length} addresses</strong> ready to be
|
||||
airdropped
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div>
|
||||
<div className="mb-5 space-y-1">
|
||||
<p className="text-base text-foreground">
|
||||
{addresses.length} addresses ready to be airdropped
|
||||
</p>
|
||||
|
||||
{estimateGasCost && (
|
||||
<p className="text-muted-foreground text-sm">
|
||||
This transaction requires at least {estimateGasCost} gas. Since
|
||||
each chain has a different gas limit, please split this operation
|
||||
into multiple transactions if necessary. Usually under 10M gas is
|
||||
safe.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{addresses?.length > 0 && !airdropFormOpen && (
|
||||
<>
|
||||
{estimateGasCost && (
|
||||
<Text>
|
||||
This transaction requires at least {estimateGasCost} gas. Since
|
||||
each chain has a different gas limit, please split this
|
||||
operation into multiple transactions if necessary. Usually under
|
||||
10M gas is safe.
|
||||
</Text>
|
||||
)}
|
||||
<TransactionButton
|
||||
className="self-end"
|
||||
client={contract.client}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendTransaction.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Airdrop
|
||||
</TransactionButton>
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendTransaction.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Airdrop
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+92
-161
@@ -1,90 +1,28 @@
|
||||
import { Link } from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { CircleAlertIcon, UploadIcon } from "lucide-react";
|
||||
import { useMemo, useRef } from "react";
|
||||
import { useDropzone } from "react-dropzone";
|
||||
import type { Column } from "react-table";
|
||||
import { type ThirdwebClient, ZERO_ADDRESS } from "thirdweb";
|
||||
import { UnorderedList } from "@/components/ui/List/List";
|
||||
import { ArrowRightIcon, RefreshCcwIcon, TrashIcon } from "lucide-react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { DownloadableCode } from "@/components/blocks/code/downloadable-code";
|
||||
import { DropZone } from "@/components/blocks/drop-zone/drop-zone";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { useCsvUpload } from "@/hooks/useCsvUpload";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { CsvDataTable } from "../../_components/csv-data-table";
|
||||
import { AirdropCSVTable } from "./airdrop-csv-table";
|
||||
|
||||
export interface AirdropAddressInput {
|
||||
export type AirdropAddressInput = {
|
||||
address: string;
|
||||
quantity: string;
|
||||
isValid?: boolean;
|
||||
}
|
||||
interface AirdropUploadProps {
|
||||
setAirdrop: (airdrop: AirdropAddressInput[]) => void;
|
||||
onClose: () => void;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
const csvParser = (items: AirdropAddressInput[]): AirdropAddressInput[] => {
|
||||
return items
|
||||
.map(({ address, quantity }) => ({
|
||||
address: (address || "").trim(),
|
||||
quantity: (quantity || "1").trim(),
|
||||
}))
|
||||
.filter(({ address }) => address !== "");
|
||||
};
|
||||
|
||||
export const AirdropUpload: React.FC<AirdropUploadProps> = ({
|
||||
setAirdrop,
|
||||
onClose,
|
||||
client,
|
||||
}) => {
|
||||
const csvUpload = useCsvUpload<AirdropAddressInput>({ client, csvParser });
|
||||
const dropzone = useDropzone({
|
||||
onDrop: csvUpload.setFiles,
|
||||
export function AirdropUpload(props: {
|
||||
setAirdrop: (airdrop: AirdropAddressInput[]) => void;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const csvUpload = useCsvUpload<AirdropAddressInput>({
|
||||
client: props.client,
|
||||
csvParser,
|
||||
});
|
||||
|
||||
const paginationPortalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const normalizeData = csvUpload.normalizeQuery.data;
|
||||
|
||||
const columns = useMemo(() => {
|
||||
return [
|
||||
{
|
||||
accessor: ({ address, isValid }) => {
|
||||
if (isValid) {
|
||||
return address;
|
||||
}
|
||||
return (
|
||||
<ToolTipLabel
|
||||
label={
|
||||
address === ZERO_ADDRESS
|
||||
? "Cannot send tokens to ZERO_ADDRESS"
|
||||
: address.startsWith("0x")
|
||||
? "Address is not valid"
|
||||
: "Address couldn't be resolved"
|
||||
}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<CircleAlertIcon className="size-4 text-red-500" />
|
||||
<div className="cursor-default font-bold text-red-500">
|
||||
{address}
|
||||
</div>
|
||||
</div>
|
||||
</ToolTipLabel>
|
||||
);
|
||||
},
|
||||
Header: "Address",
|
||||
},
|
||||
{
|
||||
accessor: ({ quantity }: { quantity: string }) => {
|
||||
return quantity || "1";
|
||||
},
|
||||
Header: "Quantity",
|
||||
},
|
||||
] as Column<AirdropAddressInput>[];
|
||||
}, []);
|
||||
|
||||
if (!normalizeData) {
|
||||
return (
|
||||
<div className="flex min-h-[400px] w-full grow items-center justify-center rounded-lg border border-border">
|
||||
@@ -94,121 +32,114 @@ export const AirdropUpload: React.FC<AirdropUploadProps> = ({
|
||||
}
|
||||
|
||||
const onSave = () => {
|
||||
setAirdrop(
|
||||
props.setAirdrop(
|
||||
normalizeData.result.map((o) => ({
|
||||
address: o.resolvedAddress,
|
||||
quantity: o.quantity,
|
||||
})),
|
||||
);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="w-full">
|
||||
{normalizeData.result.length && csvUpload.rawData.length > 0 ? (
|
||||
<>
|
||||
<CsvDataTable<AirdropAddressInput>
|
||||
columns={columns}
|
||||
data={csvUpload.normalizeQuery.data.result}
|
||||
portalRef={paginationPortalRef}
|
||||
<div>
|
||||
<AirdropCSVTable
|
||||
data={csvUpload.normalizeQuery.data.result.map((row) => ({
|
||||
address: row.address ?? row.resolvedAddress,
|
||||
quantity: row.quantity,
|
||||
isValid: row.isValid,
|
||||
}))}
|
||||
/>
|
||||
<div className="mt-4 flex flex-col justify-between md:mt-0">
|
||||
<div ref={paginationPortalRef} />
|
||||
<div className="mt-3 ml-auto flex w-full flex-row gap-2 md:w-auto">
|
||||
<div className="flex justify-end gap-4 mt-6">
|
||||
<Button
|
||||
disabled={csvUpload.rawData.length === 0}
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
onClick={() => {
|
||||
csvUpload.reset();
|
||||
}}
|
||||
>
|
||||
<RefreshCcwIcon className="size-4" />
|
||||
<span>Reset</span>
|
||||
</Button>
|
||||
{csvUpload.normalizeQuery.data.invalidFound ? (
|
||||
<Button
|
||||
borderRadius="md"
|
||||
disabled={csvUpload.rawData.length === 0}
|
||||
className="gap-2"
|
||||
onClick={() => {
|
||||
csvUpload.reset();
|
||||
csvUpload.removeInvalid();
|
||||
}}
|
||||
w={{ base: "100%", md: "auto" }}
|
||||
>
|
||||
Reset
|
||||
<TrashIcon className="size-4" />
|
||||
<span>Remove invalid</span>
|
||||
</Button>
|
||||
{csvUpload.normalizeQuery.data.invalidFound ? (
|
||||
<Button
|
||||
borderRadius="md"
|
||||
colorScheme="primary"
|
||||
disabled={csvUpload.rawData.length === 0}
|
||||
onClick={() => {
|
||||
csvUpload.removeInvalid();
|
||||
}}
|
||||
w={{ base: "100%", md: "auto" }}
|
||||
>
|
||||
Remove invalid
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
borderRadius="md"
|
||||
colorScheme="primary"
|
||||
isDisabled={csvUpload.rawData.length === 0}
|
||||
onClick={onSave}
|
||||
w={{ base: "100%", md: "auto" }}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
disabled={csvUpload.rawData.length === 0}
|
||||
className="gap-2"
|
||||
onClick={onSave}
|
||||
>
|
||||
<span>Next</span>
|
||||
<ArrowRightIcon className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="relative aspect-[21/9] w-full">
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full cursor-pointer items-center justify-center rounded-md border border-border hover:border-primary",
|
||||
csvUpload.noCsv ? "bg-red-200" : "bg-background",
|
||||
)}
|
||||
{...dropzone.getRootProps()}
|
||||
>
|
||||
<input {...dropzone.getInputProps()} />
|
||||
<div className="flex flex-col p-6">
|
||||
<UploadIcon
|
||||
className={cn("mx-auto mb-2 size-4 text-gray-500", {
|
||||
"text-red-500": csvUpload.noCsv,
|
||||
})}
|
||||
/>
|
||||
{dropzone.isDragActive ? (
|
||||
<Heading as={Text} size="label.md">
|
||||
Drop the files here
|
||||
</Heading>
|
||||
) : (
|
||||
<Heading
|
||||
as={Text}
|
||||
color={csvUpload.noCsv ? "red.500" : "gray.600"}
|
||||
size="label.md"
|
||||
>
|
||||
{csvUpload.noCsv
|
||||
? `No valid CSV file found, make sure your CSV includes the "address" & "quantity" column.`
|
||||
: "Drag & Drop a CSV file here"}
|
||||
</Heading>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="subtitle.sm">Requirements</Heading>
|
||||
<UnorderedList>
|
||||
<DropZone
|
||||
onDrop={csvUpload.setFiles}
|
||||
isError={csvUpload.noCsv}
|
||||
title="Upload CSV"
|
||||
className="py-16"
|
||||
description={
|
||||
csvUpload.noCsv
|
||||
? "Invalid CSV File. Follow the instructions below to upload a valid CSV file"
|
||||
: "Follow the instructions below to create a CSV file"
|
||||
}
|
||||
resetButton={{ label: "Remove CSV", onClick: csvUpload.reset }}
|
||||
accept=".csv"
|
||||
/>
|
||||
|
||||
<div>
|
||||
<h3 className="text-base font-medium mb-2">Requirements</h3>
|
||||
<ul className="list-disc list-outside pl-4 space-y-2 text-muted-foreground text-base leading-relaxed">
|
||||
<li>
|
||||
Files <em>must</em> contain one .csv file with an address and
|
||||
quantity column, if the quantity column is not provided, that
|
||||
record will be flagged as invalid.
|
||||
<Link
|
||||
color="primary.500"
|
||||
download
|
||||
href="/assets/examples/airdrop.csv"
|
||||
>
|
||||
Download an example CSV
|
||||
</Link>
|
||||
record will be flagged as invalid.{" "}
|
||||
</li>
|
||||
<li>
|
||||
Repeated addresses will be removed and only the first found will
|
||||
be kept.
|
||||
</li>
|
||||
</UnorderedList>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h3 className="text-base font-medium mb-2">CSV Example</h3>
|
||||
<DownloadableCode
|
||||
code={exampleAirdropCSV}
|
||||
lang="csv"
|
||||
fileNameWithExtension="airdrop.csv"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const csvParser = (items: AirdropAddressInput[]): AirdropAddressInput[] => {
|
||||
return items
|
||||
.map(({ address, quantity }) => ({
|
||||
address: address.trim(),
|
||||
quantity: (quantity || "1").trim(),
|
||||
}))
|
||||
.filter(({ address }) => address !== "");
|
||||
};
|
||||
|
||||
const exampleAirdropCSV = `address,quantity
|
||||
0xEb0effdFB4dC5b3d5d3aC6ce29F3ED213E95d675,10
|
||||
0x000000000000000000000000000000000000dEaD,1`;
|
||||
|
||||
+107
-109
@@ -1,140 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl, Input } from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { FlameIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { type ThirdwebContract, toUnits } from "thirdweb";
|
||||
import * as ERC20Ext from "thirdweb/extensions/erc20";
|
||||
import {
|
||||
useActiveAccount,
|
||||
useReadContract,
|
||||
useSendAndConfirmTransaction,
|
||||
} from "thirdweb/react";
|
||||
import { useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { z } from "zod";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DecimalInput } from "@/components/ui/decimal-input";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface TokenBurnButtonProps {
|
||||
const burnSchema = z.object({
|
||||
amount: z.string().refine(
|
||||
(val) => {
|
||||
const num = Number(val);
|
||||
return !Number.isNaN(num) && num > 0;
|
||||
},
|
||||
{
|
||||
message: "Amount must be greater than 0",
|
||||
},
|
||||
),
|
||||
});
|
||||
|
||||
export function TokenBurnButton(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
const BURN_FORM_ID = "token-burn-form";
|
||||
|
||||
export const TokenBurnButton: React.FC<TokenBurnButtonProps> = ({
|
||||
contract,
|
||||
isLoggedIn,
|
||||
...restButtonProps
|
||||
}) => {
|
||||
const address = useActiveAccount()?.address;
|
||||
|
||||
const tokenBalanceQuery = useReadContract(ERC20Ext.balanceOf, {
|
||||
address: address || "",
|
||||
contract,
|
||||
queryOptions: { enabled: !!address },
|
||||
}) {
|
||||
const sendConfirmation = useSendAndConfirmTransaction();
|
||||
const form = useForm<z.infer<typeof burnSchema>>({
|
||||
defaultValues: { amount: "0" },
|
||||
resolver: zodResolver(burnSchema),
|
||||
});
|
||||
|
||||
const hasBalance = tokenBalanceQuery.data && tokenBalanceQuery.data > 0n;
|
||||
const [open, setOpen] = useState(false);
|
||||
const sendConfirmation = useSendAndConfirmTransaction();
|
||||
const form = useForm({ defaultValues: { amount: "0" } });
|
||||
const decimalsQuery = useReadContract(ERC20Ext.decimals, { contract });
|
||||
async function onSubmit(data: z.infer<typeof burnSchema>) {
|
||||
// TODO: burn should be updated to take amount / amountWei (v6?)
|
||||
const burnTokensTx = ERC20Ext.burn({
|
||||
asyncParams: async () => {
|
||||
return {
|
||||
amount: toUnits(
|
||||
data.amount,
|
||||
await ERC20Ext.decimals({ contract: props.contract }),
|
||||
),
|
||||
};
|
||||
},
|
||||
contract: props.contract,
|
||||
});
|
||||
|
||||
const txPromise = sendConfirmation.mutateAsync(burnTokensTx);
|
||||
|
||||
toast.promise(txPromise, {
|
||||
error: (error) => ({
|
||||
message: "Failed to burn tokens",
|
||||
description: parseError(error),
|
||||
}),
|
||||
success: "Tokens burned successfully",
|
||||
});
|
||||
|
||||
await txPromise;
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
variant="primary"
|
||||
{...restButtonProps}
|
||||
className="gap-2"
|
||||
disabled={!hasBalance}
|
||||
>
|
||||
<Button className="gap-2">
|
||||
<FlameIcon className="size-4" /> Burn
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle className="text-left">Burn tokens</SheetTitle>
|
||||
</SheetHeader>
|
||||
<form className="mt-10 flex flex-col gap-3">
|
||||
<div className="flex w-full flex-col gap-6 md:flex-row">
|
||||
<FormControl isInvalid={!!form.formState.errors.amount} isRequired>
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<Input
|
||||
pattern={`^\\d+(\\.\\d{1,${decimalsQuery.data || 18}})?$`}
|
||||
type="text"
|
||||
{...form.register("amount")}
|
||||
/>
|
||||
<FormHelperText>How many would you like to burn?</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors.amount?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</div>
|
||||
<Text>
|
||||
Burning these{" "}
|
||||
{`${Number.parseInt(form.watch("amount")) > 1 ? form.watch("amount") : ""} `}
|
||||
tokens will remove them from the total circulating supply. This
|
||||
action is irreversible.
|
||||
</Text>
|
||||
</form>
|
||||
<SheetFooter className="mt-10">
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!form.formState.isDirty}
|
||||
form={BURN_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendConfirmation.isPending}
|
||||
onClick={form.handleSubmit((data) => {
|
||||
if (address) {
|
||||
// TODO: burn should be updated to take amount / amountWei (v6?)
|
||||
const tx = ERC20Ext.burn({
|
||||
asyncParams: async () => {
|
||||
return {
|
||||
amount: toUnits(
|
||||
data.amount,
|
||||
await ERC20Ext.decimals({ contract }),
|
||||
),
|
||||
};
|
||||
},
|
||||
contract,
|
||||
});
|
||||
|
||||
const promise = sendConfirmation.mutateAsync(tx, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset({ amount: "0" });
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.promise(promise, {
|
||||
error: "Failed to burn tokens",
|
||||
loading: `Burning ${data.amount} token(s)`,
|
||||
success: "Tokens burned successfully",
|
||||
});
|
||||
}
|
||||
})}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Burn Tokens
|
||||
</TransactionButton>
|
||||
</SheetFooter>
|
||||
<SheetContent className="!w-full lg:!max-w-lg">
|
||||
<SheetHeader className="mb-4">
|
||||
<SheetTitle className="text-left tracking-tight">
|
||||
Burn tokens
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="flex w-full flex-col gap-6 md:flex-row mb-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
<FormItem className="w-full">
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<FormControl>
|
||||
<DecimalInput className="bg-card" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
How many would you like to burn?
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Burning these tokens will remove them from the total circulating
|
||||
supply. This action is irreversible.
|
||||
</p>
|
||||
|
||||
<TransactionButton
|
||||
client={props.contract.client}
|
||||
disabled={!form.formState.isDirty}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={sendConfirmation.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={props.contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Burn Tokens
|
||||
</TransactionButton>
|
||||
</form>
|
||||
</Form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+146
-132
@@ -1,165 +1,179 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl, Input } from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { GemIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { type ThirdwebContract, ZERO_ADDRESS } from "thirdweb";
|
||||
import { isAddress, type ThirdwebContract } from "thirdweb";
|
||||
import * as ERC20Ext from "thirdweb/extensions/erc20";
|
||||
import {
|
||||
useActiveAccount,
|
||||
useReadContract,
|
||||
useSendAndConfirmTransaction,
|
||||
} from "thirdweb/react";
|
||||
import { useActiveAccount, useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { z } from "zod";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DecimalInput } from "@/components/ui/decimal-input";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface TokenClaimButtonProps {
|
||||
const claimFormSchema = z.object({
|
||||
to: z.string().refine(
|
||||
(val) => {
|
||||
if (isAddress(val)) return true;
|
||||
return false;
|
||||
},
|
||||
{ message: "Invalid address" },
|
||||
),
|
||||
amount: z.string().refine(
|
||||
(val) => {
|
||||
// must be a positive number
|
||||
const num = Number(val);
|
||||
return !Number.isNaN(num) && num > 0;
|
||||
},
|
||||
{ message: "Amount must be a positive number" },
|
||||
),
|
||||
});
|
||||
|
||||
type ClaimFormValues = z.infer<typeof claimFormSchema>;
|
||||
|
||||
export function TokenClaimButton(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
const CLAIM_FORM_ID = "token-claim-form";
|
||||
|
||||
export const TokenClaimButton: React.FC<TokenClaimButtonProps> = ({
|
||||
contract,
|
||||
isLoggedIn,
|
||||
...restButtonProps
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
}) {
|
||||
const sendAndConfirmTransaction = useSendAndConfirmTransaction();
|
||||
const account = useActiveAccount();
|
||||
const form = useForm({
|
||||
defaultValues: { amount: "0", to: account?.address },
|
||||
|
||||
const form = useForm<ClaimFormValues>({
|
||||
defaultValues: { amount: "0", to: account?.address || "" },
|
||||
resolver: zodResolver(claimFormSchema),
|
||||
});
|
||||
const { data: _decimals, isPending } = useReadContract(ERC20Ext.decimals, {
|
||||
contract,
|
||||
});
|
||||
const claimTokensNotifications = useTxNotifications(
|
||||
"Tokens claimed successfully",
|
||||
"Failed to claim tokens",
|
||||
);
|
||||
|
||||
async function onSubmit(d: ClaimFormValues) {
|
||||
if (!account) {
|
||||
return toast.error("Wallet is not connected");
|
||||
}
|
||||
|
||||
const transaction = ERC20Ext.claimTo({
|
||||
contract: props.contract,
|
||||
from: account.address,
|
||||
quantity: d.amount,
|
||||
to: d.to,
|
||||
});
|
||||
|
||||
const approveTx = await ERC20Ext.getApprovalForTransaction({
|
||||
account,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (approveTx) {
|
||||
const approveTxPromise = sendAndConfirmTransaction.mutateAsync(approveTx);
|
||||
toast.promise(approveTxPromise, {
|
||||
error: (error) => ({
|
||||
loading: "Approve Spending for claiming tokens",
|
||||
message: "Failed to approve tokens",
|
||||
description: parseError(error),
|
||||
}),
|
||||
success: "Tokens approved successfully",
|
||||
});
|
||||
|
||||
await approveTxPromise;
|
||||
}
|
||||
|
||||
const claimTxPromise = sendAndConfirmTransaction.mutateAsync(transaction);
|
||||
|
||||
toast.promise(claimTxPromise, {
|
||||
error: (error) => ({
|
||||
loading: "Claiming tokens",
|
||||
message: "Failed to claim tokens",
|
||||
description: parseError(error),
|
||||
}),
|
||||
success: "Tokens claimed successfully",
|
||||
});
|
||||
|
||||
await claimTxPromise;
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button className="gap-2" variant="primary" {...restButtonProps}>
|
||||
<GemIcon size={16} /> Claim
|
||||
<Button className="gap-2">
|
||||
<GemIcon className="size-4" /> Claim
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetContent className="!w-full lg:!max-w-xl">
|
||||
<SheetHeader className="mb-4">
|
||||
<SheetTitle className="text-left">Claim tokens</SheetTitle>
|
||||
</SheetHeader>
|
||||
<form>
|
||||
<div className="mt-10 flex flex-col gap-6">
|
||||
<FormControl isInvalid={!!form.formState.errors.to} isRequired>
|
||||
<FormLabel>To Address</FormLabel>
|
||||
<Input
|
||||
placeholder={ZERO_ADDRESS}
|
||||
{...form.register("to", { required: true })}
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="to"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>To Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="0x..."
|
||||
{...field}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The wallet address of the recipient
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>Enter the address to claim to.</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors.to?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!form.formState.errors.amount} isRequired>
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<Input
|
||||
pattern={`^\\d+(\\.\\d{1,${_decimals || 18}})?$`}
|
||||
type="text"
|
||||
{...form.register("amount", { required: true })}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<FormControl>
|
||||
<DecimalInput {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The amount of tokens to claim
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>How many would you like to claim?</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors.amount?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</div>
|
||||
</form>
|
||||
<SheetFooter className="mt-10">
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!form.formState.isDirty || isPending}
|
||||
form={CLAIM_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={form.formState.isSubmitting}
|
||||
onClick={form.handleSubmit(async (d) => {
|
||||
try {
|
||||
if (!d.to) {
|
||||
return toast.error(
|
||||
"Need to specify an address to receive tokens",
|
||||
);
|
||||
}
|
||||
</div>
|
||||
|
||||
if (!account) {
|
||||
return toast.error("No account detected");
|
||||
}
|
||||
const transaction = ERC20Ext.claimTo({
|
||||
contract,
|
||||
from: account.address,
|
||||
quantity: d.amount,
|
||||
to: d.to,
|
||||
});
|
||||
|
||||
const approveTx = await ERC20Ext.getApprovalForTransaction({
|
||||
account,
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (approveTx) {
|
||||
const promise = sendAndConfirmTransaction.mutateAsync(
|
||||
approveTx,
|
||||
{
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
},
|
||||
);
|
||||
toast.promise(promise, {
|
||||
error: "Failed to approve token",
|
||||
loading: "Approving ERC20 tokens for this claim",
|
||||
success: "Tokens approved successfully",
|
||||
});
|
||||
|
||||
await promise;
|
||||
}
|
||||
|
||||
await sendAndConfirmTransaction.mutateAsync(transaction, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset({ amount: "0", to: account?.address });
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
claimTokensNotifications.onSuccess();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
claimTokensNotifications.onError(error);
|
||||
}
|
||||
})}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Claim Tokens
|
||||
</TransactionButton>
|
||||
</SheetFooter>
|
||||
<div className="mt-6 flex">
|
||||
<TransactionButton
|
||||
client={props.contract.client}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={form.formState.isSubmitting}
|
||||
transactionCount={1}
|
||||
txChainID={props.contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Claim Tokens
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+100
-90
@@ -1,125 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl, Input } from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormLabel } from "chakra/form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import * as ERC20Ext from "thirdweb/extensions/erc20";
|
||||
import {
|
||||
useActiveAccount,
|
||||
useReadContract,
|
||||
useSendAndConfirmTransaction,
|
||||
} from "thirdweb/react";
|
||||
import { useActiveAccount, useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { z } from "zod";
|
||||
import { MinterOnly } from "@/components/contracts/roles/minter-only";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface TokenMintButtonProps {
|
||||
const mintFormSchema = z.object({
|
||||
amount: z
|
||||
.string()
|
||||
.min(1, "Amount is required")
|
||||
.refine((val) => {
|
||||
const num = Number(val);
|
||||
return !Number.isNaN(num) && num > 0;
|
||||
}, "Amount must be a positive number"),
|
||||
});
|
||||
|
||||
type MintFormValues = z.infer<typeof mintFormSchema>;
|
||||
|
||||
export function TokenMintButton(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
const MINT_FORM_ID = "token-mint-form";
|
||||
|
||||
/**
|
||||
* This component is for minting tokens to a TokenERC20 contract (NOT DropERC20)
|
||||
*/
|
||||
export const TokenMintButton: React.FC<TokenMintButtonProps> = ({
|
||||
contract,
|
||||
isLoggedIn,
|
||||
...restButtonProps
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
}) {
|
||||
const address = useActiveAccount()?.address;
|
||||
const { data: tokenDecimals } = useReadContract(ERC20Ext.decimals, {
|
||||
contract,
|
||||
});
|
||||
const sendAndConfirmTransaction = useSendAndConfirmTransaction();
|
||||
const form = useForm({ defaultValues: { amount: "0" } });
|
||||
const form = useForm<MintFormValues>({
|
||||
resolver: zodResolver(mintFormSchema),
|
||||
defaultValues: { amount: "" },
|
||||
mode: "onChange",
|
||||
});
|
||||
|
||||
async function handleSubmit(values: MintFormValues) {
|
||||
if (!address) {
|
||||
toast.error("No wallet connected");
|
||||
return;
|
||||
}
|
||||
|
||||
const mintTx = ERC20Ext.mintTo({
|
||||
amount: values.amount,
|
||||
contract: props.contract,
|
||||
to: address,
|
||||
});
|
||||
|
||||
const mintTxPromise = sendAndConfirmTransaction.mutateAsync(mintTx);
|
||||
toast.promise(mintTxPromise, {
|
||||
error: (err) => ({
|
||||
message: "Failed to mint tokens",
|
||||
description: parseError(err),
|
||||
}),
|
||||
success: "Tokens minted successfully",
|
||||
});
|
||||
|
||||
await mintTxPromise;
|
||||
}
|
||||
|
||||
return (
|
||||
<MinterOnly contract={contract}>
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<MinterOnly contract={props.contract}>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="primary" {...restButtonProps} className="gap-2">
|
||||
<PlusIcon size={16} /> Mint
|
||||
<Button className="gap-2">
|
||||
<PlusIcon className="size-4" /> Mint
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
|
||||
<SheetContent className="!w-full lg:!max-w-lg">
|
||||
<SheetHeader className="mb-4">
|
||||
<SheetTitle className="text-left">
|
||||
Mint additional tokens
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<form
|
||||
className="mt-10 flex flex-col gap-6"
|
||||
id={MINT_FORM_ID}
|
||||
onSubmit={form.handleSubmit((d) => {
|
||||
if (!address) {
|
||||
return toast.error("No wallet connected");
|
||||
}
|
||||
const transaction = ERC20Ext.mintTo({
|
||||
amount: d.amount,
|
||||
contract,
|
||||
to: address,
|
||||
});
|
||||
const promise = sendAndConfirmTransaction.mutateAsync(
|
||||
transaction,
|
||||
{
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset({ amount: "0" });
|
||||
setOpen(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
toast.promise(promise, {
|
||||
error: "Failed to mint tokens",
|
||||
loading: "Minting tokens",
|
||||
success: "Tokens minted successfully",
|
||||
});
|
||||
})}
|
||||
>
|
||||
<FormControl isInvalid={!!form.formState.errors.amount} isRequired>
|
||||
<FormLabel>Additional Supply</FormLabel>
|
||||
<Input
|
||||
pattern={`^\\d+(\\.\\d{1,${tokenDecimals || 18}})?$`}
|
||||
type="text"
|
||||
{...form.register("amount")}
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)}>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Additional Supply</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="text" {...field} className="bg-card" />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The amount of tokens to mint
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors?.amount?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</form>
|
||||
<SheetFooter className="mt-10">
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!form.formState.isDirty}
|
||||
form={MINT_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendAndConfirmTransaction.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Mint Tokens
|
||||
</TransactionButton>
|
||||
</SheetFooter>
|
||||
|
||||
<div className="mt-6 flex">
|
||||
<TransactionButton
|
||||
client={props.contract.client}
|
||||
disabled={!form.formState.isDirty || !form.formState.isValid}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={sendAndConfirmTransaction.isPending}
|
||||
transactionCount={1}
|
||||
txChainID={props.contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Mint Tokens
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</MinterOnly>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+135
-108
@@ -1,138 +1,165 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl, Input } from "@chakra-ui/react";
|
||||
import { FormErrorMessage, FormHelperText, FormLabel } from "chakra/form";
|
||||
import { SendIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { ForwardIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { type ThirdwebContract, ZERO_ADDRESS } from "thirdweb";
|
||||
import { isAddress, type ThirdwebContract, ZERO_ADDRESS } from "thirdweb";
|
||||
import * as ERC20Ext from "thirdweb/extensions/erc20";
|
||||
import {
|
||||
useActiveAccount,
|
||||
useReadContract,
|
||||
useSendAndConfirmTransaction,
|
||||
} from "thirdweb/react";
|
||||
import { useSendAndConfirmTransaction } from "thirdweb/react";
|
||||
import { z } from "zod";
|
||||
import { SolidityInput } from "@/components/solidity-inputs";
|
||||
import { TransactionButton } from "@/components/tx-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DecimalInput } from "@/components/ui/decimal-input";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/ui/sheet";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface TokenTransferButtonProps {
|
||||
const transferFormSchema = z.object({
|
||||
to: z.string().refine(
|
||||
(val) => {
|
||||
if (isAddress(val)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
{
|
||||
message: "Invalid address",
|
||||
},
|
||||
),
|
||||
amount: z.string().refine(
|
||||
(val) => {
|
||||
// must be a positive number
|
||||
const num = Number(val);
|
||||
return !Number.isNaN(num) && num > 0;
|
||||
},
|
||||
{ message: "Amount must be a positive number" },
|
||||
),
|
||||
});
|
||||
|
||||
type TransferFormValues = z.infer<typeof transferFormSchema>;
|
||||
|
||||
export function TokenTransferButton(props: {
|
||||
contract: ThirdwebContract;
|
||||
isLoggedIn: boolean;
|
||||
}
|
||||
|
||||
const TRANSFER_FORM_ID = "token-transfer-form";
|
||||
|
||||
export const TokenTransferButton: React.FC<TokenTransferButtonProps> = ({
|
||||
contract,
|
||||
isLoggedIn,
|
||||
...restButtonProps
|
||||
}) => {
|
||||
const address = useActiveAccount()?.address;
|
||||
const tokenBalanceQuery = useReadContract(ERC20Ext.balanceOf, {
|
||||
address: address || "",
|
||||
contract,
|
||||
queryOptions: { enabled: !!address },
|
||||
}) {
|
||||
const form = useForm<TransferFormValues>({
|
||||
defaultValues: { amount: "0", to: "" },
|
||||
resolver: zodResolver(transferFormSchema),
|
||||
});
|
||||
const form = useForm({ defaultValues: { amount: "0", to: "" } });
|
||||
const hasBalance = tokenBalanceQuery.data && tokenBalanceQuery.data > 0n;
|
||||
const decimalsQuery = useReadContract(ERC20Ext.decimals, { contract });
|
||||
const sendConfirmation = useSendAndConfirmTransaction();
|
||||
const [open, setOpen] = useState(false);
|
||||
const sendAndConfirmTransaction = useSendAndConfirmTransaction();
|
||||
|
||||
async function onSubmit(values: TransferFormValues) {
|
||||
const transferTx = ERC20Ext.transfer({
|
||||
amount: values.amount,
|
||||
contract: props.contract,
|
||||
to: values.to,
|
||||
});
|
||||
|
||||
const transferTxPromise = sendAndConfirmTransaction.mutateAsync(transferTx);
|
||||
|
||||
toast.promise(transferTxPromise, {
|
||||
error: (error) => ({
|
||||
message: "Failed to transfer tokens",
|
||||
description: parseError(error),
|
||||
}),
|
||||
success: "Successfully transferred tokens",
|
||||
});
|
||||
|
||||
await transferTxPromise;
|
||||
}
|
||||
|
||||
return (
|
||||
<Sheet onOpenChange={setOpen} open={open}>
|
||||
<Sheet>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
variant="primary"
|
||||
{...restButtonProps}
|
||||
className="gap-2"
|
||||
disabled={!hasBalance}
|
||||
>
|
||||
<SendIcon size={16} /> Transfer
|
||||
<Button className="gap-2">
|
||||
<ForwardIcon className="size-4" /> Transfer
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent>
|
||||
<SheetHeader>
|
||||
<SheetTitle className="text-left">Transfer tokens</SheetTitle>
|
||||
<SheetContent className="!w-full lg:!max-w-lg">
|
||||
<SheetHeader className="mb-4">
|
||||
<SheetTitle className="text-left tracking-tight">
|
||||
Transfer tokens
|
||||
</SheetTitle>
|
||||
</SheetHeader>
|
||||
<form className="mt-10">
|
||||
<div className="flex flex-col gap-6">
|
||||
<FormControl isInvalid={!!form.formState.errors.to} isRequired>
|
||||
<FormLabel>To Address</FormLabel>
|
||||
<SolidityInput
|
||||
client={contract.client}
|
||||
formContext={form}
|
||||
placeholder={ZERO_ADDRESS}
|
||||
solidityType="address"
|
||||
{...form.register("to")}
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="to"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Address</FormLabel>
|
||||
<FormControl>
|
||||
<SolidityInput
|
||||
client={props.contract.client}
|
||||
formContext={form}
|
||||
placeholder={ZERO_ADDRESS}
|
||||
solidityType="address"
|
||||
{...field}
|
||||
className="bg-card"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
The wallet address of the recipient
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>Enter the address to transfer to.</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors.to?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
<FormControl isInvalid={!!form.formState.errors.amount} isRequired>
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<Input
|
||||
pattern={`^\\d+(\\.\\d{1,${decimalsQuery.data || 18}})?$`}
|
||||
type="text"
|
||||
{...form.register("amount")}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="amount"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Amount</FormLabel>
|
||||
<FormControl>
|
||||
<DecimalInput
|
||||
id="amount"
|
||||
value={field.value}
|
||||
className="bg-card"
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Number of tokens to transfer
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormHelperText>
|
||||
How many would you like to transfer?
|
||||
</FormHelperText>
|
||||
<FormErrorMessage>
|
||||
{form.formState.errors.amount?.message}
|
||||
</FormErrorMessage>
|
||||
</FormControl>
|
||||
</div>
|
||||
</form>
|
||||
<SheetFooter className="mt-10">
|
||||
<TransactionButton
|
||||
client={contract.client}
|
||||
disabled={!form.formState.isDirty}
|
||||
form={TRANSFER_FORM_ID}
|
||||
isLoggedIn={isLoggedIn}
|
||||
isPending={sendConfirmation.isPending}
|
||||
onClick={form.handleSubmit((d) => {
|
||||
const transaction = ERC20Ext.transfer({
|
||||
amount: d.amount,
|
||||
contract,
|
||||
to: d.to,
|
||||
});
|
||||
const promise = sendConfirmation.mutateAsync(transaction, {
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
form.reset({ amount: "0", to: "" });
|
||||
setOpen(false);
|
||||
},
|
||||
});
|
||||
toast.promise(promise, {
|
||||
error: "Failed to transfer tokens",
|
||||
loading: "Transferring tokens",
|
||||
success: "Successfully transferred tokens",
|
||||
});
|
||||
})}
|
||||
transactionCount={1}
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
Transfer Tokens
|
||||
</TransactionButton>
|
||||
</SheetFooter>
|
||||
</div>
|
||||
<div className="flex mt-6">
|
||||
<TransactionButton
|
||||
client={props.contract.client}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isPending={sendAndConfirmTransaction.isPending}
|
||||
type="submit"
|
||||
transactionCount={1}
|
||||
txChainID={props.contract.chain.id}
|
||||
>
|
||||
Transfer Tokens
|
||||
</TransactionButton>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+8
-1
@@ -52,11 +52,18 @@ export async function SharedContractTokensPage(props: {
|
||||
info.serverContract,
|
||||
);
|
||||
|
||||
if (!supportedERCs.isERC20) {
|
||||
redirectToContractLandingPage({
|
||||
chainIdOrSlug: props.chainIdOrSlug,
|
||||
contractAddress: props.contractAddress,
|
||||
projectMeta: props.projectMeta,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<ContractTokensPage
|
||||
contract={info.clientContract}
|
||||
isClaimToSupported={isClaimToSupported(functionSelectors)}
|
||||
isERC20={supportedERCs.isERC20}
|
||||
isLoggedIn={props.isLoggedIn}
|
||||
isMintToSupported={isMintToSupported(functionSelectors)}
|
||||
/>
|
||||
|
||||
@@ -41,14 +41,14 @@ export const products = [
|
||||
description: "Enable gas sponsorship for seamless transactions",
|
||||
icon: SmartAccountIcon,
|
||||
id: "account-abstraction",
|
||||
link: "https://portal.thirdweb.com/connect/account-abstraction/overview",
|
||||
link: "https://portal.thirdweb.com/wallets/sponsor-gas",
|
||||
name: "Account Abstraction",
|
||||
},
|
||||
{
|
||||
description: "Enable payments in any token on any chain",
|
||||
icon: PayIcon,
|
||||
id: "pay",
|
||||
link: "https://portal.thirdweb.com/connect/pay/overview",
|
||||
link: "https://portal.thirdweb.com/payments",
|
||||
name: "Payments",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -168,7 +168,7 @@ async function AsyncAppHighlightsCard(props: {
|
||||
|
||||
return (
|
||||
<EmptyStateCard
|
||||
link="https://portal.thirdweb.com/connect/quickstart"
|
||||
link="https://portal.thirdweb.com/wallets"
|
||||
metric="Wallets"
|
||||
/>
|
||||
);
|
||||
@@ -189,7 +189,7 @@ async function AsyncWalletDistributionCard(props: {
|
||||
<WalletDistributionCard data={walletConnections} />
|
||||
) : (
|
||||
<EmptyStateCard
|
||||
link="https://portal.thirdweb.com/connect/quickstart"
|
||||
link="https://portal.thirdweb.com/wallets"
|
||||
metric="Wallets"
|
||||
/>
|
||||
);
|
||||
@@ -248,7 +248,7 @@ async function AsyncTransactionsChartCard(props: {
|
||||
/>
|
||||
) : (
|
||||
<EmptyStateCard
|
||||
link="https://portal.thirdweb.com/connect/quickstart"
|
||||
link="https://portal.thirdweb.com/wallets"
|
||||
metric="Wallets"
|
||||
/>
|
||||
);
|
||||
@@ -355,7 +355,7 @@ function AppHighlightsCard({
|
||||
emptyContent: (
|
||||
<EmptyStateContent
|
||||
description="Your apps haven't collected any fees yet."
|
||||
link={"https://portal.thirdweb.com/connect/pay/fees"}
|
||||
link={"https://portal.thirdweb.com/payments"}
|
||||
metric="Fees"
|
||||
/>
|
||||
),
|
||||
@@ -368,7 +368,7 @@ function AppHighlightsCard({
|
||||
emptyContent: (
|
||||
<EmptyStateContent
|
||||
description="Onramp, swap, and bridge with thirdweb's Payments."
|
||||
link="https://portal.thirdweb.com/connect/pay/overview"
|
||||
link="https://portal.thirdweb.com/payments"
|
||||
metric="Payments"
|
||||
/>
|
||||
),
|
||||
|
||||
+42
-8
@@ -11,6 +11,7 @@ import {
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
@@ -39,6 +40,12 @@ export function CreditBalanceSection({
|
||||
const [selectedAmount, setSelectedAmount] = useState<string>(
|
||||
predefinedAmounts[0].value,
|
||||
);
|
||||
const [customAmount, setCustomAmount] = useState<string>("");
|
||||
|
||||
const isSelectedAmountValid =
|
||||
selectedAmount !== "" &&
|
||||
Number.isInteger(Number(selectedAmount)) &&
|
||||
Number(selectedAmount) > 0;
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
@@ -61,7 +68,7 @@ export function CreditBalanceSection({
|
||||
|
||||
<Separator />
|
||||
<div className="space-y-2">
|
||||
<h3 className="font-medium text-lg">Top Up Credits</h3>
|
||||
<h3 className="font-medium text-lg">Credits</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Add credits to your account for future billing cycles. Credits are
|
||||
non-refundable and do not expire.
|
||||
@@ -74,7 +81,10 @@ export function CreditBalanceSection({
|
||||
<Label className="font-medium text-base">Select Amount</Label>
|
||||
<RadioGroup
|
||||
className="grid grid-cols-4 gap-3"
|
||||
onValueChange={setSelectedAmount}
|
||||
onValueChange={(value) => {
|
||||
setSelectedAmount(value);
|
||||
setCustomAmount("");
|
||||
}}
|
||||
value={selectedAmount}
|
||||
>
|
||||
{predefinedAmounts.map((amount) => (
|
||||
@@ -95,6 +105,30 @@ export function CreditBalanceSection({
|
||||
</div>
|
||||
))}
|
||||
</RadioGroup>
|
||||
|
||||
{/* Custom Amount Input */}
|
||||
<div className="space-y-2">
|
||||
<Label className="font-medium text-base" htmlFor="customAmount">
|
||||
Or enter custom amount
|
||||
</Label>
|
||||
<Input
|
||||
id="customAmount"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
pattern="[0-9]*"
|
||||
min={1}
|
||||
step={1}
|
||||
value={customAmount}
|
||||
placeholder="Custom amount"
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/^0+/, "");
|
||||
if (/^\d*$/.test(val)) {
|
||||
setCustomAmount(val);
|
||||
setSelectedAmount(val);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top-up Summary and Button */}
|
||||
@@ -118,14 +152,14 @@ export function CreditBalanceSection({
|
||||
|
||||
<ToolTipLabel
|
||||
label={
|
||||
isOwnerAccount ? null : "Only team owners can top up credits."
|
||||
isOwnerAccount ? null : "Only team owners can purchase credits."
|
||||
}
|
||||
>
|
||||
<div>
|
||||
<Button
|
||||
asChild
|
||||
className="w-full"
|
||||
disabled={!isOwnerAccount}
|
||||
disabled={!isOwnerAccount || !isSelectedAmountValid}
|
||||
size="lg"
|
||||
>
|
||||
<a
|
||||
@@ -134,7 +168,7 @@ export function CreditBalanceSection({
|
||||
target="_blank"
|
||||
>
|
||||
<ThirdwebMiniLogo className="mr-2 h-4 w-4" />
|
||||
Top Up With Crypto
|
||||
Buy Credits
|
||||
<ArrowRightIcon className="ml-2 h-4 w-4" />
|
||||
</a>
|
||||
</Button>
|
||||
@@ -203,7 +237,7 @@ function TopUpSummary({
|
||||
<div className="space-y-3 rounded-lg bg-muted/30 p-4">
|
||||
<h3 className="font-medium text-sm">Summary</h3>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Top-up amount:</span>
|
||||
<span>Added credits:</span>
|
||||
<span className="font-medium">{formatUsd(Number(selectedAmount))}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
@@ -221,7 +255,7 @@ function TopUpSummarySkeleton({ selectedAmount }: { selectedAmount: string }) {
|
||||
<div className="space-y-3 rounded-lg bg-muted/30 p-4">
|
||||
<h3 className="font-medium text-sm">Summary</h3>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Top-up amount:</span>
|
||||
<span>Added credits:</span>
|
||||
<span className="font-medium">{formatUsd(Number(selectedAmount))}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
@@ -241,7 +275,7 @@ function TopUpSummaryErrorBoundary({
|
||||
<div className="space-y-3 rounded-lg bg-muted/30 p-4">
|
||||
<h3 className="font-medium text-sm">Summary</h3>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Top-up amount:</span>
|
||||
<span>Added credits:</span>
|
||||
<span className="font-medium">{formatUsd(Number(selectedAmount))}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
|
||||
+1
-1
@@ -391,7 +391,7 @@ export function AuthOptionsForm({
|
||||
Enter the URL for your own authentication endpoint.{" "}
|
||||
<a
|
||||
className="underline"
|
||||
href="https://portal.thirdweb.com/connect/in-app-wallet/custom-auth/configuration#generic-auth"
|
||||
href="https://portal.thirdweb.com/wallets/custom-auth"
|
||||
>
|
||||
Learn more.
|
||||
</a>
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ export async function EcosystemCreatePage(props: {
|
||||
<br /> You can control which apps join your ecosystem and how their
|
||||
users interact with your wallet.{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/connect/ecosystems/overview"
|
||||
href="https://portal.thirdweb.com/wallets/ecosystem/set-up"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
|
||||
+1
-1
@@ -167,7 +167,7 @@ export function CreateEcosystemForm(props: {
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/connect/wallet/ecosystem/permissions"
|
||||
href="https://portal.thirdweb.com/wallets/ecosystem/set-up#Set%20Ecosystem%20Permissions"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ export function AAFooter() {
|
||||
left={{
|
||||
links: [
|
||||
{
|
||||
href: "https://portal.thirdweb.com/connect/account-abstraction/overview",
|
||||
href: "https://portal.thirdweb.com/wallets/sponsor-gas",
|
||||
label: "Overview",
|
||||
},
|
||||
{
|
||||
|
||||
-8
@@ -11,7 +11,6 @@ import { getTeamBySlug } from "@/api/team";
|
||||
import { ClientOnly } from "@/components/blocks/client-only";
|
||||
import { GenericLoadingPage } from "@/components/blocks/skeletons/GenericLoadingPage";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
@@ -80,13 +79,6 @@ function YourFactoriesSection(props: {
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Deploy your own account factories to create smart wallets.{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/connect/account-abstraction/factories"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Learn more{" "}
|
||||
</UnderlineLink>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
+1
-1
@@ -254,7 +254,7 @@ function ProductsSection(props: { teamSlug: string; projectSlug: string }) {
|
||||
{
|
||||
description:
|
||||
"Bridge, swap, and purchase cryptocurrencies with any fiat options or tokens via cross-chain routing",
|
||||
href: `/team/${props.teamSlug}/${props.projectSlug}/universal-bridge`,
|
||||
href: `/team/${props.teamSlug}/${props.projectSlug}/payments`,
|
||||
icon: PayIcon,
|
||||
title: "Payments",
|
||||
},
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ export function ProjectSidebarLayout(props: {
|
||||
group: "Monetize",
|
||||
links: [
|
||||
{
|
||||
href: `${layoutPath}/universal-bridge`,
|
||||
href: `${layoutPath}/payments`,
|
||||
icon: PayIcon,
|
||||
label: "Payments",
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { FormControl } from "@chakra-ui/react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { CircleAlertIcon, DownloadIcon, ExternalLinkIcon } from "lucide-react";
|
||||
@@ -12,6 +11,7 @@ import { apiServerProxy } from "@/actions/proxies";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
|
||||
+140
-132
@@ -1,33 +1,28 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
type UseDisclosureReturn,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { PencilIcon, Trash2Icon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { TWTable } from "@/components/blocks/TWTable";
|
||||
import { WalletAddress } from "@/components/blocks/wallet-address";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import {
|
||||
type AccessToken,
|
||||
useEngineRevokeAccessToken,
|
||||
useEngineUpdateAccessToken,
|
||||
} from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { toDateTimeLocal } from "@/utils/date-utils";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface AccessTokensTableProps {
|
||||
instanceUrl: string;
|
||||
@@ -40,36 +35,32 @@ interface AccessTokensTableProps {
|
||||
|
||||
const columnHelper = createColumnHelper<AccessToken>();
|
||||
|
||||
export const AccessTokensTable: React.FC<AccessTokensTableProps> = ({
|
||||
export function AccessTokensTable({
|
||||
instanceUrl,
|
||||
accessTokens,
|
||||
isPending,
|
||||
isFetched,
|
||||
authToken,
|
||||
client,
|
||||
}) => {
|
||||
const editDisclosure = useDisclosure();
|
||||
const removeDisclosure = useDisclosure();
|
||||
}: AccessTokensTableProps) {
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [selectedAccessToken, setSelectedAccessToken] = useState<AccessToken>();
|
||||
|
||||
const columns = useMemo(() => {
|
||||
return [
|
||||
columnHelper.accessor("tokenMask", {
|
||||
cell: (cell) => {
|
||||
return (
|
||||
<p className="py-3 font-mono text-foreground">{cell.getValue()}</p>
|
||||
);
|
||||
},
|
||||
cell: (cell) => (
|
||||
<p className="py-3 font-mono text-foreground">{cell.getValue()}</p>
|
||||
),
|
||||
header: "Access Token",
|
||||
}),
|
||||
columnHelper.accessor("label", {
|
||||
cell: (cell) => {
|
||||
return (
|
||||
<Text isTruncated maxW={300}>
|
||||
{cell.getValue()}
|
||||
</Text>
|
||||
);
|
||||
},
|
||||
cell: (cell) => (
|
||||
<span className="truncate max-w-[300px] block">
|
||||
{cell.getValue()}
|
||||
</span>
|
||||
),
|
||||
header: "Label",
|
||||
}),
|
||||
columnHelper.accessor("walletAddress", {
|
||||
@@ -82,11 +73,8 @@ export const AccessTokensTable: React.FC<AccessTokensTableProps> = ({
|
||||
columnHelper.accessor("createdAt", {
|
||||
cell: (cell) => {
|
||||
const value = cell.getValue();
|
||||
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
return <Text>{toDateTimeLocal(value)}</Text>;
|
||||
if (!value) return null;
|
||||
return <span>{toDateTimeLocal(value)}</span>;
|
||||
},
|
||||
header: "Created At",
|
||||
}),
|
||||
@@ -105,7 +93,7 @@ export const AccessTokensTable: React.FC<AccessTokensTableProps> = ({
|
||||
icon: <PencilIcon className="size-4" />,
|
||||
onClick: (accessToken) => {
|
||||
setSelectedAccessToken(accessToken);
|
||||
editDisclosure.onOpen();
|
||||
setEditOpen(true);
|
||||
},
|
||||
text: "Edit",
|
||||
},
|
||||
@@ -114,181 +102,201 @@ export const AccessTokensTable: React.FC<AccessTokensTableProps> = ({
|
||||
isDestructive: true,
|
||||
onClick: (accessToken) => {
|
||||
setSelectedAccessToken(accessToken);
|
||||
removeDisclosure.onOpen();
|
||||
setRemoveOpen(true);
|
||||
},
|
||||
text: "Delete",
|
||||
},
|
||||
]}
|
||||
title="access tokens"
|
||||
/>
|
||||
|
||||
{selectedAccessToken && editDisclosure.isOpen && (
|
||||
{selectedAccessToken && (
|
||||
<EditModal
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
accessToken={selectedAccessToken}
|
||||
authToken={authToken}
|
||||
disclosure={editDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
/>
|
||||
)}
|
||||
{selectedAccessToken && removeDisclosure.isOpen && (
|
||||
{selectedAccessToken && (
|
||||
<RemoveModal
|
||||
open={removeOpen}
|
||||
onOpenChange={setRemoveOpen}
|
||||
accessToken={selectedAccessToken}
|
||||
authToken={authToken}
|
||||
disclosure={removeDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const EditModal = ({
|
||||
function EditModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
accessToken,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
accessToken: AccessToken;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) => {
|
||||
const { mutate: updateAccessToken } = useEngineUpdateAccessToken({
|
||||
}) {
|
||||
const updateToken = useEngineUpdateAccessToken({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully updated access token",
|
||||
"Failed to update access token",
|
||||
);
|
||||
|
||||
const [label, setLabel] = useState(accessToken.label ?? "");
|
||||
|
||||
const onClick = () => {
|
||||
updateAccessToken(
|
||||
updateToken.mutate(
|
||||
{
|
||||
id: accessToken.id,
|
||||
label,
|
||||
},
|
||||
{
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to update access token", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
disclosure.onClose();
|
||||
toast.success("Successfully updated access token");
|
||||
onOpenChange(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Update Access Token</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormControl>
|
||||
<FormLabel>Access Token</FormLabel>
|
||||
<Text>{accessToken.tokenMask}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
placeholder="Enter a description for this access token"
|
||||
type="text"
|
||||
value={label}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Update Access Token</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} type="button" variant="ghost">
|
||||
<div className="px-4 lg:px-6 space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<h3 className="text-sm font-medium">Access Token </h3>
|
||||
<div className="font-mono text-sm text-muted-foreground">
|
||||
{accessToken.tokenMask}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="edit-label">Label</Label>
|
||||
<Input
|
||||
id="edit-label"
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
placeholder="Enter a description for this access token"
|
||||
className="bg-card"
|
||||
type="text"
|
||||
value={label}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 border-t p-4 lg:p-6 mt-8 bg-card">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
type="button"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="blue" onClick={onClick} type="submit">
|
||||
<Button onClick={onClick} type="submit" className="gap-2">
|
||||
{updateToken.isPending && <Spinner className="size-4" />}
|
||||
Save
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const RemoveModal = ({
|
||||
function RemoveModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
accessToken,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
accessToken: AccessToken;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) => {
|
||||
const { mutate: deleteAccessToken } = useEngineRevokeAccessToken({
|
||||
}) {
|
||||
const deleteToken = useEngineRevokeAccessToken({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully deleted access token",
|
||||
"Failed to delete access token",
|
||||
);
|
||||
|
||||
const onClick = () => {
|
||||
deleteAccessToken(
|
||||
deleteToken.mutate(
|
||||
{
|
||||
id: accessToken.id,
|
||||
},
|
||||
{
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to delete access token", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
disclosure.onClose();
|
||||
toast.success("Successfully deleted access token");
|
||||
onOpenChange(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Delete Access Token</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Text>Are you sure you want to delete this access token?</Text>
|
||||
<FormControl>
|
||||
<FormLabel>Access Token</FormLabel>
|
||||
<Text>{accessToken.tokenMask}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Text>{accessToken.label ?? <em>N/A</em>}</Text>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Delete access token</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete this access token?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} type="button" variant="ghost">
|
||||
<div className="px-4 lg:px-6 space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<h3 className="text-sm font-medium">Access Token </h3>
|
||||
<div className="font-mono text-sm text-muted-foreground">
|
||||
{accessToken.tokenMask}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>Label</Label>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{accessToken.label ?? <span> No Label </span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 border-t p-4 lg:p-6 mt-8 bg-card">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
type="button"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="red" onClick={onClick} type="submit">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={onClick}
|
||||
type="submit"
|
||||
className="gap-2"
|
||||
>
|
||||
{deleteToken.isPending && <Spinner className="size-4" />}
|
||||
Delete
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+64
-73
@@ -1,111 +1,102 @@
|
||||
import {
|
||||
Flex,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { Text } from "chakra/text";
|
||||
import { CirclePlusIcon } from "lucide-react";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox, CheckboxWithLabel } from "@/components/ui/checkbox";
|
||||
import { PlainTextCodeBlock } from "@/components/ui/code/plaintext-code";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { useEngineCreateAccessToken } from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface AddAccessTokenButtonProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
export const AddAccessTokenButton: React.FC<AddAccessTokenButtonProps> = ({
|
||||
export function AddAccessTokenButton({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
const [accessToken, setAccessToken] = useState<string>("");
|
||||
const { isOpen, onOpen, onClose } = useDisclosure();
|
||||
const { mutate: createAccessToken } = useEngineCreateAccessToken({
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [accessToken, setAccessToken] = useState("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const createAccessToken = useEngineCreateAccessToken({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const [hasStoredToken, setHasStoredToken] = useState<boolean>(false);
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Access token created successfully.",
|
||||
"Failed to create Access Token.",
|
||||
);
|
||||
const [hasStoredToken, setHasStoredToken] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
leftIcon={<CirclePlusIcon className="size-6" />}
|
||||
className="gap-2"
|
||||
onClick={() => {
|
||||
createAccessToken(undefined, {
|
||||
createAccessToken.mutate(undefined, {
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to create access token", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: (response) => {
|
||||
onSuccess();
|
||||
toast.success("Access token created successfully");
|
||||
setAccessToken(response.accessToken);
|
||||
onOpen();
|
||||
setIsOpen(true);
|
||||
},
|
||||
});
|
||||
}}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
w="fit-content"
|
||||
>
|
||||
{createAccessToken.isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<PlusIcon className="size-4" />
|
||||
)}
|
||||
Create Access Token
|
||||
</Button>
|
||||
|
||||
<Modal
|
||||
closeOnEsc={false}
|
||||
closeOnOverlayClick={false}
|
||||
isCentered
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsOpen(open);
|
||||
if (!open) setAccessToken("");
|
||||
}}
|
||||
>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Access token</ModalHeader>
|
||||
<ModalBody as={Flex} flexDir="column" gap={4}>
|
||||
<div className="flex flex-col gap-4">
|
||||
<PlainTextCodeBlock code={accessToken} />
|
||||
<Text color="red.500">
|
||||
This access token will not be shown again.
|
||||
</Text>
|
||||
<CheckboxWithLabel>
|
||||
<Checkbox
|
||||
checked={hasStoredToken}
|
||||
onCheckedChange={(val) => setHasStoredToken(!!val)}
|
||||
/>
|
||||
<span>I have securely stored this access token.</span>
|
||||
</CheckboxWithLabel>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<DialogContent className="p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Access token</DialogTitle>
|
||||
<DialogDescription>
|
||||
This access token will not be shown again.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<div className="space-y-4 overflow-hidden px-4 lg:px-6">
|
||||
<PlainTextCodeBlock code={accessToken} className="max-w-full" />
|
||||
<CheckboxWithLabel>
|
||||
<Checkbox
|
||||
checked={hasStoredToken}
|
||||
onCheckedChange={(val) => setHasStoredToken(!!val)}
|
||||
/>
|
||||
<span>I have securely stored this access token.</span>
|
||||
</CheckboxWithLabel>
|
||||
</div>
|
||||
|
||||
<div className="p-4 lg:p-6 border-t bg-card mt-8 flex justify-end">
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={!hasStoredToken}
|
||||
disabled={!hasStoredToken}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
setIsOpen(false);
|
||||
setAccessToken("");
|
||||
}}
|
||||
type="submit"
|
||||
>
|
||||
Done
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+125
-130
@@ -1,26 +1,27 @@
|
||||
import {
|
||||
Alert,
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
Select,
|
||||
Textarea,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { CirclePlusIcon } from "lucide-react";
|
||||
import { InfoIcon, PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { PlainTextCodeBlock } from "@/components/ui/code/plaintext-code";
|
||||
import { toast } from "sonner";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { type KeypairAlgorithm, useEngineAddKeypair } from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
const KEYPAIR_ALGORITHM_DETAILS: Record<
|
||||
KeypairAlgorithm,
|
||||
@@ -52,168 +53,162 @@ const KEYPAIR_ALGORITHM_DETAILS: Record<
|
||||
},
|
||||
};
|
||||
|
||||
interface AddKeypairButtonProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
export const AddKeypairButton: React.FC<AddKeypairButtonProps> = ({
|
||||
export function AddKeypairButton({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
const [publicKey, setPublicKey] = useState<string>("");
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [publicKey, setPublicKey] = useState("");
|
||||
const [algorithm, setAlgorithm] = useState<KeypairAlgorithm>("ES256");
|
||||
const [label, setLabel] = useState<string>("");
|
||||
const { isOpen, onOpen, onClose } = useDisclosure();
|
||||
const { mutateAsync: importKeypair } = useEngineAddKeypair({
|
||||
const [label, setLabel] = useState("");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const importKeypairMutation = useEngineAddKeypair({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Public key added successfully.",
|
||||
"Failed to add public key.",
|
||||
);
|
||||
|
||||
const onClick = async () => {
|
||||
try {
|
||||
await importKeypair({
|
||||
await importKeypairMutation.mutateAsync({
|
||||
algorithm,
|
||||
label,
|
||||
publicKey,
|
||||
});
|
||||
|
||||
onSuccess();
|
||||
|
||||
toast.success("Public key added successfully.");
|
||||
setPublicKey("");
|
||||
onClose();
|
||||
setIsOpen(false);
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
toast.error("Failed to add public key.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
leftIcon={<CirclePlusIcon className="size-6" />}
|
||||
onClick={onOpen}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
w="fit-content"
|
||||
>
|
||||
Add Public Key
|
||||
<Button className="w-fit gap-2" onClick={() => setIsOpen(true)}>
|
||||
<PlusIcon className="size-4" /> Add Public Key
|
||||
</Button>
|
||||
|
||||
<Modal
|
||||
closeOnEsc={false}
|
||||
closeOnOverlayClick={false}
|
||||
isCentered
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
size="2xl"
|
||||
>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Add Public Key</ModalHeader>
|
||||
<ModalBody as={Flex} flexDir="column" gap={8}>
|
||||
<FormControl>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-row gap-2">
|
||||
<Text>Create a private key using:</Text>
|
||||
<Select
|
||||
color="primary.500"
|
||||
fontFamily="mono"
|
||||
fontSize="small"
|
||||
mt="-1px"
|
||||
onChange={(e) =>
|
||||
setAlgorithm(e.target.value as KeypairAlgorithm)
|
||||
}
|
||||
size="sm"
|
||||
// fontWeight="bold"
|
||||
value={algorithm}
|
||||
variant="unstyled"
|
||||
w="fit-content"
|
||||
>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="!max-w-2xl p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 lg:p-6 border-b border-dashed">
|
||||
<DialogTitle className="text-lg font-semibold">
|
||||
Add Public Key
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6 max-h-[600px] overflow-y-auto px-4 lg:px-6 pb-6 pt-4">
|
||||
{/* instruction */}
|
||||
<div className="space-y-2">
|
||||
{/* create private key */}
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm">Generate a public key</span>
|
||||
<Select
|
||||
value={algorithm}
|
||||
onValueChange={(v) => setAlgorithm(v as KeypairAlgorithm)}
|
||||
>
|
||||
<SelectTrigger className="bg-card">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent id="algorithm">
|
||||
{(
|
||||
Object.keys(
|
||||
KEYPAIR_ALGORITHM_DETAILS,
|
||||
) as KeypairAlgorithm[]
|
||||
).map((key) => (
|
||||
<option key={key} value={key}>
|
||||
<SelectItem key={key} value={key}>
|
||||
{key} ({KEYPAIR_ALGORITHM_DETAILS[key].name})
|
||||
</option>
|
||||
</SelectItem>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<PlainTextCodeBlock
|
||||
code={
|
||||
KEYPAIR_ALGORITHM_DETAILS[algorithm].privateKeyInstructions
|
||||
}
|
||||
<CodeClient
|
||||
lang="bash"
|
||||
code={`\
|
||||
# create private key
|
||||
${KEYPAIR_ALGORITHM_DETAILS[algorithm].privateKeyInstructions}
|
||||
|
||||
# extract public key
|
||||
${KEYPAIR_ALGORITHM_DETAILS[algorithm].publicKeyInstructions}
|
||||
|
||||
# print public key
|
||||
cat public.key
|
||||
`}
|
||||
/>
|
||||
<Text>Extract the public key.</Text>
|
||||
<PlainTextCodeBlock
|
||||
code={
|
||||
KEYPAIR_ALGORITHM_DETAILS[algorithm].publicKeyInstructions
|
||||
}
|
||||
/>
|
||||
<Text>Print the public key.</Text>
|
||||
<PlainTextCodeBlock code="cat public.key" />
|
||||
</div>
|
||||
</FormControl>
|
||||
</div>
|
||||
|
||||
<FormControl isRequired>
|
||||
<FormLabel>
|
||||
Public Key ({KEYPAIR_ALGORITHM_DETAILS[algorithm].name})
|
||||
</FormLabel>
|
||||
{/* public key input */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="text-sm font-medium" htmlFor="publicKey">
|
||||
Public Key ({KEYPAIR_ALGORITHM_DETAILS[algorithm].name}){" "}
|
||||
<span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Textarea
|
||||
fontFamily="mono"
|
||||
fontSize="small"
|
||||
onChange={(e) => setPublicKey(e.target.value)}
|
||||
placeholder="-----BEGIN PUBLIC KEY-----\n...\n...\n...\n...\n-----END PUBLIC KEY-----"
|
||||
id="publicKey"
|
||||
className="font-mono bg-card"
|
||||
rows={6}
|
||||
placeholder={
|
||||
"-----BEGIN PUBLIC KEY-----\n...\n...\n...\n...\n-----END PUBLIC KEY-----"
|
||||
}
|
||||
value={publicKey}
|
||||
onChange={(e) => setPublicKey(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
{/* label */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="text-sm font-medium" htmlFor="key-label">
|
||||
Label
|
||||
</label>
|
||||
<Input
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
id="key-label"
|
||||
placeholder="Enter a description for this keypair"
|
||||
className="bg-card"
|
||||
value={label}
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
|
||||
<Alert variant="left-accent">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Text>
|
||||
<strong>Keep your private key secure!</strong>
|
||||
<br />
|
||||
Your backend will sign access tokens with this private key
|
||||
which Engine verifies with this public key.
|
||||
</Text>
|
||||
</div>
|
||||
{/* alert */}
|
||||
<Alert variant="info">
|
||||
<InfoIcon className="size-5" />
|
||||
<AlertTitle>Keep your private key secure</AlertTitle>
|
||||
<AlertDescription>
|
||||
Your backend will sign access tokens with this private key which
|
||||
Engine verifies with this public key.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</ModalBody>
|
||||
</div>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={onClose} variant="ghost">
|
||||
<div className="flex justify-end gap-3 border-t p-4 lg:p-6 bg-card">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setIsOpen(false)}
|
||||
type="button"
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={!publicKey}
|
||||
disabled={!publicKey}
|
||||
onClick={onClick}
|
||||
type="submit"
|
||||
className="gap-2"
|
||||
>
|
||||
{importKeypairMutation.isPending && (
|
||||
<Spinner className="size-4" />
|
||||
)}
|
||||
Add Public Key
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+60
-64
@@ -1,14 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { ButtonGroup, Flex } from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import { useState } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import {
|
||||
useEngineAccessTokens,
|
||||
useEngineKeypairs,
|
||||
@@ -39,38 +36,28 @@ export const EngineAccessTokens: React.FC<EngineAccessTokensProps> = ({
|
||||
);
|
||||
|
||||
return (
|
||||
<Flex flexDir="column" gap={4}>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Access Tokens</Heading>
|
||||
</Flex>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-1">
|
||||
Access Tokens
|
||||
</h2>
|
||||
|
||||
{supportsKeyPairAuth && (
|
||||
<ButtonGroup size="sm" spacing={2} variant="ghost">
|
||||
<Button
|
||||
_active={{
|
||||
bg: "bgBlack",
|
||||
color: "bgWhite",
|
||||
}}
|
||||
isActive={selected === "standard"}
|
||||
onClick={() => setSelected("standard")}
|
||||
rounded="lg"
|
||||
type="button"
|
||||
>
|
||||
Standard
|
||||
</Button>
|
||||
<Button
|
||||
_active={{
|
||||
bg: "bgBlack",
|
||||
color: "bgWhite",
|
||||
}}
|
||||
isActive={selected === "keypair"}
|
||||
onClick={() => setSelected("keypair")}
|
||||
rounded="lg"
|
||||
type="button"
|
||||
>
|
||||
Keypair Authentication
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
<TabButtons
|
||||
containerClassName="mb-4 mt-3"
|
||||
tabClassName="!text-sm"
|
||||
tabs={[
|
||||
{
|
||||
name: "Standard",
|
||||
onClick: () => setSelected("standard"),
|
||||
isActive: selected === "standard",
|
||||
},
|
||||
{
|
||||
name: "Keypair Authentication",
|
||||
onClick: () => setSelected("keypair"),
|
||||
isActive: selected === "keypair",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
{selected === "standard" ? (
|
||||
@@ -85,7 +72,7 @@ export const EngineAccessTokens: React.FC<EngineAccessTokensProps> = ({
|
||||
instanceUrl={instanceUrl}
|
||||
/>
|
||||
) : null}
|
||||
</Flex>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -104,18 +91,16 @@ const StandardAccessTokensPanel = ({
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Access tokens allow API access to Engine.{" "}
|
||||
<Link
|
||||
color="primary.500"
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/engine/features/access-tokens"
|
||||
isExternal
|
||||
target="_blank"
|
||||
>
|
||||
Learn more about access tokens
|
||||
</Link>
|
||||
.
|
||||
</Text>
|
||||
</UnderlineLink>
|
||||
</p>
|
||||
|
||||
<AccessTokensTable
|
||||
accessTokens={accessTokens.data ?? []}
|
||||
@@ -125,13 +110,20 @@ const StandardAccessTokensPanel = ({
|
||||
isFetched={accessTokens.isFetched}
|
||||
isPending={accessTokens.isPending}
|
||||
/>
|
||||
<AddAccessTokenButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
|
||||
<Flex direction="column" gap={2} mt={16}>
|
||||
<Heading size="title.md">Authenticate with your access token</Heading>
|
||||
<Text>
|
||||
Set the <InlineCode code="authorization" /> header.
|
||||
</Text>
|
||||
<div className="flex justify-end mt-4">
|
||||
<AddAccessTokenButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
</div>
|
||||
|
||||
<div className="mt-16">
|
||||
<div className="mb-3">
|
||||
<h3 className="text-lg font-semibold mb-1">
|
||||
Authenticate with your access token
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Set the <InlineCode code="authorization" /> header.
|
||||
</p>
|
||||
</div>
|
||||
<CodeClient
|
||||
code={`const resp = fetch("<engine_url>/backend-wallet/get-all", {
|
||||
headers: {
|
||||
@@ -140,8 +132,8 @@ const StandardAccessTokensPanel = ({
|
||||
});`}
|
||||
lang="ts"
|
||||
/>
|
||||
</Flex>
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -159,20 +151,19 @@ const KeypairAuthenticationPanel = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<Text>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Keypair authentication allows your app to generate short-lived access
|
||||
tokens.
|
||||
<br />
|
||||
They are securely signed by your backend and verified with a public key.{" "}
|
||||
<Link
|
||||
color="primary.500"
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/engine/features/keypair-authentication"
|
||||
isExternal
|
||||
target="_blank"
|
||||
>
|
||||
Learn more about keypair authentication
|
||||
</Link>
|
||||
</UnderlineLink>
|
||||
.
|
||||
</Text>
|
||||
</p>
|
||||
|
||||
<KeypairsTable
|
||||
authToken={authToken}
|
||||
@@ -181,14 +172,19 @@ const KeypairAuthenticationPanel = ({
|
||||
isPending={keypairs.isPending}
|
||||
keypairs={keypairs.data || []}
|
||||
/>
|
||||
<AddKeypairButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
|
||||
<Flex direction="column" gap={2} mt={16}>
|
||||
<Heading size="title.md">Authenticate with your access token</Heading>
|
||||
<div className="flex justify-end mt-4">
|
||||
<AddKeypairButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
</div>
|
||||
|
||||
<Text>
|
||||
<div className="flex flex-col gap-2 mt-16">
|
||||
<h3 className="text-lg font-medium">
|
||||
Authenticate with your access token
|
||||
</h3>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Set the <InlineCode code="authorization" /> header.
|
||||
</Text>
|
||||
</p>
|
||||
<CodeClient
|
||||
code={`import jsonwebtoken from "jsonwebtoken";
|
||||
|
||||
@@ -209,7 +205,7 @@ const resp = fetch("<engine_url>/backend-wallet/get-all", {
|
||||
});`}
|
||||
lang="ts"
|
||||
/>
|
||||
</Flex>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
+74
-88
@@ -1,43 +1,29 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
type UseDisclosureReturn,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { TWTable } from "@/components/blocks/TWTable";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyAddressButton } from "@/components/ui/CopyAddressButton";
|
||||
import { PlainTextCodeBlock } from "@/components/ui/code/plaintext-code";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { type Keypair, useEngineRemoveKeypair } from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { toDateTimeLocal } from "@/utils/date-utils";
|
||||
|
||||
interface KeypairsTableProps {
|
||||
instanceUrl: string;
|
||||
keypairs: Keypair[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
}
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
const columnHelper = createColumnHelper<Keypair>();
|
||||
|
||||
const columns = [
|
||||
columnHelper.accessor("label", {
|
||||
cell: (cell) => {
|
||||
return <Text>{cell.getValue()}</Text>;
|
||||
return <span>{cell.getValue()}</span>;
|
||||
},
|
||||
header: "Label",
|
||||
}),
|
||||
@@ -63,26 +49,32 @@ const columns = [
|
||||
}),
|
||||
columnHelper.accessor("algorithm", {
|
||||
cell: (cell) => {
|
||||
return <Text>{cell.getValue()}</Text>;
|
||||
return <span>{cell.getValue()}</span>;
|
||||
},
|
||||
header: "Type",
|
||||
}),
|
||||
columnHelper.accessor("createdAt", {
|
||||
cell: (cell) => {
|
||||
return <Text>{toDateTimeLocal(cell.getValue())}</Text>;
|
||||
return <span>{toDateTimeLocal(cell.getValue())}</span>;
|
||||
},
|
||||
header: "Added At",
|
||||
}),
|
||||
];
|
||||
|
||||
export const KeypairsTable: React.FC<KeypairsTableProps> = ({
|
||||
export function KeypairsTable({
|
||||
instanceUrl,
|
||||
keypairs,
|
||||
isPending,
|
||||
isFetched,
|
||||
authToken,
|
||||
}) => {
|
||||
const removeDisclosure = useDisclosure();
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
keypairs: Keypair[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [isRemoveDialogOpen, setIsRemoveDialogOpen] = useState(false);
|
||||
const [selectedKeypair, setSelectedKeypair] = useState<Keypair>();
|
||||
|
||||
return (
|
||||
@@ -98,7 +90,7 @@ export const KeypairsTable: React.FC<KeypairsTableProps> = ({
|
||||
isDestructive: true,
|
||||
onClick: (keypair) => {
|
||||
setSelectedKeypair(keypair);
|
||||
removeDisclosure.onOpen();
|
||||
setIsRemoveDialogOpen(true);
|
||||
},
|
||||
text: "Remove",
|
||||
},
|
||||
@@ -106,99 +98,93 @@ export const KeypairsTable: React.FC<KeypairsTableProps> = ({
|
||||
title="public keys"
|
||||
/>
|
||||
|
||||
{selectedKeypair && removeDisclosure.isOpen && (
|
||||
<RemoveModal
|
||||
{selectedKeypair && (
|
||||
<RemoveDialog
|
||||
authToken={authToken}
|
||||
disclosure={removeDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
keypair={selectedKeypair}
|
||||
isOpen={isRemoveDialogOpen}
|
||||
onOpenChange={setIsRemoveDialogOpen}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const RemoveModal = ({
|
||||
function RemoveDialog({
|
||||
keypair,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
}: {
|
||||
keypair: Keypair;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) => {
|
||||
const { mutate: revokeKeypair } = useEngineRemoveKeypair({
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const removeKeypairMutation = useEngineRemoveKeypair({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully removed public key",
|
||||
"Failed to remove public key",
|
||||
);
|
||||
|
||||
const onClick = () => {
|
||||
revokeKeypair(
|
||||
removeKeypairMutation.mutate(
|
||||
{ hash: keypair.hash },
|
||||
{
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to remove public key.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
disclosure.onClose();
|
||||
toast.success("Public key removed successfully.");
|
||||
onOpenChange(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Remove Keypair</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Text>Are you sure you want to remove this keypair?</Text>
|
||||
<Text>
|
||||
Access tokens signed by the private key for this keypair will no
|
||||
longer be valid.
|
||||
</Text>
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6 border-b border-dashed">
|
||||
<DialogTitle>Remove Keypair</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to remove this keypair? Access tokens signed
|
||||
by the private key for this keypair will no longer be valid.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Text>{keypair.label}</Text>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel>Type</FormLabel>
|
||||
<Text>{keypair.algorithm}</Text>
|
||||
</FormControl>
|
||||
|
||||
<FormControl>
|
||||
<FormLabel>Public Key</FormLabel>
|
||||
<Flex overflowX="scroll">
|
||||
<Text fontFamily="mono" fontSize="small" whiteSpace="pre-line">
|
||||
{keypair.publicKey}
|
||||
</Text>
|
||||
</Flex>
|
||||
</FormControl>
|
||||
<div className="flex flex-col gap-4 overflow-hidden px-4 lg:px-6 pb-8 pt-6">
|
||||
<div className="space-y-1.">
|
||||
<h3 className="text-sm font-medium">Label</h3>
|
||||
<p className="text-sm text-muted-foreground">{keypair.label}</p>
|
||||
</div>
|
||||
</ModalBody>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} type="button" variant="ghost">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">Type</h3>
|
||||
<p className="text-sm text-muted-foreground">{keypair.algorithm}</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">Public Key</h3>
|
||||
<PlainTextCodeBlock code={keypair.publicKey} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 p-4 lg:p-6 bg-card border-t">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="red" onClick={onClick} type="submit">
|
||||
<Button variant="destructive" onClick={onClick} className="gap-2">
|
||||
{removeKeypairMutation.isPending && <Spinner className="size-4" />}
|
||||
Remove
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+139
-100
@@ -1,116 +1,155 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { CirclePlusIcon } from "lucide-react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { isAddress } from "thirdweb";
|
||||
import { type EngineAdmin, useEngineGrantPermissions } from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { z } from "zod";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { useEngineGrantPermissions } from "@/hooks/useEngine";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface AddAdminButtonProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
const addAdminSchema = z.object({
|
||||
walletAddress: z
|
||||
.string()
|
||||
.refine((address) => isAddress(address), "Invalid address"),
|
||||
label: z.string().optional(),
|
||||
});
|
||||
|
||||
export const AddAdminButton: React.FC<AddAdminButtonProps> = ({
|
||||
type AddAdminFormData = z.infer<typeof addAdminSchema>;
|
||||
|
||||
export function AddAdminButton({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
const { isOpen, onOpen, onClose } = useDisclosure();
|
||||
const { mutate: grantPermissions } = useEngineGrantPermissions({
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const grantPermissionsMutation = useEngineGrantPermissions({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const form = useForm<EngineAdmin>({
|
||||
defaultValues: {
|
||||
permissions: "ADMIN",
|
||||
},
|
||||
const form = useForm<AddAdminFormData>({
|
||||
resolver: zodResolver(addAdminSchema),
|
||||
defaultValues: {},
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully added admin.",
|
||||
"Failed to add admin.",
|
||||
);
|
||||
const onSubmit = (data: AddAdminFormData) => {
|
||||
grantPermissionsMutation.mutate(
|
||||
{
|
||||
...data,
|
||||
permissions: "ADMIN",
|
||||
},
|
||||
{
|
||||
onError: (error) => {
|
||||
toast.error("Failed to add admin.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("Admin added successfully.");
|
||||
setOpen(false);
|
||||
form.reset();
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
leftIcon={<CirclePlusIcon className="size-6" />}
|
||||
onClick={onOpen}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
w="fit-content"
|
||||
>
|
||||
Add Admin
|
||||
</Button>
|
||||
<Modal isCentered isOpen={isOpen} onClose={onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent
|
||||
as="form"
|
||||
className="!bg-background rounded-lg border border-border"
|
||||
onSubmit={form.handleSubmit((data) => {
|
||||
if (!isAddress(data.walletAddress)) {
|
||||
onError(new Error("Invalid wallet address"));
|
||||
}
|
||||
grantPermissions(data, {
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
})}
|
||||
>
|
||||
<ModalHeader>Add Admin</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Wallet Address</FormLabel>
|
||||
<Input
|
||||
placeholder="The wallet address for this admin"
|
||||
type="text"
|
||||
{...form.register("walletAddress", { required: true })}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Input
|
||||
placeholder="Enter a description for this admin"
|
||||
type="text"
|
||||
{...form.register("label")}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="w-fit gap-2">
|
||||
<PlusIcon className="size-4" />
|
||||
Add Admin
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Add Admin</DialogTitle>
|
||||
<DialogDescription>
|
||||
Add a new admin to your engine instance.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={onClose} type="button" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="primary" type="submit">
|
||||
Add
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="space-y-4 px-4 lg:px-6 pb-8">
|
||||
{/* wallet address */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="walletAddress"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Wallet Address</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="0x..."
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{/* label */}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="label"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="label for this admin"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-end gap-3 p-4 lg:p-6 bg-card border-t">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" className="gap-2">
|
||||
{grantPermissionsMutation.isPending && (
|
||||
<Spinner className="size-4" />
|
||||
)}
|
||||
Add Admin
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+186
-133
@@ -1,55 +1,64 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
type UseDisclosureReturn,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { PencilIcon, Trash2Icon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { z } from "zod";
|
||||
import { TWTable } from "@/components/blocks/TWTable";
|
||||
import { WalletAddress } from "@/components/blocks/wallet-address";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import {
|
||||
type EngineAdmin,
|
||||
useEngineGrantPermissions,
|
||||
useEngineRevokePermissions,
|
||||
} from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
|
||||
interface AdminsTableProps {
|
||||
instanceUrl: string;
|
||||
admins: EngineAdmin[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
const columnHelper = createColumnHelper<EngineAdmin>();
|
||||
|
||||
export const AdminsTable: React.FC<AdminsTableProps> = ({
|
||||
const editAdminSchema = z.object({
|
||||
label: z.string().optional(),
|
||||
});
|
||||
|
||||
type EditAdminFormData = z.infer<typeof editAdminSchema>;
|
||||
|
||||
export function AdminsTable({
|
||||
instanceUrl,
|
||||
admins,
|
||||
isPending,
|
||||
isFetched,
|
||||
authToken,
|
||||
client,
|
||||
}) => {
|
||||
const editDisclosure = useDisclosure();
|
||||
const removeDisclosure = useDisclosure();
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
admins: EngineAdmin[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [removeOpen, setRemoveOpen] = useState(false);
|
||||
const [selectedAdmin, setSelectedAdmin] = useState<EngineAdmin>();
|
||||
|
||||
const columns = useMemo(() => {
|
||||
@@ -63,11 +72,7 @@ export const AdminsTable: React.FC<AdminsTableProps> = ({
|
||||
}),
|
||||
columnHelper.accessor("label", {
|
||||
cell: (cell) => {
|
||||
return (
|
||||
<Text isTruncated maxW={300}>
|
||||
{cell.getValue()}
|
||||
</Text>
|
||||
);
|
||||
return <p className="truncate max-w-[300px]">{cell.getValue()}</p>;
|
||||
},
|
||||
header: "Label",
|
||||
}),
|
||||
@@ -92,7 +97,7 @@ export const AdminsTable: React.FC<AdminsTableProps> = ({
|
||||
icon: <PencilIcon className="size-4" />,
|
||||
onClick: (admin) => {
|
||||
setSelectedAdmin(admin);
|
||||
editDisclosure.onOpen();
|
||||
setEditOpen(true);
|
||||
},
|
||||
text: "Edit",
|
||||
},
|
||||
@@ -101,7 +106,7 @@ export const AdminsTable: React.FC<AdminsTableProps> = ({
|
||||
isDestructive: true,
|
||||
onClick: (admin) => {
|
||||
setSelectedAdmin(admin);
|
||||
removeDisclosure.onOpen();
|
||||
setRemoveOpen(true);
|
||||
},
|
||||
text: "Remove",
|
||||
},
|
||||
@@ -109,174 +114,222 @@ export const AdminsTable: React.FC<AdminsTableProps> = ({
|
||||
title="admins"
|
||||
/>
|
||||
|
||||
{selectedAdmin && editDisclosure.isOpen && (
|
||||
<EditModal
|
||||
{selectedAdmin && (
|
||||
<EditDialog
|
||||
admin={selectedAdmin}
|
||||
authToken={authToken}
|
||||
disclosure={editDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
/>
|
||||
)}
|
||||
{selectedAdmin && removeDisclosure.isOpen && (
|
||||
<RemoveModal
|
||||
{selectedAdmin && (
|
||||
<RemoveDialog
|
||||
admin={selectedAdmin}
|
||||
authToken={authToken}
|
||||
disclosure={removeDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
open={removeOpen}
|
||||
onOpenChange={setRemoveOpen}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const EditModal = ({
|
||||
function EditDialog({
|
||||
admin,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
admin: EngineAdmin;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) => {
|
||||
const { mutate: updatePermissions } = useEngineGrantPermissions({
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const updatePermissionsMutation = useEngineGrantPermissions({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully updated admin",
|
||||
"Failed to update admin",
|
||||
);
|
||||
const form = useForm<EditAdminFormData>({
|
||||
resolver: zodResolver(editAdminSchema),
|
||||
values: {
|
||||
label: admin.label ?? "",
|
||||
},
|
||||
});
|
||||
|
||||
const [label, setLabel] = useState(admin.label ?? "");
|
||||
|
||||
const onClick = () => {
|
||||
updatePermissions(
|
||||
const onSubmit = (data: EditAdminFormData) => {
|
||||
updatePermissionsMutation.mutate(
|
||||
{
|
||||
label,
|
||||
label: data.label,
|
||||
permissions: admin.permissions,
|
||||
walletAddress: admin.walletAddress,
|
||||
},
|
||||
{
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to update admin.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
disclosure.onClose();
|
||||
toast.success("Admin updated successfully.");
|
||||
onOpenChange(false);
|
||||
form.reset();
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Update Admin</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<FormControl>
|
||||
<FormLabel>Wallet Address</FormLabel>
|
||||
<Text>{admin.walletAddress}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Input
|
||||
onChange={(e) => setLabel(e.target.value)}
|
||||
placeholder="Enter a description for this admin"
|
||||
type="text"
|
||||
value={label}
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Update Admin</DialogTitle>
|
||||
<DialogDescription>
|
||||
Update the label for this admin.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="space-y-4 px-4 lg:px-6 pb-8">
|
||||
<div className="space-y-1.5">
|
||||
<h3 className="text-sm font-medium">Wallet Address</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{admin.walletAddress}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="label"
|
||||
render={({ field }) => (
|
||||
<FormItem className="space-y-1.5">
|
||||
<FormLabel>Label</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="Enter a description for this admin"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
</div>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} type="button" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="blue" onClick={onClick} type="submit">
|
||||
Save
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
<div className="flex justify-end gap-3 p-4 lg:p-6 bg-card border-t">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" className="gap-2">
|
||||
{updatePermissionsMutation.isPending && (
|
||||
<Spinner className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const RemoveModal = ({
|
||||
function RemoveDialog({
|
||||
admin,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
admin: EngineAdmin;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) => {
|
||||
const { mutate: revokePermissions } = useEngineRevokePermissions({
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const revokePermissionsMutation = useEngineRevokePermissions({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Successfully removed admin",
|
||||
"Failed to remove admin",
|
||||
);
|
||||
|
||||
const onClick = () => {
|
||||
revokePermissions(
|
||||
revokePermissionsMutation.mutate(
|
||||
{
|
||||
walletAddress: admin.walletAddress,
|
||||
},
|
||||
{
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
toast.error("Failed to remove admin.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
disclosure.onClose();
|
||||
toast.success("Admin removed successfully.");
|
||||
onOpenChange(false);
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Remove Admin</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Text>Are you sure you want to remove this admin?</Text>
|
||||
<FormControl>
|
||||
<FormLabel>Wallet Address</FormLabel>
|
||||
<Text>{admin.walletAddress}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Label</FormLabel>
|
||||
<Text>{admin.label ?? <em>N/A</em>}</Text>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden gap-0">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Remove Admin</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to remove this admin?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} type="button" variant="ghost">
|
||||
<div className="space-y-5 px-4 lg:px-6 pb-8">
|
||||
<div className="space-y-1.5">
|
||||
<h3 className="text-sm font-medium">Wallet Address</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{admin.walletAddress}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<h3 className="text-sm font-medium">Label</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{admin.label ?? <em>N/A</em>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 p-4 lg:p-6 bg-card border-t">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="red" onClick={onClick} type="submit">
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
onClick={onClick}
|
||||
className="gap-2"
|
||||
>
|
||||
{revokePermissionsMutation.isPending && (
|
||||
<Spinner className="size-4" />
|
||||
)}
|
||||
Remove
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+26
-28
@@ -1,45 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { useEnginePermissions } from "@/hooks/useEngine";
|
||||
import { AddAdminButton } from "./add-admin-button";
|
||||
import { AdminsTable } from "./admins-table";
|
||||
|
||||
interface EngineAdminsProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
client: ThirdwebClient;
|
||||
}
|
||||
|
||||
export const EngineAdmins: React.FC<EngineAdminsProps> = ({
|
||||
export function EngineAdmins({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
client,
|
||||
}) => {
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const admins = useEnginePermissions({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="title.md">Admins</Heading>
|
||||
<Text>
|
||||
Admins are allowed to manage your Engine instance from the dashboard.{" "}
|
||||
<Link
|
||||
color="primary.500"
|
||||
href="https://portal.thirdweb.com/engine/features/admins"
|
||||
isExternal
|
||||
>
|
||||
Learn more about admins
|
||||
</Link>
|
||||
.
|
||||
</Text>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-1">Admins</h2>
|
||||
<p className="text-muted-foreground text-sm mb-5">
|
||||
Admins are allowed to manage your Engine instance from the dashboard.{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/engine/features/admins"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Learn more about admins
|
||||
</UnderlineLink>
|
||||
.
|
||||
</p>
|
||||
|
||||
<AdminsTable
|
||||
admins={admins.data || []}
|
||||
authToken={authToken}
|
||||
@@ -48,7 +43,10 @@ export const EngineAdmins: React.FC<EngineAdminsProps> = ({
|
||||
isFetched={admins.isFetched}
|
||||
isPending={admins.isPending}
|
||||
/>
|
||||
<AddAdminButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
|
||||
<div className="mt-4 flex justify-end">
|
||||
<AddAdminButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+52
-45
@@ -1,4 +1,4 @@
|
||||
import Link from "next/link";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useId } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Form } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import {
|
||||
type EngineInstance,
|
||||
type SetWalletConfigInput,
|
||||
@@ -58,55 +59,61 @@ export const CircleConfig: React.FC<CircleConfigProps> = ({
|
||||
const circleApiKeyId = useId();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-muted-foreground">
|
||||
Circle wallets require an API Key from your Circle account with
|
||||
sufficient permissions. Created wallets are stored in your AWS
|
||||
account. Configure your Circle API Key to use Circle wallets. Learn
|
||||
more about{" "}
|
||||
<Link
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
href="https://portal.thirdweb.com/engine/features/backend-wallets#circle-wallet"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
how to get an API Key
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-card rounded-lg border mb-8">
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("circleApiKey", form.formState).error?.message
|
||||
}
|
||||
htmlFor={circleApiKeyId}
|
||||
isRequired
|
||||
label="Circle API Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={circleApiKeyId}
|
||||
placeholder="TEST_API_KEY:..."
|
||||
type="password"
|
||||
{...form.register("circleApiKey")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="p-4 lg:p-6">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-lg font-semibold mb-1">Credentials</h2>
|
||||
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Circle wallets require an API Key from your Circle account with
|
||||
sufficient permissions. <br /> Created wallets are stored in
|
||||
your AWS account. Configure your Circle API Key to use Circle
|
||||
wallets. Learn more about{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/engine/features/backend-wallets#circle-wallet"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
how to get an API Key
|
||||
</UnderlineLink>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("circleApiKey", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={circleApiKeyId}
|
||||
isRequired
|
||||
label="Circle API Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={circleApiKeyId}
|
||||
placeholder="TEST_API_KEY:..."
|
||||
type="password"
|
||||
{...form.register("circleApiKey")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-4 border-t border-dashed px-4 py-4 lg:px-6">
|
||||
<Button
|
||||
className="min-w-28 gap-2"
|
||||
disabled={isPending}
|
||||
className="gap-2"
|
||||
disabled={isPending || !form.formState.isDirty}
|
||||
size="sm"
|
||||
type="submit"
|
||||
>
|
||||
{isPending && <Spinner className="size-4" />}
|
||||
{isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
+51
-52
@@ -1,42 +1,36 @@
|
||||
import { Flex, Textarea } from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
useEngineCorsConfiguration,
|
||||
useEngineSetCorsConfiguration,
|
||||
} from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface EngineCorsConfigProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
interface CorsForm {
|
||||
type CorsForm = {
|
||||
raw: string;
|
||||
}
|
||||
};
|
||||
|
||||
export const EngineCorsConfig: React.FC<EngineCorsConfigProps> = ({
|
||||
export function EngineCorsConfig({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const { data: existingUrls } = useEngineCorsConfiguration({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
const { mutateAsync: setCorsConfig } = useEngineSetCorsConfiguration({
|
||||
const setCorsConfigMutation = useEngineSetCorsConfiguration({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"CORS URLs updated successfully.",
|
||||
"Failed to update CORS URLs.",
|
||||
);
|
||||
|
||||
const form = useForm<CorsForm>({
|
||||
values: { raw: existingUrls?.join("\n") ?? "" },
|
||||
});
|
||||
@@ -47,52 +41,57 @@ export const EngineCorsConfig: React.FC<EngineCorsConfigProps> = ({
|
||||
// Assert all URLs are well formed and strip the path.
|
||||
const sanitized = urls.map(parseOriginFromUrl);
|
||||
|
||||
await setCorsConfig({ urls: sanitized });
|
||||
onSuccess();
|
||||
await setCorsConfigMutation.mutateAsync({ urls: sanitized });
|
||||
toast.success("CORS URLs updated successfully.");
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
toast.error("Failed to update CORS URLs.", {
|
||||
description: parseError(error),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Flex
|
||||
as="form"
|
||||
flexDir="column"
|
||||
gap={4}
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Allowlisted Domains</Heading>
|
||||
<Text>
|
||||
<div className="bg-card rounded-lg border">
|
||||
<div className="px-4 lg:px-6 pt-4 lg:pt-6">
|
||||
<h2 className="text-lg font-semibold mb-1">Allowlisted Domains</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Specify the origins that can call Engine (
|
||||
<InlineCode code="https://example.com" />
|
||||
).
|
||||
<br />
|
||||
Enter one origin per line, or leave this list empty to disallow calls
|
||||
from web clients.
|
||||
</Text>
|
||||
</Flex>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
placeholder={"https://example.com\nhttp://localhost:3000"}
|
||||
rows={4}
|
||||
{...form.register("raw")}
|
||||
/>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="p-4 lg:px-6">
|
||||
<Textarea
|
||||
placeholder={"https://example.com\nhttp://localhost:3000"}
|
||||
rows={4}
|
||||
{...form.register("raw")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Flex alignItems="center" gap={4} justifyContent="end">
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={!form.formState.isDirty}
|
||||
px={12}
|
||||
type="submit"
|
||||
w={{ base: "full", md: "inherit" }}
|
||||
>
|
||||
{form.formState.isSubmitting ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div className="flex justify-end border-t border-dashed px-4 py-4 lg:px-6">
|
||||
<Button
|
||||
className="gap-2"
|
||||
size="sm"
|
||||
type="submit"
|
||||
disabled={!form.formState.isDirty || form.formState.isSubmitting}
|
||||
>
|
||||
{setCorsConfigMutation.isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
const parseOriginFromUrl = (url: string) => {
|
||||
try {
|
||||
|
||||
+13
-11
@@ -20,23 +20,25 @@ export const EngineConfiguration: React.FC<EngineConfigurationProps> = ({
|
||||
authToken,
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-col gap-12">
|
||||
<div>
|
||||
<EngineWalletConfig
|
||||
authToken={authToken}
|
||||
instance={instance}
|
||||
projectSlug={projectSlug}
|
||||
teamSlug={teamSlug}
|
||||
/>
|
||||
<EngineCorsConfig authToken={authToken} instanceUrl={instance.url} />
|
||||
<EngineIpAllowlistConfig
|
||||
authToken={authToken}
|
||||
instanceUrl={instance.url}
|
||||
/>
|
||||
<EngineSystem
|
||||
instance={instance}
|
||||
projectSlug={projectSlug}
|
||||
teamIdOrSlug={teamSlug}
|
||||
/>
|
||||
<div className="space-y-8">
|
||||
<EngineCorsConfig authToken={authToken} instanceUrl={instance.url} />
|
||||
<EngineIpAllowlistConfig
|
||||
authToken={authToken}
|
||||
instanceUrl={instance.url}
|
||||
/>
|
||||
<EngineSystem
|
||||
instance={instance}
|
||||
projectSlug={projectSlug}
|
||||
teamIdOrSlug={teamSlug}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+30
-30
@@ -1,10 +1,9 @@
|
||||
import { Heading } from "chakra/heading";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { TabButtons } from "@/components/ui/tabs";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import {
|
||||
EngineBackendWalletOptions,
|
||||
type EngineBackendWalletType,
|
||||
@@ -20,19 +19,17 @@ import { KmsAwsConfig } from "./kms-aws-config";
|
||||
import { KmsGcpConfig } from "./kms-gcp-config";
|
||||
import { LocalConfig } from "./local-config";
|
||||
|
||||
interface EngineWalletConfigProps {
|
||||
instance: EngineInstance;
|
||||
teamSlug: string;
|
||||
projectSlug: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
export const EngineWalletConfig: React.FC<EngineWalletConfigProps> = ({
|
||||
export function EngineWalletConfig({
|
||||
instance,
|
||||
teamSlug,
|
||||
projectSlug,
|
||||
authToken,
|
||||
}) => {
|
||||
}: {
|
||||
instance: EngineInstance;
|
||||
teamSlug: string;
|
||||
projectSlug: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const { data: walletConfig } = useEngineWalletConfig({
|
||||
authToken,
|
||||
instanceUrl: instance.url,
|
||||
@@ -68,17 +65,18 @@ export const EngineWalletConfig: React.FC<EngineWalletConfigProps> = ({
|
||||
const isGcpKmsConfigured = !!walletConfig?.gcpKmsKeyRingId;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="title.md">Backend Wallets</Heading>
|
||||
<p className="text-muted-foreground">
|
||||
<div>
|
||||
<div className="mb-4">
|
||||
<h2 className="text-2xl font-semibold tracking-tight mb-1">
|
||||
Backend Wallets
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Create backend wallets on the{" "}
|
||||
<Link
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
<UnderlineLink
|
||||
href={`/team/${teamSlug}/${projectSlug}/engine/dedicated/${instance.id}`}
|
||||
>
|
||||
Overview
|
||||
</Link>{" "}
|
||||
</UnderlineLink>{" "}
|
||||
tab. To use other wallet types, configure them below.
|
||||
</p>
|
||||
</div>
|
||||
@@ -102,18 +100,20 @@ export const EngineWalletConfig: React.FC<EngineWalletConfigProps> = ({
|
||||
}))}
|
||||
/>
|
||||
|
||||
{!isWalletCredentialsSupported && activeTab === "circle" && (
|
||||
<Alert className="mt-4" variant="warning">
|
||||
<CircleAlertIcon className="size-4" />
|
||||
<AlertTitle>Update Required</AlertTitle>
|
||||
<AlertDescription>
|
||||
Circle wallet support requires a newer version of Engine. Please
|
||||
update your Engine instance to use this feature.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="mt-4 space-y-4">
|
||||
{!isWalletCredentialsSupported && activeTab === "circle" && (
|
||||
<Alert className="mt-4" variant="warning">
|
||||
<CircleAlertIcon className="size-4" />
|
||||
<AlertTitle>Update Required</AlertTitle>
|
||||
<AlertDescription>
|
||||
Circle wallet support requires a newer version of Engine. Please
|
||||
update your Engine instance to use this feature.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{tabContent[activeTab]}
|
||||
{tabContent[activeTab]}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+59
-60
@@ -1,42 +1,38 @@
|
||||
import { Flex, Textarea } from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Text } from "chakra/text";
|
||||
import { isValid } from "ipaddr.js";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { InlineCode } from "@/components/ui/inline-code";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
useEngineIpAllowlistConfiguration,
|
||||
useEngineSetIpAllowlistConfiguration,
|
||||
useHasEngineFeature,
|
||||
} from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
|
||||
interface EngineIpAllowlistConfigProps {
|
||||
type IpForm = {
|
||||
raw: string;
|
||||
};
|
||||
|
||||
export function EngineIpAllowlistConfig({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
interface IpForm {
|
||||
raw: string;
|
||||
}
|
||||
|
||||
export const EngineIpAllowlistConfig: React.FC<
|
||||
EngineIpAllowlistConfigProps
|
||||
> = ({ instanceUrl, authToken }) => {
|
||||
}) {
|
||||
const { data: existingIpAllowlist } = useEngineIpAllowlistConfiguration({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
const { mutateAsync: setIpAllowlist } = useEngineSetIpAllowlistConfiguration({
|
||||
const setIpAllowlistMutation = useEngineSetIpAllowlistConfiguration({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"IP Allowlist updated successfully.",
|
||||
"Failed to update IP Allowlist",
|
||||
);
|
||||
const { isSupported } = useHasEngineFeature(instanceUrl, "IP_ALLOWLIST");
|
||||
|
||||
const form = useForm<IpForm>({
|
||||
@@ -57,13 +53,15 @@ export const EngineIpAllowlistConfig: React.FC<
|
||||
throw new Error(`Invalid IP Address: ${incorrectIp}`);
|
||||
}
|
||||
|
||||
await setIpAllowlist({ ips });
|
||||
await setIpAllowlistMutation.mutateAsync({ ips });
|
||||
toast.success("IP Allowlist updated successfully.");
|
||||
form.reset({
|
||||
raw: ips.join("\n"),
|
||||
});
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
onError(error);
|
||||
toast.error("Failed to update IP Allowlist", {
|
||||
description: parseError(error),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -72,43 +70,44 @@ export const EngineIpAllowlistConfig: React.FC<
|
||||
}
|
||||
|
||||
return (
|
||||
<Flex
|
||||
as="form"
|
||||
flexDir="column"
|
||||
gap={4}
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<Flex flexDir="column" gap={2}>
|
||||
<Heading size="title.md">Allowlist IPs</Heading>
|
||||
<Text>
|
||||
Specify the IP Addresses that can call Engine (
|
||||
<InlineCode code="8.8.8.8" />
|
||||
).
|
||||
<br />
|
||||
Enter a comma separated list of IPs, or one IP per line, or leave this
|
||||
list empty to allow all IPs.
|
||||
<br />
|
||||
This does not affect Dashboard calls to Engine.
|
||||
</Text>
|
||||
</Flex>
|
||||
<div className="bg-card rounded-lg border">
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="p-4 lg:p-6 lg:pb-4">
|
||||
<h2 className="text-lg font-semibold mb-1">Allowlist IPs</h2>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
Specify the IP Addresses that can call Engine (
|
||||
<InlineCode code="8.8.8.8" />
|
||||
).
|
||||
<br />
|
||||
Enter a comma separated list of IPs, or one IP per line, or leave
|
||||
this list empty to allow all IPs.
|
||||
<br />
|
||||
This does not affect Dashboard calls to Engine.
|
||||
</p>
|
||||
|
||||
<Textarea
|
||||
placeholder={"8.8.8.8\nff06:0:0:0:0:0:0:c3"}
|
||||
rows={4}
|
||||
{...form.register("raw")}
|
||||
/>
|
||||
<Textarea
|
||||
placeholder={"8.8.8.8\nff06:0:0:0:0:0:0:c3"}
|
||||
rows={4}
|
||||
{...form.register("raw")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Flex alignItems="center" gap={4} justifyContent="end">
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
isDisabled={!form.formState.isDirty}
|
||||
px={12}
|
||||
type="submit"
|
||||
w={{ base: "full", md: "inherit" }}
|
||||
>
|
||||
{form.formState.isSubmitting ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div className="flex justify-end border-t border-dashed px-4 py-4 lg:px-6">
|
||||
<Button
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
disabled={!form.formState.isDirty}
|
||||
type="submit"
|
||||
>
|
||||
{form.formState.isSubmitting ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+109
-94
@@ -1,4 +1,4 @@
|
||||
import Link from "next/link";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useId } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Form, FormDescription } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import {
|
||||
type EngineInstance,
|
||||
type SetWalletConfigInput,
|
||||
@@ -74,102 +75,116 @@ export const KmsAwsConfig: React.FC<KmsAwsConfigProps> = ({
|
||||
const awsSecretKeyId = useId();
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<p className="text-muted-foreground">
|
||||
AWS KMS wallets require credentials from your Amazon Web Services
|
||||
account with sufficient permissions to manage KMS keys. Wallets are
|
||||
stored in KMS keys on your AWS account.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
For help and more advanced use cases,{" "}
|
||||
<Link
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/backend-wallets"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
learn more about using AWS KMS wallets
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<div className="bg-card rounded-lg border mb-8">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="p-4 lg:p-6 ">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-lg font-semibold mb-1">Credentials</h2>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsRegion", form.formState).error?.message
|
||||
}
|
||||
htmlFor="aws-region"
|
||||
isRequired
|
||||
label="Region"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsRegionId}
|
||||
placeholder="us-west-2"
|
||||
type="text"
|
||||
{...form.register("awsRegion")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<p className="text-muted-foreground mb-1 text-sm">
|
||||
AWS KMS wallets require credentials from your Amazon Web
|
||||
Services account with sufficient permissions to manage KMS keys.{" "}
|
||||
<br />
|
||||
Wallets are stored in KMS keys on your AWS account.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
For help and more advanced use cases,{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/backend-wallets"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
learn more about using AWS KMS wallets
|
||||
</UnderlineLink>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsAccessKeyId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={awsAccessKeyId}
|
||||
isRequired
|
||||
label="Access Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsAccessKeyId}
|
||||
placeholder="AKIA..."
|
||||
type="text"
|
||||
{...form.register("awsAccessKeyId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<div className="space-y-4">
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsRegion", form.formState).error?.message
|
||||
}
|
||||
htmlFor="aws-region"
|
||||
isRequired
|
||||
label="Region"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsRegionId}
|
||||
placeholder="us-west-2"
|
||||
type="text"
|
||||
{...form.register("awsRegion")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsSecretAccessKey", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={awsSecretKeyId}
|
||||
isRequired
|
||||
label="Secret Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsSecretKeyId}
|
||||
placeholder="UW7A..."
|
||||
type="text"
|
||||
{...form.register("awsSecretAccessKey")}
|
||||
/>
|
||||
<FormDescription className="pt-2">
|
||||
This will not be shown again.
|
||||
</FormDescription>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsAccessKeyId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={awsAccessKeyId}
|
||||
isRequired
|
||||
label="Access Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsAccessKeyId}
|
||||
placeholder="AKIA..."
|
||||
type="text"
|
||||
{...form.register("awsAccessKeyId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
{!supportsMultipleWalletTypes && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
This will clear other credentials.
|
||||
</p>
|
||||
)}
|
||||
<Button className="min-w-28 gap-2" disabled={isPending} type="submit">
|
||||
{isPending && <Spinner className="size-4" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("awsSecretAccessKey", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={awsSecretKeyId}
|
||||
isRequired
|
||||
label="Secret Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={awsSecretKeyId}
|
||||
placeholder="UW7A..."
|
||||
type="text"
|
||||
{...form.register("awsSecretAccessKey")}
|
||||
/>
|
||||
<FormDescription className="pt-2">
|
||||
Secret key will not be shown again. Please save your secret
|
||||
key in a secure location
|
||||
</FormDescription>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-4 border-t border-dashed px-4 py-4 lg:px-6">
|
||||
{!supportsMultipleWalletTypes && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
This will clear other credentials.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
className="gap-2"
|
||||
disabled={isPending || !form.formState.isDirty}
|
||||
size="sm"
|
||||
type="submit"
|
||||
>
|
||||
{isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+151
-135
@@ -1,4 +1,4 @@
|
||||
import Link from "next/link";
|
||||
import { SaveIcon } from "lucide-react";
|
||||
import { useId } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
@@ -7,6 +7,7 @@ import { Form, FormDescription } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import {
|
||||
type EngineInstance,
|
||||
type SetWalletConfigInput,
|
||||
@@ -81,145 +82,160 @@ export const KmsGcpConfig: React.FC<KmsGcpConfigProps> = ({
|
||||
const gcpPrivateKeyId = useId();
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
>
|
||||
<p className="text-muted-foreground">
|
||||
GCP KMS wallets require credentials from your Google Cloud Platform
|
||||
account with sufficient permissions to manage KMS keys. Wallets are
|
||||
stored in KMS keys on your GCP account.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
For help and more advanced use cases,{" "}
|
||||
<Link
|
||||
className="text-link-foreground hover:text-foreground"
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/backend-wallets"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
learn more about using Google Cloud KMS wallets
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
<div className="bg-card rounded-lg border mb-8">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="p-4 lg:p-6">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-lg font-semibold mb-1">Credentials</h2>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpKmsLocationId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={gcpLocationId}
|
||||
isRequired
|
||||
label="Location ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
id={gcpLocationId}
|
||||
placeholder="us-west2"
|
||||
type="text"
|
||||
{...form.register("gcpKmsLocationId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<p className="text-muted-foreground mb-1 text-sm">
|
||||
GCP KMS wallets require credentials from your Google Cloud
|
||||
Platform account with sufficient permissions to manage KMS keys.{" "}
|
||||
<br />
|
||||
Wallets are stored in KMS keys on your GCP account.
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
For help and more advanced use cases,{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/backend-wallets"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
learn more about using Google Cloud KMS wallets
|
||||
</UnderlineLink>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpKmsKeyRingId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={gcpKeyRingId}
|
||||
isRequired
|
||||
label="Key Ring ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpKeyRingId}
|
||||
placeholder="my-key-ring"
|
||||
type="text"
|
||||
{...form.register("gcpKmsKeyRingId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<div className="space-y-4">
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpKmsLocationId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={gcpLocationId}
|
||||
isRequired
|
||||
label="Location ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
id={gcpLocationId}
|
||||
placeholder="us-west2"
|
||||
type="text"
|
||||
{...form.register("gcpKmsLocationId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpApplicationProjectId", form.formState)
|
||||
.error?.message
|
||||
}
|
||||
htmlFor={gcpProjectId}
|
||||
isRequired
|
||||
label="Project ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpProjectId}
|
||||
placeholder="my-gcp-project-id-123"
|
||||
type="text"
|
||||
{...form.register("gcpApplicationProjectId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpKmsKeyRingId", form.formState).error
|
||||
?.message
|
||||
}
|
||||
htmlFor={gcpKeyRingId}
|
||||
isRequired
|
||||
label="Key Ring ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpKeyRingId}
|
||||
placeholder="my-key-ring"
|
||||
type="text"
|
||||
{...form.register("gcpKmsKeyRingId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState(
|
||||
"gcpApplicationCredentialEmail",
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
htmlFor={gcpCredentialEmailId}
|
||||
isRequired
|
||||
label="Credential Email"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpCredentialEmailId}
|
||||
placeholder="[email protected]"
|
||||
type="text"
|
||||
{...form.register("gcpApplicationCredentialEmail")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState("gcpApplicationProjectId", form.formState)
|
||||
.error?.message
|
||||
}
|
||||
htmlFor={gcpProjectId}
|
||||
isRequired
|
||||
label="Project ID"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpProjectId}
|
||||
placeholder="my-gcp-project-id-123"
|
||||
type="text"
|
||||
{...form.register("gcpApplicationProjectId")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState(
|
||||
"gcpApplicationCredentialPrivateKey",
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
htmlFor={gcpPrivateKeyId}
|
||||
isRequired
|
||||
label="Private Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Textarea
|
||||
autoComplete="off"
|
||||
id={gcpPrivateKeyId}
|
||||
placeholder={
|
||||
"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
|
||||
}
|
||||
{...form.register("gcpApplicationCredentialPrivateKey")}
|
||||
/>
|
||||
<FormDescription className="pt-2">
|
||||
This will not be shown again.
|
||||
</FormDescription>
|
||||
</FormFieldSetup>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState(
|
||||
"gcpApplicationCredentialEmail",
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
htmlFor={gcpCredentialEmailId}
|
||||
isRequired
|
||||
label="Credential Email"
|
||||
tooltip={null}
|
||||
>
|
||||
<Input
|
||||
autoComplete="off"
|
||||
id={gcpCredentialEmailId}
|
||||
placeholder="[email protected]"
|
||||
type="text"
|
||||
{...form.register("gcpApplicationCredentialEmail")}
|
||||
/>
|
||||
</FormFieldSetup>
|
||||
|
||||
<div className="flex items-center justify-end gap-4">
|
||||
{!supportsMultipleWalletTypes && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
This will clear other credentials.
|
||||
</p>
|
||||
)}
|
||||
<Button className="min-w-28 gap-2" disabled={isPending} type="submit">
|
||||
{isPending && <Spinner className="size-4" />}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
<FormFieldSetup
|
||||
errorMessage={
|
||||
form.getFieldState(
|
||||
"gcpApplicationCredentialPrivateKey",
|
||||
form.formState,
|
||||
).error?.message
|
||||
}
|
||||
htmlFor={gcpPrivateKeyId}
|
||||
isRequired
|
||||
label="Private Key"
|
||||
tooltip={null}
|
||||
>
|
||||
<Textarea
|
||||
autoComplete="off"
|
||||
id={gcpPrivateKeyId}
|
||||
placeholder={
|
||||
"-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
|
||||
}
|
||||
{...form.register("gcpApplicationCredentialPrivateKey")}
|
||||
/>
|
||||
<FormDescription className="pt-2">
|
||||
Private key will not be shown again. Please save your private
|
||||
key in a secure location
|
||||
</FormDescription>
|
||||
</FormFieldSetup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-4 border-t border-dashed px-4 py-4 lg:px-6">
|
||||
{!supportsMultipleWalletTypes && (
|
||||
<p className="text-destructive-text text-sm">
|
||||
This will clear other credentials.
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
className="gap-2"
|
||||
disabled={isPending || !form.formState.isDirty}
|
||||
size="sm"
|
||||
type="submit"
|
||||
>
|
||||
{isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<SaveIcon className="size-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+4
-3
@@ -1,9 +1,10 @@
|
||||
export const LocalConfig: React.FC = () => {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="mb-4">
|
||||
<p className="text-muted-foreground">
|
||||
Local wallets are natively supported with no configuration required.
|
||||
Wallets are stored encrypted in Engine's database.
|
||||
Local wallets are natively supported with no configuration required.{" "}
|
||||
<br />
|
||||
Wallets are stored encrypted in Engine's database
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
+11
-9
@@ -26,14 +26,16 @@ export const EngineSystem: React.FC<EngineSystemProps> = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<p className="gap-0 font-mono text-xs opacity-50">
|
||||
Version: {healthQuery.data.engineVersion ?? "..."}
|
||||
<br />
|
||||
Enabled: {healthQuery.data.features?.join(", ")}
|
||||
<br />
|
||||
CPU: {metricsQuery.data?.result?.cpu?.toFixed(2) ?? "..."}%
|
||||
<br />
|
||||
Memory: {metricsQuery.data?.result?.memory?.toFixed(0) ?? "..."}MB
|
||||
</p>
|
||||
<div className="rounded-lg border border-dashed p-4 lg:p-6">
|
||||
<p className="font-mono text-xs text-muted-foreground leading-relaxed">
|
||||
Version: {healthQuery.data.engineVersion ?? "..."}
|
||||
<br />
|
||||
Enabled: {healthQuery.data.features?.join(", ")}
|
||||
<br />
|
||||
CPU: {metricsQuery.data?.result?.cpu?.toFixed(2) ?? "..."}%
|
||||
<br />
|
||||
Memory: {metricsQuery.data?.result?.memory?.toFixed(0) ?? "..."}MB
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
+172
-108
@@ -1,33 +1,38 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Input,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
Select,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { Button } from "chakra/button";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { CirclePlusIcon } from "lucide-react";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
type CreateWebhookInput,
|
||||
useEngineCreateWebhook,
|
||||
} from "@/hooks/useEngine";
|
||||
import { useTxNotifications } from "@/hooks/useTxNotifications";
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useEngineCreateWebhook } from "@/hooks/useEngine";
|
||||
import { beautifyString } from "./webhooks-table";
|
||||
|
||||
interface AddWebhookButtonProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
const WEBHOOK_EVENT_TYPES = [
|
||||
"all_transactions",
|
||||
"sent_transaction",
|
||||
@@ -38,97 +43,156 @@ const WEBHOOK_EVENT_TYPES = [
|
||||
"auth",
|
||||
];
|
||||
|
||||
export const AddWebhookButton: React.FC<AddWebhookButtonProps> = ({
|
||||
const webhookFormSchema = z.object({
|
||||
eventType: z.string().min(1, "Event type is required"),
|
||||
name: z.string().min(1, "Name is required"),
|
||||
url: z.string().url("Please enter a valid URL"),
|
||||
});
|
||||
|
||||
type WebhookFormValues = z.infer<typeof webhookFormSchema>;
|
||||
|
||||
export function AddWebhookButton({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
const { isOpen, onOpen, onClose } = useDisclosure();
|
||||
const { mutate: createWebhook } = useEngineCreateWebhook({
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const createWebhook = useEngineCreateWebhook({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const form = useForm<CreateWebhookInput>();
|
||||
const form = useForm<WebhookFormValues>({
|
||||
resolver: zodResolver(webhookFormSchema),
|
||||
defaultValues: {
|
||||
eventType: "",
|
||||
name: "",
|
||||
url: "",
|
||||
},
|
||||
mode: "onChange",
|
||||
});
|
||||
|
||||
const { onSuccess, onError } = useTxNotifications(
|
||||
"Webhook created successfully.",
|
||||
"Failed to create webhook.",
|
||||
);
|
||||
const onSubmit = (data: WebhookFormValues) => {
|
||||
createWebhook.mutate(data, {
|
||||
onError: (error) => {
|
||||
toast.error("Failed to create webhook", {
|
||||
description: error.message,
|
||||
});
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("Webhook created successfully");
|
||||
setOpen(false);
|
||||
form.reset();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
colorScheme="primary"
|
||||
leftIcon={<CirclePlusIcon className="size-6" />}
|
||||
onClick={onOpen}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
w="fit-content"
|
||||
>
|
||||
Create Webhook
|
||||
</Button>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="w-fit gap-2" onClick={() => setOpen(true)}>
|
||||
<PlusIcon className="size-4" />
|
||||
Create Webhook
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
|
||||
<Modal isCentered isOpen={isOpen} onClose={onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent
|
||||
as="form"
|
||||
className="!bg-background rounded-lg border border-border"
|
||||
onSubmit={form.handleSubmit((data) => {
|
||||
createWebhook(data, {
|
||||
onError: (error) => {
|
||||
onError(error);
|
||||
console.error(error);
|
||||
},
|
||||
onSuccess: () => {
|
||||
onSuccess();
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
})}
|
||||
>
|
||||
<ModalHeader>Create Webhook</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<Flex flexDir="column" gap={4}>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Event Type</FormLabel>
|
||||
<Select {...form.register("eventType", { required: true })}>
|
||||
{WEBHOOK_EVENT_TYPES.map((eventType) => (
|
||||
<option key={eventType} value={eventType}>
|
||||
{beautifyString(eventType)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Input
|
||||
placeholder="My webhook"
|
||||
type="text"
|
||||
{...form.register("name", { required: true })}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormControl isRequired>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<Input
|
||||
placeholder="https://"
|
||||
type="url"
|
||||
{...form.register("url", { required: true })}
|
||||
/>
|
||||
</FormControl>
|
||||
</Flex>
|
||||
</ModalBody>
|
||||
<DialogContent className="p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Create Webhook</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new webhook to receive notifications for engine events.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={onClose} type="button" variant="ghost">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button colorScheme="primary" type="submit">
|
||||
Create
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-4 px-4 lg:px-6 pb-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="eventType"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Event Type</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger className="bg-card">
|
||||
<SelectValue placeholder="Select event type" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{WEBHOOK_EVENT_TYPES.map((eventType) => (
|
||||
<SelectItem key={eventType} value={eventType}>
|
||||
{beautifyString(eventType)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="My webhook"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="https://"
|
||||
type="url"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-3 p-4 lg:p-6 bg-card border-t border-border">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={createWebhook.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{createWebhook.isPending && <Spinner className="size-4" />}
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+26
-28
@@ -1,43 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import { Heading } from "chakra/heading";
|
||||
import { Link } from "chakra/link";
|
||||
import { Text } from "chakra/text";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { useEngineWebhooks } from "@/hooks/useEngine";
|
||||
import { AddWebhookButton } from "./add-webhook-button";
|
||||
import { WebhooksTable } from "./webhooks-table";
|
||||
|
||||
interface EngineWebhooksProps {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
export const EngineWebhooks: React.FC<EngineWebhooksProps> = ({
|
||||
export function EngineWebhooks({
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}) => {
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const webhooks = useEngineWebhooks({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Heading size="title.md">Webhooks</Heading>
|
||||
<Text>
|
||||
Notify your app backend when transaction and backend wallet events
|
||||
occur.{" "}
|
||||
<Link
|
||||
color="primary.500"
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/webhooks"
|
||||
isExternal
|
||||
>
|
||||
Learn more about webhooks
|
||||
</Link>
|
||||
.
|
||||
</Text>
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-2xl tracking-tight font-semibold mb-1">Webhooks</h2>
|
||||
<p className="text-muted-foreground mb-4 text-sm">
|
||||
Notify your app backend when transaction and backend wallet events
|
||||
occur.{" "}
|
||||
<UnderlineLink
|
||||
href="https://portal.thirdweb.com/infrastructure/engine/features/webhooks"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Learn more about webhooks
|
||||
</UnderlineLink>
|
||||
.
|
||||
</p>
|
||||
|
||||
<WebhooksTable
|
||||
authToken={authToken}
|
||||
instanceUrl={instanceUrl}
|
||||
@@ -45,7 +40,10 @@ export const EngineWebhooks: React.FC<EngineWebhooksProps> = ({
|
||||
isPending={webhooks.isPending}
|
||||
webhooks={webhooks.data || []}
|
||||
/>
|
||||
<AddWebhookButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
|
||||
<div className="mt-4 flex justify-end">
|
||||
<AddWebhookButton authToken={authToken} instanceUrl={instanceUrl} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
+197
-147
@@ -1,36 +1,30 @@
|
||||
import {
|
||||
Flex,
|
||||
FormControl,
|
||||
Modal,
|
||||
ModalBody,
|
||||
ModalCloseButton,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalHeader,
|
||||
ModalOverlay,
|
||||
Tooltip,
|
||||
type UseDisclosureReturn,
|
||||
useDisclosure,
|
||||
} from "@chakra-ui/react";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { Card } from "chakra/card";
|
||||
import { FormLabel } from "chakra/form";
|
||||
import { Text } from "chakra/text";
|
||||
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||
import { MailQuestionIcon, TrashIcon } from "lucide-react";
|
||||
import { ForwardIcon, RotateCcwIcon, TrashIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { TWTable } from "@/components/blocks/TWTable";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
||||
import { FormItem } from "@/components/ui/form";
|
||||
import { PlainTextCodeBlock } from "@/components/ui/code/plaintext-code";
|
||||
import { DynamicHeight } from "@/components/ui/DynamicHeight";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Spinner } from "@/components/ui/Spinner/Spinner";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import {
|
||||
type EngineWebhook,
|
||||
useEngineDeleteWebhook,
|
||||
useEngineTestWebhook,
|
||||
} from "@/hooks/useEngine";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
import { shortenString } from "@/utils/usedapp-external";
|
||||
|
||||
export function beautifyString(str: string): string {
|
||||
@@ -40,26 +34,27 @@ export function beautifyString(str: string): string {
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
interface WebhooksTableProps {
|
||||
instanceUrl: string;
|
||||
webhooks: EngineWebhook[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
}
|
||||
|
||||
const columnHelper = createColumnHelper<EngineWebhook>();
|
||||
|
||||
const columns = [
|
||||
columnHelper.accessor("name", {
|
||||
cell: (cell) => {
|
||||
return <Text>{cell.getValue()}</Text>;
|
||||
return (
|
||||
<span className="text-foreground">{cell.getValue() || "N/A"}</span>
|
||||
);
|
||||
},
|
||||
header: "Name",
|
||||
}),
|
||||
columnHelper.accessor("eventType", {
|
||||
cell: (cell) => {
|
||||
return <Text>{beautifyString(cell.getValue())}</Text>;
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="py-1 text-sm font-normal bg-background"
|
||||
>
|
||||
{beautifyString(cell.getValue())}
|
||||
</Badge>
|
||||
);
|
||||
},
|
||||
header: "Event Type",
|
||||
}),
|
||||
@@ -71,6 +66,8 @@ const columns = [
|
||||
textToCopy={cell.getValue() || ""}
|
||||
textToShow={shortenString(cell.getValue() || "")}
|
||||
tooltip="Secret"
|
||||
variant="ghost"
|
||||
className="-translate-x-2 text-muted-foreground font-mono"
|
||||
/>
|
||||
);
|
||||
},
|
||||
@@ -80,9 +77,9 @@ const columns = [
|
||||
cell: (cell) => {
|
||||
const url = cell.getValue();
|
||||
return (
|
||||
<Text isTruncated maxW={300}>
|
||||
<span className="text-foreground truncate max-w-[300px] block">
|
||||
{url}
|
||||
</Text>
|
||||
</span>
|
||||
);
|
||||
},
|
||||
header: "URL",
|
||||
@@ -96,35 +93,33 @@ const columns = [
|
||||
|
||||
const date = new Date(value);
|
||||
return (
|
||||
<Tooltip
|
||||
bg="transparent"
|
||||
borderRadius="md"
|
||||
boxShadow="none"
|
||||
label={
|
||||
<Card bgColor="backgroundHighlight">
|
||||
<Text>{format(date, "PP pp z")}</Text>
|
||||
</Card>
|
||||
}
|
||||
shouldWrapChildren
|
||||
>
|
||||
<Text>{formatDistanceToNowStrict(date, { addSuffix: true })}</Text>
|
||||
</Tooltip>
|
||||
<ToolTipLabel label={format(date, "PP pp z")}>
|
||||
<span className="text-foreground cursor-help">
|
||||
{formatDistanceToNowStrict(date, { addSuffix: true })}
|
||||
</span>
|
||||
</ToolTipLabel>
|
||||
);
|
||||
},
|
||||
header: "Created At",
|
||||
}),
|
||||
];
|
||||
|
||||
export const WebhooksTable: React.FC<WebhooksTableProps> = ({
|
||||
export function WebhooksTable({
|
||||
instanceUrl,
|
||||
webhooks,
|
||||
isPending,
|
||||
isFetched,
|
||||
authToken,
|
||||
}) => {
|
||||
}: {
|
||||
instanceUrl: string;
|
||||
webhooks: EngineWebhook[];
|
||||
isPending: boolean;
|
||||
isFetched: boolean;
|
||||
authToken: string;
|
||||
}) {
|
||||
const [selectedWebhook, setSelectedWebhook] = useState<EngineWebhook>();
|
||||
const deleteDisclosure = useDisclosure();
|
||||
const testDisclosure = useDisclosure();
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [testDialogOpen, setTestDialogOpen] = useState(false);
|
||||
|
||||
const activeWebhooks = webhooks.filter((webhook) => webhook.active);
|
||||
|
||||
@@ -137,10 +132,10 @@ export const WebhooksTable: React.FC<WebhooksTableProps> = ({
|
||||
isPending={isPending}
|
||||
onMenuClick={[
|
||||
{
|
||||
icon: <MailQuestionIcon className="size-4" />,
|
||||
icon: <ForwardIcon className="size-4" />,
|
||||
onClick: (row) => {
|
||||
setSelectedWebhook(row);
|
||||
testDisclosure.onOpen();
|
||||
setTestDialogOpen(true);
|
||||
},
|
||||
text: "Test webhook",
|
||||
},
|
||||
@@ -149,7 +144,7 @@ export const WebhooksTable: React.FC<WebhooksTableProps> = ({
|
||||
isDestructive: true,
|
||||
onClick: (row) => {
|
||||
setSelectedWebhook(row);
|
||||
deleteDisclosure.onOpen();
|
||||
setDeleteDialogOpen(true);
|
||||
},
|
||||
text: "Delete",
|
||||
},
|
||||
@@ -157,114 +152,150 @@ export const WebhooksTable: React.FC<WebhooksTableProps> = ({
|
||||
title="webhooks"
|
||||
/>
|
||||
|
||||
{selectedWebhook && deleteDisclosure.isOpen && (
|
||||
<DeleteWebhookModal
|
||||
{selectedWebhook && (
|
||||
<DeleteWebhookDialog
|
||||
authToken={authToken}
|
||||
disclosure={deleteDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
webhook={selectedWebhook}
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
/>
|
||||
)}
|
||||
{selectedWebhook && testDisclosure.isOpen && (
|
||||
<TestWebhookModal
|
||||
{selectedWebhook && (
|
||||
<TestWebhookDialog
|
||||
authToken={authToken}
|
||||
disclosure={testDisclosure}
|
||||
instanceUrl={instanceUrl}
|
||||
webhook={selectedWebhook}
|
||||
open={testDialogOpen}
|
||||
onOpenChange={setTestDialogOpen}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
interface DeleteWebhookModalProps {
|
||||
webhook: EngineWebhook;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
function DeleteWebhookModal({
|
||||
|
||||
function DeleteWebhookDialog({
|
||||
webhook,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}: DeleteWebhookModalProps) {
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
webhook: EngineWebhook;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
const deleteWebhook = useEngineDeleteWebhook({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
|
||||
const onDelete = () => {
|
||||
const promise = deleteWebhook.mutateAsync(
|
||||
const onDelete = async () => {
|
||||
await deleteWebhook.mutateAsync(
|
||||
{ id: webhook.id },
|
||||
{
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
toast.error("Failed to delete webhook", {
|
||||
description: parseError(error),
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
disclosure.onClose();
|
||||
onOpenChange(false);
|
||||
toast.success("Webhook deleted successfully");
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
toast.promise(promise, {
|
||||
error: "Failed to delete webhook.",
|
||||
success: "Successfully deleted webhook.",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Delete Webhook</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4">
|
||||
<Text>Are you sure you want to delete this webhook?</Text>
|
||||
<FormControl>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<Text>{webhook.name}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<Text>{webhook.url}</Text>
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<FormLabel>Created at</FormLabel>
|
||||
<Text>
|
||||
{format(new Date(webhook.createdAt ?? ""), "PP pp z")}
|
||||
</Text>
|
||||
</FormControl>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Delete Webhook</DialogTitle>
|
||||
<DialogDescription>
|
||||
Are you sure you want to delete this webhook?
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ModalFooter as={Flex} gap={3}>
|
||||
<Button onClick={disclosure.onClose} variant="outline">
|
||||
<div className="space-y-4 px-4 lg:px-6 pb-8 overflow-hidden">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium text-foreground">Name</h3>
|
||||
<span className="text-foreground text-sm">
|
||||
{webhook.name || "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium text-foreground">URL</h3>
|
||||
<p className="text-foreground text-sm truncate">{webhook.url}</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium text-foreground">Created at</h3>
|
||||
<span className="text-foreground text-sm">
|
||||
{format(new Date(webhook.createdAt ?? ""), "PP pp z")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 p-4 lg:p-6 bg-card border-t border-border justify-end ">
|
||||
<Button onClick={() => onOpenChange(false)} variant="outline">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={onDelete} type="submit" variant="destructive">
|
||||
<Button
|
||||
onClick={onDelete}
|
||||
type="submit"
|
||||
variant="destructive"
|
||||
disabled={deleteWebhook.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{deleteWebhook.isPending && <Spinner className="size-4" />}
|
||||
Delete
|
||||
</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
interface TestWebhookModalProps {
|
||||
webhook: EngineWebhook;
|
||||
disclosure: UseDisclosureReturn;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}
|
||||
function TestWebhookModal({
|
||||
function TestWebhookDialog({
|
||||
webhook,
|
||||
disclosure,
|
||||
instanceUrl,
|
||||
authToken,
|
||||
}: TestWebhookModalProps) {
|
||||
const { mutate: testWebhook, isPending } = useEngineTestWebhook({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
webhook: EngineWebhook;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="gap-0 p-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 lg:p-6">
|
||||
<DialogTitle>Test Webhook</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<TestWebhookDialogContent
|
||||
authToken={authToken}
|
||||
instanceUrl={instanceUrl}
|
||||
webhook={webhook}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function TestWebhookDialogContent(props: {
|
||||
webhook: EngineWebhook;
|
||||
instanceUrl: string;
|
||||
authToken: string;
|
||||
}) {
|
||||
const { webhook, instanceUrl, authToken } = props;
|
||||
|
||||
const testWebhook = useEngineTestWebhook({
|
||||
authToken,
|
||||
instanceUrl,
|
||||
});
|
||||
@@ -273,7 +304,7 @@ function TestWebhookModal({
|
||||
const [body, setBody] = useState<string | undefined>();
|
||||
|
||||
const onTest = () => {
|
||||
testWebhook(
|
||||
testWebhook.mutate(
|
||||
{ id: webhook.id },
|
||||
{
|
||||
onSuccess: (result) => {
|
||||
@@ -285,36 +316,55 @@ function TestWebhookModal({
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isCentered isOpen={disclosure.isOpen} onClose={disclosure.onClose}>
|
||||
<ModalOverlay />
|
||||
<ModalContent className="!bg-background rounded-lg border border-border">
|
||||
<ModalHeader>Test Webhook</ModalHeader>
|
||||
<ModalCloseButton />
|
||||
<ModalBody>
|
||||
<div className="flex flex-col gap-4 pb-2">
|
||||
<FormItem>
|
||||
<FormLabel>URL</FormLabel>
|
||||
<span className="font-mono">{webhook.url}</span>
|
||||
</FormItem>
|
||||
|
||||
<Button disabled={isPending} onClick={onTest} type="submit">
|
||||
{isPending && <Spinner className="mr-2 size-4" />}
|
||||
Send Request
|
||||
</Button>
|
||||
|
||||
{status && (
|
||||
<div>
|
||||
<Badge variant={status <= 299 ? "success" : "destructive"}>
|
||||
{status}
|
||||
</Badge>
|
||||
</div>
|
||||
)}
|
||||
<div className="max-h-[12rem] overflow-y-auto font-mono text-sm">
|
||||
{body ?? "Send a request to see the response."}
|
||||
</div>
|
||||
<DynamicHeight>
|
||||
<div className="overflow-hidden">
|
||||
<div className="space-y-4 px-4 lg:px-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium text-foreground">URL</h3>
|
||||
{/* <span className="font-mono text-foreground">{webhook.url}</span> */}
|
||||
<PlainTextCodeBlock code={webhook.url} />
|
||||
</div>
|
||||
</ModalBody>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
|
||||
{body && !testWebhook.isPending && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-sm font-medium text-foreground">
|
||||
Response
|
||||
</h3>
|
||||
{status && (
|
||||
<Badge variant={status <= 299 ? "success" : "destructive"}>
|
||||
{status}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<PlainTextCodeBlock
|
||||
code={body}
|
||||
scrollableClassName="max-h-[300px]"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{testWebhook.isPending && <Skeleton className="h-32 w-full" />}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end p-4 lg:p-6 bg-card border-t border-border mt-8">
|
||||
<Button
|
||||
disabled={testWebhook.isPending}
|
||||
onClick={onTest}
|
||||
type="submit"
|
||||
className="gap-2"
|
||||
>
|
||||
{testWebhook.isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : body ? (
|
||||
<RotateCcwIcon className="size-4" />
|
||||
) : (
|
||||
<ForwardIcon className="size-4" />
|
||||
)}
|
||||
{body ? "Send again" : "Send request"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DynamicHeight>
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { CardHeading } from "../../universal-bridge/components/common";
|
||||
import { CardHeading } from "../../payments/components/common";
|
||||
|
||||
export function TopInsightChainsTable(props: {
|
||||
data: InsightChainStats[];
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@ import {
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { CardHeading } from "../../universal-bridge/components/common";
|
||||
import { CardHeading } from "../../payments/components/common";
|
||||
|
||||
export function TopInsightEndpointsTable(props: {
|
||||
data: InsightEndpointStats[];
|
||||
|
||||
@@ -373,7 +373,7 @@ async function AsyncAppHighlightsCard(props: {
|
||||
|
||||
return (
|
||||
<EmptyStateCard
|
||||
link="https://portal.thirdweb.com/connect/quickstart"
|
||||
link="https://portal.thirdweb.com/wallets"
|
||||
metric="Wallets"
|
||||
/>
|
||||
);
|
||||
@@ -395,7 +395,7 @@ async function AsyncWalletDistributionCard(props: {
|
||||
<WalletDistributionCard data={walletConnections} />
|
||||
) : (
|
||||
<EmptyStateCard
|
||||
link="https://portal.thirdweb.com/connect/quickstart"
|
||||
link="https://portal.thirdweb.com/wallets"
|
||||
metric="Wallets"
|
||||
/>
|
||||
);
|
||||
@@ -423,7 +423,7 @@ function AppHighlightsCard({
|
||||
emptyContent: (
|
||||
<EmptyStateContent
|
||||
description="Your app hasn't collected any fees yet."
|
||||
link={`/team/${params.team_slug}/${params.project_slug}/connect/universal-bridge/settings`}
|
||||
link={`/team/${params.team_slug}/${params.project_slug}/payments/settings`}
|
||||
metric="Fees"
|
||||
/>
|
||||
),
|
||||
@@ -436,7 +436,7 @@ function AppHighlightsCard({
|
||||
emptyContent: (
|
||||
<EmptyStateContent
|
||||
description="Onramp, swap, and bridge with thirdweb's Payments."
|
||||
link="https://portal.thirdweb.com/connect/pay/overview"
|
||||
link="https://portal.thirdweb.com/payments"
|
||||
metric="Payments"
|
||||
/>
|
||||
),
|
||||
|
||||
+4
-6
@@ -5,8 +5,8 @@ import { getAuthToken } from "@/api/auth-token";
|
||||
import { getProject } from "@/api/projects";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { PayAnalytics } from "./components/PayAnalytics";
|
||||
import { getUniversalBridgeFiltersFromSearchParams } from "./components/time";
|
||||
import { PayAnalytics } from "../components/PayAnalytics";
|
||||
import { getUniversalBridgeFiltersFromSearchParams } from "../components/time";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{
|
||||
@@ -24,9 +24,7 @@ export default async function Page(props: {
|
||||
const project = await getProject(params.team_slug, params.project_slug);
|
||||
|
||||
if (!authToken) {
|
||||
loginRedirect(
|
||||
`/team/${params.team_slug}/${params.project_slug}/universal-bridge`,
|
||||
);
|
||||
loginRedirect(`/team/${params.team_slug}/${params.project_slug}/payments`);
|
||||
}
|
||||
|
||||
if (!project) {
|
||||
@@ -70,7 +68,7 @@ export default async function Page(props: {
|
||||
</div>
|
||||
<a
|
||||
className="inline-flex items-center gap-2 rounded-md bg-green-600 px-4 py-2 font-medium text-sm text-white transition-all hover:bg-green-600/90 hover:shadow-sm"
|
||||
href="https://portal.thirdweb.com/pay"
|
||||
href="https://portal.thirdweb.com/payments"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { CodeIcon, WebhookIcon } from "lucide-react";
|
||||
import { FeatureCard } from "./FeatureCard.client";
|
||||
|
||||
export function AdvancedSection({
|
||||
teamSlug,
|
||||
projectSlug,
|
||||
}: {
|
||||
teamSlug: string;
|
||||
projectSlug: string;
|
||||
}) {
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-4">
|
||||
<h2 className="font-semibold text-xl tracking-tight">Going Further</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Advanced features to drive revenue in your app.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<FeatureCard
|
||||
title="Customized Experience"
|
||||
description="Build your own branded experiences with the HTTP API or TypeScript SDK."
|
||||
icon={CodeIcon}
|
||||
setupTime={10}
|
||||
color="green"
|
||||
id="http_api"
|
||||
features={["Route discovery", "Real-time token prices"]}
|
||||
link={{
|
||||
href: "https://payments.thirdweb.com/reference",
|
||||
label: "Documentation",
|
||||
}}
|
||||
/>
|
||||
<FeatureCard
|
||||
title="Webhooks"
|
||||
description="Create Webhooks to get notified on each purchase or transaction."
|
||||
icon={WebhookIcon}
|
||||
setupTime={5}
|
||||
color="green"
|
||||
id="webhooks"
|
||||
features={["Instant events", "Transaction verification"]}
|
||||
link={{
|
||||
href: `/team/${teamSlug}/${projectSlug}/payments/webhooks`,
|
||||
label: "Setup Webhooks",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+3
-3
@@ -8,7 +8,7 @@ import { TabButtons } from "@/components/ui/tabs";
|
||||
|
||||
type Tab = "embed" | "sdk" | "api";
|
||||
|
||||
export function PayEmbedFTUX(props: {
|
||||
export function BuyWidgetFTUX(props: {
|
||||
clientId: string;
|
||||
codeExamples: {
|
||||
embed: React.ReactNode;
|
||||
@@ -21,7 +21,7 @@ export function PayEmbedFTUX(props: {
|
||||
<div className="rounded-lg border bg-card">
|
||||
<div className="border-b border-dashed p-4">
|
||||
<h2 className="font-semibold text-lg tracking-tight">
|
||||
Start Monetizing Your App
|
||||
Setup Payments to View Analytics
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
@@ -56,7 +56,7 @@ export function PayEmbedFTUX(props: {
|
||||
<Button asChild size="sm" variant="outline">
|
||||
<Link
|
||||
className="gap-2"
|
||||
href="https://portal.thirdweb.com/pay"
|
||||
href="https://portal.thirdweb.com/payments"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowRightIcon, ClockIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { reportPaymentCardClick } from "@/analytics/report";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
|
||||
export function FeatureCard(props: {
|
||||
title: string;
|
||||
description: string;
|
||||
badge?: { label: string; variant?: "outline" | "success" | "default" };
|
||||
id: string;
|
||||
icon: React.FC<{ className?: string }>;
|
||||
color?: "green" | "violet";
|
||||
setupTime?: number;
|
||||
features?: string[];
|
||||
link: { href: string; label: string; target?: string };
|
||||
}) {
|
||||
return (
|
||||
<Card className="p-6 flex flex-col items-start gap-6 text-muted-foreground w-full">
|
||||
<div className="flex-1 flex flex-col items-start gap-6 w-full">
|
||||
<div className="relative w-full">
|
||||
<div
|
||||
className={`${props.color === "green" ? "bg-green-700/25" : "bg-violet-700/25"} rounded-lg size-9 flex items-center justify-center`}
|
||||
>
|
||||
<props.icon
|
||||
className={`size-5 ${props.color === "green" ? "text-green-500" : "text-violet-500"}`}
|
||||
/>
|
||||
</div>
|
||||
{props.badge && (
|
||||
<Badge
|
||||
variant={props.badge.variant}
|
||||
className="absolute top-0 right-0"
|
||||
>
|
||||
{props.badge.label}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<h3 className="font-semibold text-foreground">{props.title}</h3>
|
||||
<p className="text-muted-foreground text-sm font-medium">
|
||||
{props.description}
|
||||
</p>
|
||||
</div>
|
||||
{(props.setupTime || props.features) && (
|
||||
<div className="flex justify-center gap-4 text-xs flex-col">
|
||||
{props.setupTime && (
|
||||
<p className="flex gap-2 items-center">
|
||||
<ClockIcon className="size-3" />
|
||||
{props.setupTime} minute{props.setupTime > 1 && "s"} setup time
|
||||
</p>
|
||||
)}
|
||||
{props.features && (
|
||||
<ul>
|
||||
{props.features.map((feature) => (
|
||||
<li key={feature} className="flex gap-2 items-center mb-1.5">
|
||||
<span className="bg-violet-500 size-1.5 rounded-full" />
|
||||
{feature}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => reportPaymentCardClick({ id: props.id })}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="w-full gap-2 group text-foreground"
|
||||
asChild
|
||||
>
|
||||
<Link href={props.link.href} target={props.link.target}>
|
||||
{props.link.label}
|
||||
<ArrowRightIcon className="size-4 group-hover:translate-x-1 transition-all" />
|
||||
</Link>
|
||||
</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -7,10 +7,10 @@ import {
|
||||
import type { Range } from "@/components/analytics/date-range-selector";
|
||||
import { CodeServer } from "@/components/ui/code/code.server";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { BuyWidgetFTUX } from "./BuyWidgetFTUX";
|
||||
import { apiCode, embedCode, sdkCode } from "./code-examples";
|
||||
import { PayAnalyticsFilter } from "./PayAnalyticsFilter";
|
||||
import { PayCustomersTable } from "./PayCustomersTable";
|
||||
import { PayEmbedFTUX } from "./PayEmbedFTUX";
|
||||
import { PaymentHistory } from "./PaymentHistory";
|
||||
import { PaymentsSuccessRate } from "./PaymentsSuccessRate";
|
||||
import { PayNewCustomers } from "./PayNewCustomers";
|
||||
@@ -67,7 +67,7 @@ export async function PayAnalytics(props: {
|
||||
|
||||
if (!hasVolume && !hasWallet) {
|
||||
return (
|
||||
<PayEmbedFTUX
|
||||
<BuyWidgetFTUX
|
||||
clientId={props.projectClientId}
|
||||
codeExamples={
|
||||
{
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user