Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea4e2fe376 | ||
|
|
1d54cff7b4 | ||
|
|
fd04eefea9 | ||
|
|
4cc68310dc | ||
|
|
ccdce496e0 | ||
|
|
2725f337f8 | ||
|
|
2c6ea3e6dd | ||
|
|
219fc69d72 | ||
|
|
8d17685683 | ||
|
|
8ef418c543 | ||
|
|
b88f75b494 | ||
|
|
c83f1c6f7a | ||
|
|
bc0295487b | ||
|
|
90b779107d | ||
|
|
afe187de95 | ||
|
|
759b93beff | ||
|
|
8e357b3cb3 | ||
|
|
6c318f83d6 | ||
|
|
f790c9fae9 | ||
|
|
bcbb3f540a | ||
|
|
931c730a08 | ||
|
|
e0c83121c2 | ||
|
|
a82a31e5ad | ||
|
|
3d235e218a | ||
|
|
c08fb1356e | ||
|
|
68cca6f992 | ||
|
|
e0abf2b273 | ||
|
|
abf0bbaf35 | ||
|
|
23cb3bd98c | ||
|
|
dcef3f4fe7 | ||
|
|
bf46520a6b | ||
|
|
7defce7264 | ||
|
|
ae3a122cf1 | ||
|
|
2412a6958c | ||
|
|
bfd3be764c | ||
|
|
46b9d2dd82 | ||
|
|
3e9eb49787 | ||
|
|
630edadcec | ||
|
|
f757e60846 | ||
|
|
d5d593956e | ||
|
|
9a4b1cb147 | ||
|
|
85fe9491cd | ||
|
|
899051f788 | ||
|
|
5828b9bd45 | ||
|
|
2b68a32eaa | ||
|
|
66ae33ee8b | ||
|
|
e9788096d6 | ||
|
|
706d696434 | ||
|
|
c36cfbb5c7 | ||
|
|
93a9ba9121 | ||
|
|
6a7b556d75 |
@@ -188,9 +188,16 @@ jobs:
|
|||||||
- name: Build Packages
|
- name: Build Packages
|
||||||
run: pnpm build
|
run: pnpm build
|
||||||
|
|
||||||
- name: Report bundle size
|
- name: Report bundle size (thirdweb)
|
||||||
uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d # v1.8.0
|
uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d # v1.8.0
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
package_manager: pnpm
|
package_manager: pnpm
|
||||||
directory: packages/thirdweb
|
directory: packages/thirdweb
|
||||||
|
|
||||||
|
- name: Report bundle size (nexus)
|
||||||
|
uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d # v1.8.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
package_manager: pnpm
|
||||||
|
directory: packages/nexus
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hookform/resolvers": "^3.9.1",
|
"@hookform/resolvers": "^3.9.1",
|
||||||
"@marsidev/react-turnstile": "^1.1.0",
|
"@marsidev/react-turnstile": "^1.1.0",
|
||||||
|
"@number-flow/react": "^0.5.10",
|
||||||
"@radix-ui/react-accordion": "^1.2.11",
|
"@radix-ui/react-accordion": "^1.2.11",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.14",
|
"@radix-ui/react-alert-dialog": "^1.1.14",
|
||||||
"@radix-ui/react-avatar": "^1.1.10",
|
"@radix-ui/react-avatar": "^1.1.10",
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 2.1 MiB |
@@ -95,7 +95,7 @@ function SkeletonBarChart(props: {
|
|||||||
fill={`url(#${fillAreaSkeletonId})`}
|
fill={`url(#${fillAreaSkeletonId})`}
|
||||||
radius={8}
|
radius={8}
|
||||||
stroke="hsl(var(--muted-foreground))"
|
stroke="hsl(var(--muted-foreground))"
|
||||||
type="natural"
|
type="monotone"
|
||||||
/>
|
/>
|
||||||
</AreaChart>
|
</AreaChart>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -172,7 +172,7 @@ export function ThirdwebAreaChart<TConfig extends ChartConfig>(
|
|||||||
key={key}
|
key={key}
|
||||||
stackId={props.variant !== "stacked" ? undefined : "a"}
|
stackId={props.variant !== "stacked" ? undefined : "a"}
|
||||||
stroke={`var(--color-${key})`}
|
stroke={`var(--color-${key})`}
|
||||||
type="natural"
|
type="monotone"
|
||||||
/>
|
/>
|
||||||
),
|
),
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -51,17 +51,12 @@ export function WalletAddressUI(
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
// default back to zero address if no address provided
|
const address = props.address || ZERO_ADDRESS;
|
||||||
const address = useMemo(() => props.address || ZERO_ADDRESS, [props.address]);
|
|
||||||
|
|
||||||
const [shortenedAddress, _lessShortenedAddress] = useMemo(() => {
|
const shortenedAddress =
|
||||||
return [
|
|
||||||
props.shortenAddress !== false
|
props.shortenAddress !== false
|
||||||
? `${address.slice(0, 6)}...${address.slice(-4)}`
|
? `${address.slice(0, 6)}...${address.slice(-4)}`
|
||||||
: address,
|
: address;
|
||||||
`${address.slice(0, 14)}...${address.slice(-12)}`,
|
|
||||||
];
|
|
||||||
}, [address, props.shortenAddress]);
|
|
||||||
|
|
||||||
if (!isAddress(address)) {
|
if (!isAddress(address)) {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ const customClaimAmounts: Record<number, number> = {
|
|||||||
631571: 0.1,
|
631571: 0.1,
|
||||||
// Sophon testnet
|
// Sophon testnet
|
||||||
531050104: 5,
|
531050104: 5,
|
||||||
|
// Arc testnet
|
||||||
|
5042002: 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultClaimAmount = 0.01;
|
const defaultClaimAmount = 0.01;
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ export function getSDKTheme(theme: "light" | "dark"): Theme {
|
|||||||
primaryButtonText: "hsl(var(--inverted-foreground))",
|
primaryButtonText: "hsl(var(--inverted-foreground))",
|
||||||
primaryText: "hsl(var(--foreground))",
|
primaryText: "hsl(var(--foreground))",
|
||||||
scrollbarBg: "hsl(var(--muted))",
|
scrollbarBg: "hsl(var(--muted))",
|
||||||
secondaryButtonBg: "hsl(var(--secondary))",
|
secondaryButtonBg: "hsl(var(--secondary)/70%)",
|
||||||
secondaryButtonHoverBg: "hsl(var(--secondary)/80%)",
|
secondaryButtonHoverBg: "hsl(var(--secondary))",
|
||||||
secondaryButtonText: "hsl(var(--secondary-foreground))",
|
secondaryButtonText: "hsl(var(--secondary-foreground))",
|
||||||
secondaryIconColor: "hsl(var(--secondary-foreground))",
|
secondaryIconColor: "hsl(var(--secondary-foreground))",
|
||||||
secondaryIconHoverBg: "hsl(var(--accent))",
|
secondaryIconHoverBg: "hsl(var(--accent))",
|
||||||
@@ -33,7 +33,7 @@ export function getSDKTheme(theme: "light" | "dark"): Theme {
|
|||||||
separatorLine: "hsl(var(--border))",
|
separatorLine: "hsl(var(--border))",
|
||||||
skeletonBg: "hsl(var(--secondary-foreground)/15%)",
|
skeletonBg: "hsl(var(--secondary-foreground)/15%)",
|
||||||
success: "hsl(var(--success-text))",
|
success: "hsl(var(--success-text))",
|
||||||
tertiaryBg: "hsl(var(--muted)/30%)",
|
tertiaryBg: "hsl(var(--muted)/50%)",
|
||||||
tooltipBg: "hsl(var(--popover))",
|
tooltipBg: "hsl(var(--popover))",
|
||||||
tooltipText: "hsl(var(--popover-foreground))",
|
tooltipText: "hsl(var(--popover-foreground))",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { Metadata } from "next";
|
|||||||
import { unstable_cache } from "next/cache";
|
import { unstable_cache } from "next/cache";
|
||||||
import { Bridge } from "thirdweb";
|
import { Bridge } from "thirdweb";
|
||||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||||
|
import { bridgeStats } from "../../../bridge/data";
|
||||||
import { PageHeader } from "./components/header";
|
import { PageHeader } from "./components/header";
|
||||||
import { TokenPage } from "./components/token-page";
|
import { TokenPage } from "./components/token-page";
|
||||||
|
|
||||||
@@ -36,7 +37,8 @@ export default async function Page() {
|
|||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
85+ chains, 4500+ tokens and 9+ million routes supported
|
{bridgeStats.supportedChains} chains, {bridgeStats.supportedTokens}{" "}
|
||||||
|
tokens and {bridgeStats.supportedRoutes} routes supported
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+6
-2
@@ -4,9 +4,14 @@ import { ProjectFTUX } from "./ProjectFTUX";
|
|||||||
|
|
||||||
const meta = {
|
const meta = {
|
||||||
component: ProjectFTUX,
|
component: ProjectFTUX,
|
||||||
|
parameters: {
|
||||||
|
nextjs: {
|
||||||
|
appDirectory: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
decorators: [
|
decorators: [
|
||||||
(Story) => (
|
(Story) => (
|
||||||
<div className="container py-8 pb-20">
|
<div className="container py-8 pb-20 max-w-7xl">
|
||||||
<Story />
|
<Story />
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
@@ -31,6 +36,5 @@ export const Default: Story = {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
teamSlug: "bar",
|
teamSlug: "bar",
|
||||||
managementAccessToken: undefined,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-80
@@ -15,33 +15,12 @@ import { UnrealIcon } from "@/icons/brand-icons/UnrealIcon";
|
|||||||
import { ContractIcon } from "@/icons/ContractIcon";
|
import { ContractIcon } from "@/icons/ContractIcon";
|
||||||
import { InsightIcon } from "@/icons/InsightIcon";
|
import { InsightIcon } from "@/icons/InsightIcon";
|
||||||
import { PayIcon } from "@/icons/PayIcon";
|
import { PayIcon } from "@/icons/PayIcon";
|
||||||
import { WalletProductIcon } from "@/icons/WalletProductIcon";
|
|
||||||
import { getProjectWalletLabel } from "@/lib/project-wallet";
|
|
||||||
import {
|
|
||||||
getProjectWallet,
|
|
||||||
type ProjectWalletSummary,
|
|
||||||
} from "@/lib/server/project-wallet";
|
|
||||||
import { ClientIDSection } from "./ClientIDSection";
|
import { ClientIDSection } from "./ClientIDSection";
|
||||||
import { ProjectWalletControls } from "./ProjectWalletControls.client";
|
|
||||||
import { ProjectWalletSetup } from "./ProjectWalletSetup.client";
|
|
||||||
import { SecretKeySection } from "./SecretKeySection";
|
import { SecretKeySection } from "./SecretKeySection";
|
||||||
|
|
||||||
export async function ProjectFTUX(props: {
|
export function ProjectFTUX(props: { project: Project; teamSlug: string }) {
|
||||||
project: Project;
|
|
||||||
teamSlug: string;
|
|
||||||
wallet?: ProjectWalletSummary | undefined;
|
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
}) {
|
|
||||||
const projectWallet = props.wallet ?? (await getProjectWallet(props.project));
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-10">
|
<div className="flex flex-col gap-10">
|
||||||
<ProjectWalletSection
|
|
||||||
project={props.project}
|
|
||||||
teamSlug={props.teamSlug}
|
|
||||||
wallet={projectWallet}
|
|
||||||
managementAccessToken={props.managementAccessToken}
|
|
||||||
/>
|
|
||||||
<IntegrateAPIKeySection project={props.project} />
|
<IntegrateAPIKeySection project={props.project} />
|
||||||
<ProductsSection
|
<ProductsSection
|
||||||
projectSlug={props.project.slug}
|
projectSlug={props.project.slug}
|
||||||
@@ -53,64 +32,6 @@ export async function ProjectFTUX(props: {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ProjectWalletSection(props: {
|
|
||||||
project: Project;
|
|
||||||
teamSlug: string;
|
|
||||||
wallet: ProjectWalletSummary | undefined;
|
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
}) {
|
|
||||||
const defaultLabel = getProjectWalletLabel(props.project.name);
|
|
||||||
const walletAddress = props.wallet?.address;
|
|
||||||
const label = props.wallet?.label ?? defaultLabel;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section>
|
|
||||||
<div className="rounded-lg border border-border bg-card p-4">
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="rounded-full border border-border bg-background p-2">
|
|
||||||
<WalletProductIcon className="size-5 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold text-lg tracking-tight">
|
|
||||||
Project Wallet
|
|
||||||
</p>
|
|
||||||
<p className="text-muted-foreground text-sm">
|
|
||||||
Use it for deployments, payments, and API integrations.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{walletAddress ? (
|
|
||||||
<>
|
|
||||||
<ProjectWalletControls
|
|
||||||
label={label}
|
|
||||||
project={props.project}
|
|
||||||
walletAddress={walletAddress}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end">
|
|
||||||
<Link
|
|
||||||
className="inline-flex items-center gap-1 text-sm font-medium text-primary hover:underline"
|
|
||||||
href={`/team/${props.teamSlug}/${props.project.slug}/transactions`}
|
|
||||||
>
|
|
||||||
View Transactions
|
|
||||||
<ChevronRightIcon className="size-4" />
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<ProjectWalletSetup
|
|
||||||
managementAccessToken={props.managementAccessToken}
|
|
||||||
project={props.project}
|
|
||||||
teamSlug={props.teamSlug}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Integrate API key section ------------------------------------------------------------
|
// Integrate API key section ------------------------------------------------------------
|
||||||
|
|
||||||
function IntegrateAPIKeySection({ project }: { project: Project }) {
|
function IntegrateAPIKeySection({ project }: { project: Project }) {
|
||||||
|
|||||||
-747
@@ -1,747 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import {
|
|
||||||
EllipsisVerticalIcon,
|
|
||||||
RefreshCcwIcon,
|
|
||||||
SendIcon,
|
|
||||||
ShuffleIcon,
|
|
||||||
WalletIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { useEffect, useMemo, useState } from "react";
|
|
||||||
import { useForm } from "react-hook-form";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { toWei } from "thirdweb";
|
|
||||||
import { useWalletBalance } from "thirdweb/react";
|
|
||||||
import { isAddress } from "thirdweb/utils";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { listProjectServerWallets } from "@/actions/project-wallet/list-server-wallets";
|
|
||||||
import { sendProjectWalletTokens } from "@/actions/project-wallet/send-tokens";
|
|
||||||
import type { Project } from "@/api/project/projects";
|
|
||||||
import { FundWalletModal } from "@/components/blocks/fund-wallets-modal";
|
|
||||||
import { SingleNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
|
||||||
import { WalletAddress } from "@/components/blocks/wallet-address";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from "@/components/ui/dialog";
|
|
||||||
import {
|
|
||||||
DropdownMenu,
|
|
||||||
DropdownMenuContent,
|
|
||||||
DropdownMenuItem,
|
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from "@/components/ui/dropdown-menu";
|
|
||||||
import {
|
|
||||||
Form,
|
|
||||||
FormControl,
|
|
||||||
FormDescription,
|
|
||||||
FormField,
|
|
||||||
FormItem,
|
|
||||||
FormLabel,
|
|
||||||
FormMessage,
|
|
||||||
} from "@/components/ui/form";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Spinner } from "@/components/ui/Spinner";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
|
||||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
|
||||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
|
||||||
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { updateDefaultProjectWallet } from "../../transactions/lib/vault.client";
|
|
||||||
|
|
||||||
type ProjectWalletControlsProps = {
|
|
||||||
walletAddress: string;
|
|
||||||
label: string;
|
|
||||||
project: Pick<
|
|
||||||
Project,
|
|
||||||
"id" | "publishableKey" | "teamId" | "services" | "name"
|
|
||||||
>;
|
|
||||||
defaultChainId?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function ProjectWalletControls(props: ProjectWalletControlsProps) {
|
|
||||||
const { walletAddress, label, project, defaultChainId } = props;
|
|
||||||
const [isSendOpen, setIsSendOpen] = useState(false);
|
|
||||||
const [isReceiveOpen, setIsReceiveOpen] = useState(false);
|
|
||||||
const [selectedChainId, setSelectedChainId] = useState(defaultChainId ?? 1);
|
|
||||||
const [isChangeWalletOpen, setIsChangeWalletOpen] = useState(false);
|
|
||||||
const [selectedWalletId, setSelectedWalletId] = useState<string | undefined>(
|
|
||||||
undefined,
|
|
||||||
);
|
|
||||||
|
|
||||||
const client = useMemo(() => getClientThirdwebClient(), []);
|
|
||||||
const chain = useV5DashboardChain(selectedChainId);
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const router = useDashboardRouter();
|
|
||||||
|
|
||||||
const engineCloudService = useMemo(
|
|
||||||
() => project.services?.find((service) => service.name === "engineCloud"),
|
|
||||||
[project.services],
|
|
||||||
);
|
|
||||||
const managementAccessToken =
|
|
||||||
engineCloudService?.managementAccessToken ?? undefined;
|
|
||||||
const isManagedVault = !!engineCloudService?.encryptedAdminKey;
|
|
||||||
|
|
||||||
const serverWalletsQuery = useQuery({
|
|
||||||
enabled: !!managementAccessToken,
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!managementAccessToken) {
|
|
||||||
return [] as ProjectWalletSummary[];
|
|
||||||
}
|
|
||||||
|
|
||||||
return listProjectServerWallets({
|
|
||||||
managementAccessToken,
|
|
||||||
projectId: project.id,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
queryKey: ["project", project.id, "server-wallets", managementAccessToken],
|
|
||||||
staleTime: 60_000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const serverWallets = serverWalletsQuery.data ?? [];
|
|
||||||
const currentWalletAddressLower = walletAddress.toLowerCase();
|
|
||||||
const otherWallets = useMemo(() => {
|
|
||||||
return serverWallets.filter((wallet) => {
|
|
||||||
return wallet.address.toLowerCase() !== currentWalletAddressLower;
|
|
||||||
});
|
|
||||||
}, [serverWallets, currentWalletAddressLower]);
|
|
||||||
|
|
||||||
const canChangeWallet = otherWallets.length > 0;
|
|
||||||
|
|
||||||
const handleOpenChangeWallet = () => {
|
|
||||||
const currentWallet = serverWallets.find(
|
|
||||||
(wallet) => wallet.address.toLowerCase() === currentWalletAddressLower,
|
|
||||||
);
|
|
||||||
|
|
||||||
const nextWalletId =
|
|
||||||
otherWallets[0]?.id ?? currentWallet?.id ?? serverWallets[0]?.id;
|
|
||||||
|
|
||||||
setSelectedWalletId(nextWalletId);
|
|
||||||
setIsChangeWalletOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCloseChangeWallet = () => {
|
|
||||||
setIsChangeWalletOpen(false);
|
|
||||||
setSelectedWalletId(undefined);
|
|
||||||
};
|
|
||||||
|
|
||||||
const selectedWallet = useMemo(() => {
|
|
||||||
if (!selectedWalletId) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return serverWallets.find((wallet) => wallet.id === selectedWalletId);
|
|
||||||
}, [selectedWalletId, serverWallets]);
|
|
||||||
|
|
||||||
const isSelectionDifferent = Boolean(
|
|
||||||
selectedWallet &&
|
|
||||||
selectedWallet.address.toLowerCase() !== currentWalletAddressLower,
|
|
||||||
);
|
|
||||||
|
|
||||||
const changeWalletMutation = useMutation({
|
|
||||||
mutationFn: async (wallet: ProjectWalletSummary) => {
|
|
||||||
await updateDefaultProjectWallet({
|
|
||||||
project: project as Project,
|
|
||||||
projectWalletAddress: wallet.address,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
const message =
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: "Failed to update project wallet";
|
|
||||||
toast.error(message);
|
|
||||||
},
|
|
||||||
onSuccess: async (_, wallet) => {
|
|
||||||
const descriptionLabel = wallet.label ?? wallet.address;
|
|
||||||
toast.success("Project wallet updated", {
|
|
||||||
description: `Now pointing to ${descriptionLabel}`,
|
|
||||||
});
|
|
||||||
await queryClient.invalidateQueries({
|
|
||||||
queryKey: [
|
|
||||||
"project",
|
|
||||||
project.id,
|
|
||||||
"server-wallets",
|
|
||||||
managementAccessToken,
|
|
||||||
],
|
|
||||||
});
|
|
||||||
handleCloseChangeWallet();
|
|
||||||
router.refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const balanceQuery = useWalletBalance({
|
|
||||||
address: walletAddress,
|
|
||||||
chain,
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
|
|
||||||
const balanceDisplay = balanceQuery.data
|
|
||||||
? `${balanceQuery.data.displayValue} ${balanceQuery.data.symbol}`
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-5">
|
|
||||||
<div className="rounded-lg border border-border bg-background p-3">
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<div className="flex flex-col gap-3 lg:flex-row">
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-muted-foreground text-xs">Address</p>
|
|
||||||
<WalletAddress address={walletAddress} client={client} />
|
|
||||||
</div>
|
|
||||||
<div className="flex-1">
|
|
||||||
<p className="text-muted-foreground text-xs">Label</p>
|
|
||||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
|
||||||
<p className="font-mono text-sm break-all py-2 sm:py-0">
|
|
||||||
{label}
|
|
||||||
</p>
|
|
||||||
{canChangeWallet && (
|
|
||||||
<Button
|
|
||||||
className="h-8 gap-1 sm:ml-4"
|
|
||||||
onClick={handleOpenChangeWallet}
|
|
||||||
size="sm"
|
|
||||||
disabled={serverWalletsQuery.isLoading}
|
|
||||||
variant="outline"
|
|
||||||
>
|
|
||||||
<ShuffleIcon className="size-3.5" />
|
|
||||||
Change default
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
|
|
||||||
<div className="flex-1 flex-col">
|
|
||||||
<p className="text-xs text-muted-foreground pb-2">Balance</p>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WalletIcon className="size-4 text-muted-foreground" />
|
|
||||||
{balanceQuery.isLoading ? (
|
|
||||||
<Spinner className="size-4" />
|
|
||||||
) : balanceDisplay ? (
|
|
||||||
<span className="text-md tracking-tight">
|
|
||||||
{balanceDisplay}
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted-foreground text-sm">N/A</span>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
aria-label="Refresh balance"
|
|
||||||
className="h-8 w-8 p-0"
|
|
||||||
disabled={balanceQuery.isFetching}
|
|
||||||
onClick={() => balanceQuery.refetch()}
|
|
||||||
size="icon"
|
|
||||||
variant="outline"
|
|
||||||
>
|
|
||||||
<RefreshCcwIcon
|
|
||||||
className={cn(
|
|
||||||
"size-4",
|
|
||||||
balanceQuery.isFetching && "animate-spin",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<Button
|
|
||||||
aria-label="Open wallet actions"
|
|
||||||
className="h-9 w-9"
|
|
||||||
size="icon"
|
|
||||||
variant="outline"
|
|
||||||
>
|
|
||||||
<EllipsisVerticalIcon className="size-4" />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end" className="w-48 rounded-xl">
|
|
||||||
<DropdownMenuItem
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
onSelect={() => setIsSendOpen(true)}
|
|
||||||
>
|
|
||||||
<SendIcon className="size-4 text-muted-foreground" />
|
|
||||||
Send funds
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
onSelect={() => setIsReceiveOpen(true)}
|
|
||||||
>
|
|
||||||
<WalletIcon className="size-4 text-muted-foreground" />
|
|
||||||
Receive funds
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="flex-col flex-1">
|
|
||||||
<p className="text-xs text-muted-foreground pb-2">Network</p>
|
|
||||||
<SingleNetworkSelector
|
|
||||||
chainId={selectedChainId}
|
|
||||||
className="max-w-xs rounded-lg"
|
|
||||||
client={client}
|
|
||||||
disableDeprecated
|
|
||||||
disableChainId
|
|
||||||
onChange={setSelectedChainId}
|
|
||||||
placeholder="Select network"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<SendProjectWalletModal
|
|
||||||
chainId={selectedChainId}
|
|
||||||
client={client}
|
|
||||||
isManagedVault={isManagedVault}
|
|
||||||
label={label}
|
|
||||||
onClose={() => setIsSendOpen(false)}
|
|
||||||
onSuccess={() => balanceQuery.refetch()}
|
|
||||||
open={isSendOpen}
|
|
||||||
publishableKey={project.publishableKey}
|
|
||||||
teamId={project.teamId}
|
|
||||||
walletAddress={walletAddress}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FundWalletModal
|
|
||||||
checkoutWidgetTitle={`Fund ${label}`}
|
|
||||||
client={client}
|
|
||||||
defaultChainId={selectedChainId}
|
|
||||||
description="Use your card or crypto to deposit into this server wallet"
|
|
||||||
onOpenChange={setIsReceiveOpen}
|
|
||||||
open={isReceiveOpen}
|
|
||||||
recipientAddress={walletAddress}
|
|
||||||
title="Fund project wallet"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Dialog
|
|
||||||
onOpenChange={(nextOpen) => {
|
|
||||||
if (!nextOpen) {
|
|
||||||
handleCloseChangeWallet();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
open={isChangeWalletOpen}
|
|
||||||
>
|
|
||||||
<DialogContent className="gap-0 p-0">
|
|
||||||
<DialogHeader className="p-4 lg:p-6">
|
|
||||||
<DialogTitle>Change default wallet</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Choose another server wallet to use as the default for this
|
|
||||||
project.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<div className="px-4 pb-8 lg:px-6">
|
|
||||||
{serverWalletsQuery.isLoading ? (
|
|
||||||
<div className="flex justify-center py-6">
|
|
||||||
<Spinner className="size-5" />
|
|
||||||
</div>
|
|
||||||
) : serverWallets.length <= 1 ? (
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
You need at least two server wallets to pick a different
|
|
||||||
default.
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-col gap-3">
|
|
||||||
<Select
|
|
||||||
onValueChange={(value) => setSelectedWalletId(value)}
|
|
||||||
value={selectedWalletId ?? ""}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="w-full">
|
|
||||||
<SelectValue placeholder="Select server wallet">
|
|
||||||
{selectedWallet ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WalletAddress
|
|
||||||
address={selectedWallet.address}
|
|
||||||
client={client}
|
|
||||||
/>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm text-foreground">
|
|
||||||
{selectedWallet.label ?? "Unnamed server wallet"}
|
|
||||||
</span>
|
|
||||||
{selectedWallet.address.toLowerCase() ===
|
|
||||||
currentWalletAddressLower && (
|
|
||||||
<Badge variant="success" className="text-xs">
|
|
||||||
current
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
"Select server wallet"
|
|
||||||
)}
|
|
||||||
</SelectValue>
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{serverWallets.map((wallet) => {
|
|
||||||
const isCurrent =
|
|
||||||
wallet.address.toLowerCase() ===
|
|
||||||
currentWalletAddressLower;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SelectItem key={wallet.id} value={wallet.id}>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WalletAddress
|
|
||||||
address={wallet.address}
|
|
||||||
client={client}
|
|
||||||
/>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm text-foreground">
|
|
||||||
{wallet.label ?? "Unnamed server wallet"}
|
|
||||||
</span>
|
|
||||||
{isCurrent && (
|
|
||||||
<Badge variant="success" className="text-xs">
|
|
||||||
current
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</SelectItem>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<DialogFooter className="flex justify-end gap-3 border-t bg-card p-4 lg:p-6">
|
|
||||||
<Button
|
|
||||||
onClick={handleCloseChangeWallet}
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
disabled={changeWalletMutation.isPending}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
disabled={
|
|
||||||
!selectedWallet ||
|
|
||||||
!isSelectionDifferent ||
|
|
||||||
changeWalletMutation.isPending
|
|
||||||
}
|
|
||||||
onClick={() => {
|
|
||||||
if (selectedWallet) {
|
|
||||||
changeWalletMutation.mutate(selectedWallet);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{changeWalletMutation.isPending && (
|
|
||||||
<Spinner className="mr-2 size-4" />
|
|
||||||
)}
|
|
||||||
Save default
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const createSendFormSchema = (secretKeyLabel: string) =>
|
|
||||||
z.object({
|
|
||||||
chainId: z.number({
|
|
||||||
required_error: "Select a network",
|
|
||||||
}),
|
|
||||||
toAddress: z
|
|
||||||
.string()
|
|
||||||
.trim()
|
|
||||||
.min(1, "Destination address is required")
|
|
||||||
.refine((value) => Boolean(isAddress(value)), {
|
|
||||||
message: "Enter a valid wallet address",
|
|
||||||
}),
|
|
||||||
amount: z.string().trim().min(1, "Amount is required"),
|
|
||||||
secretKey: z.string().trim().min(1, `${secretKeyLabel} is required`),
|
|
||||||
vaultAccessToken: z.string().trim(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const SECRET_KEY_LABEL = "Project secret key";
|
|
||||||
|
|
||||||
type SendFormValues = z.infer<ReturnType<typeof createSendFormSchema>>;
|
|
||||||
|
|
||||||
function SendProjectWalletModal(props: {
|
|
||||||
open: boolean;
|
|
||||||
onClose: () => void;
|
|
||||||
onSuccess: () => void;
|
|
||||||
walletAddress: string;
|
|
||||||
publishableKey: string;
|
|
||||||
teamId: string;
|
|
||||||
chainId: number;
|
|
||||||
label: string;
|
|
||||||
client: ReturnType<typeof getClientThirdwebClient>;
|
|
||||||
isManagedVault: boolean;
|
|
||||||
}) {
|
|
||||||
const {
|
|
||||||
open,
|
|
||||||
onClose,
|
|
||||||
onSuccess,
|
|
||||||
walletAddress,
|
|
||||||
publishableKey,
|
|
||||||
teamId,
|
|
||||||
chainId,
|
|
||||||
label,
|
|
||||||
client,
|
|
||||||
isManagedVault,
|
|
||||||
} = props;
|
|
||||||
|
|
||||||
const secretKeyLabel = SECRET_KEY_LABEL;
|
|
||||||
const secretKeyPlaceholder = "Enter your project secret key";
|
|
||||||
const secretKeyHelper =
|
|
||||||
"Your project secret key was generated when you created your project. If you lost it, regenerate one from Project settings.";
|
|
||||||
const vaultAccessTokenHelper =
|
|
||||||
"Vault access tokens are optional credentials with server wallet permissions. Manage them in Vault settings.";
|
|
||||||
|
|
||||||
const formSchema = useMemo(() => createSendFormSchema(SECRET_KEY_LABEL), []);
|
|
||||||
|
|
||||||
const form = useForm<SendFormValues>({
|
|
||||||
defaultValues: {
|
|
||||||
amount: "0",
|
|
||||||
chainId,
|
|
||||||
secretKey: "",
|
|
||||||
vaultAccessToken: "",
|
|
||||||
toAddress: "",
|
|
||||||
},
|
|
||||||
mode: "onChange",
|
|
||||||
resolver: zodResolver(formSchema),
|
|
||||||
});
|
|
||||||
|
|
||||||
const selectedChain = useV5DashboardChain(form.watch("chainId"));
|
|
||||||
|
|
||||||
// eslint-disable-next-line no-restricted-syntax -- form submission chainId must track selector state
|
|
||||||
useEffect(() => {
|
|
||||||
form.setValue("chainId", chainId);
|
|
||||||
}, [chainId, form]);
|
|
||||||
|
|
||||||
// eslint-disable-next-line no-restricted-syntax -- reset cached inputs when modal closes to avoid leaking state
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) {
|
|
||||||
const currentValues = form.getValues();
|
|
||||||
form.reset({
|
|
||||||
amount: "0",
|
|
||||||
chainId,
|
|
||||||
secretKey: currentValues.secretKey ?? "",
|
|
||||||
vaultAccessToken: currentValues.vaultAccessToken ?? "",
|
|
||||||
toAddress: "",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [open, chainId, form]);
|
|
||||||
|
|
||||||
const sendMutation = useMutation({
|
|
||||||
mutationFn: async (values: SendFormValues) => {
|
|
||||||
const quantityWei = toWei(values.amount).toString();
|
|
||||||
const secretKeyValue = values.secretKey.trim();
|
|
||||||
const vaultAccessTokenValue = values.vaultAccessToken.trim();
|
|
||||||
|
|
||||||
const result = await sendProjectWalletTokens({
|
|
||||||
chainId: values.chainId,
|
|
||||||
publishableKey,
|
|
||||||
quantityWei,
|
|
||||||
recipientAddress: values.toAddress,
|
|
||||||
teamId,
|
|
||||||
walletAddress,
|
|
||||||
secretKey: secretKeyValue,
|
|
||||||
...(vaultAccessTokenValue
|
|
||||||
? { vaultAccessToken: vaultAccessTokenValue }
|
|
||||||
: {}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result.ok) {
|
|
||||||
const errorMessage =
|
|
||||||
typeof result.error === "string"
|
|
||||||
? result.error
|
|
||||||
: "Failed to send funds";
|
|
||||||
throw new Error(errorMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result.transactionIds;
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
toast.error(error.message);
|
|
||||||
},
|
|
||||||
onSuccess: (transactionIds) => {
|
|
||||||
toast.success("Transfer submitted", {
|
|
||||||
description:
|
|
||||||
transactionIds && transactionIds.length > 0
|
|
||||||
? `Transaction ID: ${transactionIds[0]}`
|
|
||||||
: undefined,
|
|
||||||
});
|
|
||||||
onSuccess();
|
|
||||||
onClose();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Dialog
|
|
||||||
onOpenChange={(nextOpen) => {
|
|
||||||
if (!nextOpen) {
|
|
||||||
onClose();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
open={open}
|
|
||||||
>
|
|
||||||
<DialogContent className="gap-0 p-0">
|
|
||||||
<DialogHeader className="p-4 lg:p-6">
|
|
||||||
<DialogTitle>Send from {label}</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Execute a one-off transfer using your server wallet.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
<Form {...form}>
|
|
||||||
<form
|
|
||||||
onSubmit={form.handleSubmit((values) => {
|
|
||||||
void sendMutation.mutateAsync(values);
|
|
||||||
})}
|
|
||||||
>
|
|
||||||
<div className="space-y-4 px-4 pb-8 lg:px-6">
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="chainId"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>Network</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<SingleNetworkSelector
|
|
||||||
chainId={field.value}
|
|
||||||
className="bg-card"
|
|
||||||
client={client}
|
|
||||||
disableDeprecated
|
|
||||||
onChange={(nextChainId) => {
|
|
||||||
field.onChange(nextChainId);
|
|
||||||
}}
|
|
||||||
placeholder="Select network"
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="toAddress"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>Send to</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
autoComplete="off"
|
|
||||||
placeholder="0x..."
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="amount"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>Amount</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
inputMode="decimal"
|
|
||||||
min="0"
|
|
||||||
step="any"
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
<FormDescription>
|
|
||||||
Sending native token
|
|
||||||
{selectedChain?.nativeCurrency?.symbol
|
|
||||||
? ` (${selectedChain.nativeCurrency.symbol})`
|
|
||||||
: ""}
|
|
||||||
</FormDescription>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="secretKey"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>{secretKeyLabel}</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
autoComplete="off"
|
|
||||||
autoCorrect="off"
|
|
||||||
placeholder={secretKeyPlaceholder}
|
|
||||||
spellCheck={false}
|
|
||||||
type="password"
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
<FormDescription>{secretKeyHelper}</FormDescription>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{!isManagedVault && (
|
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="vaultAccessToken"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>
|
|
||||||
Vault access token
|
|
||||||
<span className="text-muted-foreground">
|
|
||||||
{" "}
|
|
||||||
(optional)
|
|
||||||
</span>
|
|
||||||
</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input
|
|
||||||
autoComplete="off"
|
|
||||||
autoCorrect="off"
|
|
||||||
placeholder="Enter a vault access token (optional)"
|
|
||||||
spellCheck={false}
|
|
||||||
type="password"
|
|
||||||
{...field}
|
|
||||||
/>
|
|
||||||
</FormControl>
|
|
||||||
<FormDescription>
|
|
||||||
{vaultAccessTokenHelper}
|
|
||||||
</FormDescription>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end gap-3 border-t bg-card p-4 lg:p-6">
|
|
||||||
<Button onClick={onClose} type="button" variant="outline">
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="gap-2"
|
|
||||||
disabled={!form.formState.isValid || sendMutation.isPending}
|
|
||||||
type="submit"
|
|
||||||
>
|
|
||||||
{sendMutation.isPending && <Spinner className="size-4" />}
|
|
||||||
Submit transfer
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</Form>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
-215
@@ -1,215 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { CircleAlertIcon } from "lucide-react";
|
|
||||||
import { useMemo, useState } from "react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import { listProjectServerWallets } from "@/actions/project-wallet/list-server-wallets";
|
|
||||||
import type { Project } from "@/api/project/projects";
|
|
||||||
import { WalletAddress } from "@/components/blocks/wallet-address";
|
|
||||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Spinner } from "@/components/ui/Spinner";
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from "@/components/ui/select";
|
|
||||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
|
||||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
|
||||||
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
|
||||||
import { updateDefaultProjectWallet } from "../../transactions/lib/vault.client";
|
|
||||||
import CreateServerWallet from "../../transactions/server-wallets/components/create-server-wallet.client";
|
|
||||||
|
|
||||||
export function ProjectWalletSetup(props: {
|
|
||||||
project: Project;
|
|
||||||
teamSlug: string;
|
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
}) {
|
|
||||||
const { project, teamSlug, managementAccessToken } = props;
|
|
||||||
const router = useDashboardRouter();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const client = useMemo(() => getClientThirdwebClient(), []);
|
|
||||||
const [selectedWalletId, setSelectedWalletId] = useState<string | undefined>(
|
|
||||||
undefined,
|
|
||||||
);
|
|
||||||
|
|
||||||
const serverWalletsQuery = useQuery({
|
|
||||||
enabled: Boolean(managementAccessToken),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!managementAccessToken) {
|
|
||||||
return [] as ProjectWalletSummary[];
|
|
||||||
}
|
|
||||||
|
|
||||||
return listProjectServerWallets({
|
|
||||||
managementAccessToken,
|
|
||||||
projectId: project.id,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
queryKey: ["project", project.id, "server-wallets", managementAccessToken],
|
|
||||||
staleTime: 60_000,
|
|
||||||
});
|
|
||||||
|
|
||||||
const serverWallets = serverWalletsQuery.data ?? [];
|
|
||||||
|
|
||||||
const effectiveSelectedWalletId = useMemo(() => {
|
|
||||||
if (
|
|
||||||
selectedWalletId &&
|
|
||||||
serverWallets.some((wallet) => wallet.id === selectedWalletId)
|
|
||||||
) {
|
|
||||||
return selectedWalletId;
|
|
||||||
}
|
|
||||||
|
|
||||||
return serverWallets[0]?.id;
|
|
||||||
}, [selectedWalletId, serverWallets]);
|
|
||||||
|
|
||||||
const selectedWallet = useMemo(() => {
|
|
||||||
if (!effectiveSelectedWalletId) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
return serverWallets.find(
|
|
||||||
(wallet) => wallet.id === effectiveSelectedWalletId,
|
|
||||||
);
|
|
||||||
}, [effectiveSelectedWalletId, serverWallets]);
|
|
||||||
|
|
||||||
const setDefaultWalletMutation = useMutation({
|
|
||||||
mutationFn: async (wallet: ProjectWalletSummary) => {
|
|
||||||
await updateDefaultProjectWallet({
|
|
||||||
project,
|
|
||||||
projectWalletAddress: wallet.address,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
const message =
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: "Failed to update project wallet";
|
|
||||||
toast.error(message);
|
|
||||||
},
|
|
||||||
onSuccess: async (_, wallet) => {
|
|
||||||
const descriptionLabel = wallet.label ?? wallet.address;
|
|
||||||
toast.success("Project wallet updated", {
|
|
||||||
description: `Now pointing to ${descriptionLabel}`,
|
|
||||||
});
|
|
||||||
await queryClient.invalidateQueries({
|
|
||||||
queryKey: [
|
|
||||||
"project",
|
|
||||||
project.id,
|
|
||||||
"server-wallets",
|
|
||||||
managementAccessToken,
|
|
||||||
],
|
|
||||||
});
|
|
||||||
router.refresh();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const canSelectExisting =
|
|
||||||
Boolean(managementAccessToken) && serverWallets.length > 0;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Alert variant="info">
|
|
||||||
<CircleAlertIcon className="size-5" />
|
|
||||||
<AlertTitle>No project wallet set</AlertTitle>
|
|
||||||
<AlertDescription>
|
|
||||||
Set a project wallet to use for dashboard and API integrations.
|
|
||||||
</AlertDescription>
|
|
||||||
|
|
||||||
<div className="mt-4 space-y-5">
|
|
||||||
{serverWalletsQuery.isLoading ? (
|
|
||||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
|
||||||
<Spinner className="size-4" />
|
|
||||||
<span>Loading existing server wallets…</span>
|
|
||||||
</div>
|
|
||||||
) : canSelectExisting ? (
|
|
||||||
<div className="space-y-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-sm font-medium text-foreground">
|
|
||||||
Choose an existing server wallet
|
|
||||||
</p>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
These wallets were already created for this project. Pick one to
|
|
||||||
set as the default.
|
|
||||||
</p>
|
|
||||||
<Select
|
|
||||||
onValueChange={(value) => setSelectedWalletId(value)}
|
|
||||||
value={effectiveSelectedWalletId ?? ""}
|
|
||||||
>
|
|
||||||
<SelectTrigger className="w-full">
|
|
||||||
<SelectValue placeholder="Select server wallet">
|
|
||||||
{selectedWallet ? (
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WalletAddress
|
|
||||||
address={selectedWallet.address}
|
|
||||||
client={client}
|
|
||||||
/>
|
|
||||||
<span className="text-muted-foreground text-sm">
|
|
||||||
{selectedWallet.label ?? "Unnamed server wallet"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
"Select server wallet"
|
|
||||||
)}
|
|
||||||
</SelectValue>
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{serverWallets.map((wallet) => (
|
|
||||||
<SelectItem key={wallet.id} value={wallet.id}>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WalletAddress
|
|
||||||
address={wallet.address}
|
|
||||||
client={client}
|
|
||||||
/>
|
|
||||||
<span className="text-muted-foreground text-sm">
|
|
||||||
{wallet.label ?? "Unnamed server wallet"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
|
||||||
<Button
|
|
||||||
disabled={!selectedWallet || setDefaultWalletMutation.isPending}
|
|
||||||
onClick={() => {
|
|
||||||
if (selectedWallet) {
|
|
||||||
setDefaultWalletMutation.mutate(selectedWallet);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
{setDefaultWalletMutation.isPending && (
|
|
||||||
<Spinner className="mr-2 size-4" />
|
|
||||||
)}
|
|
||||||
Set as project wallet
|
|
||||||
</Button>
|
|
||||||
<CreateServerWallet
|
|
||||||
managementAccessToken={managementAccessToken}
|
|
||||||
project={project}
|
|
||||||
teamSlug={teamSlug}
|
|
||||||
setAsProjectWallet
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3 text-sm text-muted-foreground">
|
|
||||||
<p>
|
|
||||||
Create a server wallet to start using transactions and other
|
|
||||||
project features.
|
|
||||||
</p>
|
|
||||||
<CreateServerWallet
|
|
||||||
managementAccessToken={managementAccessToken}
|
|
||||||
project={project}
|
|
||||||
teamSlug={teamSlug}
|
|
||||||
setAsProjectWallet
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</Alert>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+736
@@ -0,0 +1,736 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
ArrowLeftRightIcon,
|
||||||
|
EllipsisVerticalIcon,
|
||||||
|
RefreshCcwIcon,
|
||||||
|
SendIcon,
|
||||||
|
ShuffleIcon,
|
||||||
|
WalletIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { type ThirdwebClient, toWei } from "thirdweb";
|
||||||
|
import { useWalletBalance } from "thirdweb/react";
|
||||||
|
import { isAddress } from "thirdweb/utils";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { sendProjectWalletTokens } from "@/actions/project-wallet/send-tokens";
|
||||||
|
import type { Project } from "@/api/project/projects";
|
||||||
|
import { FundWalletModal } from "@/components/blocks/fund-wallets-modal";
|
||||||
|
import { SingleNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
||||||
|
import { WalletAddress } from "@/components/blocks/wallet-address";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
FormControl,
|
||||||
|
FormDescription,
|
||||||
|
FormField,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormMessage,
|
||||||
|
} from "@/components/ui/form";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Spinner } from "@/components/ui/Spinner";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import type { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||||
|
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||||
|
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||||
|
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { updateDefaultProjectWallet } from "../../transactions/lib/vault.client";
|
||||||
|
|
||||||
|
type GetProjectServerWallets = (params: {
|
||||||
|
managementAccessToken: string;
|
||||||
|
projectId: string;
|
||||||
|
}) => Promise<ProjectWalletSummary[]>;
|
||||||
|
|
||||||
|
type ProjectWalletControlsProps = {
|
||||||
|
projectWallet: ProjectWalletSummary;
|
||||||
|
project: Project;
|
||||||
|
defaultChainId?: number;
|
||||||
|
teamSlug: string;
|
||||||
|
getProjectServerWallets: GetProjectServerWallets;
|
||||||
|
client: ThirdwebClient;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ProjectWalletDetailsSection(props: ProjectWalletControlsProps) {
|
||||||
|
const { projectWallet, project, defaultChainId } = props;
|
||||||
|
const [isSendOpen, setIsSendOpen] = useState(false);
|
||||||
|
const [isReceiveOpen, setIsReceiveOpen] = useState(false);
|
||||||
|
const [selectedChainId, setSelectedChainId] = useState(defaultChainId ?? 1);
|
||||||
|
const [isChangeWalletOpen, setIsChangeWalletOpen] = useState(false);
|
||||||
|
|
||||||
|
const chain = useV5DashboardChain(selectedChainId);
|
||||||
|
|
||||||
|
const engineCloudService = useMemo(
|
||||||
|
() => project.services?.find((service) => service.name === "engineCloud"),
|
||||||
|
[project.services],
|
||||||
|
);
|
||||||
|
|
||||||
|
const managementAccessToken =
|
||||||
|
engineCloudService?.managementAccessToken ?? undefined;
|
||||||
|
|
||||||
|
const isManagedVault = !!engineCloudService?.encryptedAdminKey;
|
||||||
|
|
||||||
|
const serverWalletsQuery = useQuery({
|
||||||
|
enabled: !!managementAccessToken,
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!managementAccessToken) {
|
||||||
|
return [] as ProjectWalletSummary[];
|
||||||
|
}
|
||||||
|
|
||||||
|
return props.getProjectServerWallets({
|
||||||
|
managementAccessToken,
|
||||||
|
projectId: project.id,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
queryKey: ["project", project.id, "server-wallets", managementAccessToken],
|
||||||
|
staleTime: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const balanceQuery = useWalletBalance({
|
||||||
|
address: projectWallet.address,
|
||||||
|
chain,
|
||||||
|
client: props.client,
|
||||||
|
});
|
||||||
|
|
||||||
|
const canChangeWallet =
|
||||||
|
serverWalletsQuery.data && serverWalletsQuery.data.length > 1;
|
||||||
|
|
||||||
|
const router = useDashboardRouter();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="rounded-xl border border-border bg-card relative">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
aria-label="Open wallet actions"
|
||||||
|
className="p-2 h-auto w-auto absolute right-4 top-4 z-10"
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<EllipsisVerticalIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-64 rounded-xl">
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
onSelect={() => setIsSendOpen(true)}
|
||||||
|
>
|
||||||
|
<SendIcon className="size-4 text-muted-foreground" />
|
||||||
|
Send funds
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
onSelect={() => setIsReceiveOpen(true)}
|
||||||
|
>
|
||||||
|
<WalletIcon className="size-4 text-muted-foreground" />
|
||||||
|
Receive funds
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
onSelect={() =>
|
||||||
|
router.push(
|
||||||
|
`/team/${props.teamSlug}/${props.project.slug}/transactions`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ArrowLeftRightIcon className="size-4 text-muted-foreground" />
|
||||||
|
View transactions
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
{canChangeWallet && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="flex items-center gap-2"
|
||||||
|
onSelect={() => setIsChangeWalletOpen(true)}
|
||||||
|
>
|
||||||
|
<ShuffleIcon className="size-4 text-muted-foreground" />
|
||||||
|
Change project wallet
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
|
||||||
|
<div className="p-4 relative flex flex-col gap-5">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-foreground mb-1">Wallet Address</p>
|
||||||
|
<CopyTextButton
|
||||||
|
textToShow={projectWallet.address}
|
||||||
|
textToCopy={projectWallet.address}
|
||||||
|
tooltip="Copy wallet address"
|
||||||
|
copyIconPosition="right"
|
||||||
|
variant="ghost"
|
||||||
|
className="text-muted-foreground -translate-x-1.5 py-0 h-auto"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-foreground mb-1">Wallet Label</p>
|
||||||
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<p className="text-sm break-all py-2 sm:py-0 text-muted-foreground">
|
||||||
|
{projectWallet.label || "N/A"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-4 border-t border-dashed flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-foreground mb-1">Balance</p>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{balanceQuery.isFetching || !balanceQuery.data ? (
|
||||||
|
<Skeleton className="h-5 w-[100px]" />
|
||||||
|
) : (
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
{balanceQuery.data.displayValue} {balanceQuery.data.symbol}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button
|
||||||
|
aria-label="Refresh balance"
|
||||||
|
className="p-1 h-auto w-auto"
|
||||||
|
disabled={balanceQuery.isFetching}
|
||||||
|
onClick={() => balanceQuery.refetch()}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<RefreshCcwIcon
|
||||||
|
className={cn(
|
||||||
|
"size-3 text-muted-foreground",
|
||||||
|
balanceQuery.isFetching && "animate-spin",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SingleNetworkSelector
|
||||||
|
chainId={selectedChainId}
|
||||||
|
className="w-fit rounded-full bg-background hover:bg-accent/50"
|
||||||
|
client={props.client}
|
||||||
|
disableDeprecated
|
||||||
|
disableChainId
|
||||||
|
onChange={setSelectedChainId}
|
||||||
|
placeholder="Select network"
|
||||||
|
popoverContentClassName="!w-[320px] rounded-xl overflow-hidden"
|
||||||
|
align="end"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SendProjectWalletModal
|
||||||
|
chainId={selectedChainId}
|
||||||
|
client={props.client}
|
||||||
|
isManagedVault={isManagedVault}
|
||||||
|
label={projectWallet.label || ""}
|
||||||
|
onClose={() => setIsSendOpen(false)}
|
||||||
|
onSuccess={() => balanceQuery.refetch()}
|
||||||
|
open={isSendOpen}
|
||||||
|
publishableKey={project.publishableKey}
|
||||||
|
teamId={project.teamId}
|
||||||
|
walletAddress={projectWallet.address}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FundWalletModal
|
||||||
|
checkoutWidgetTitle="Fund Project Wallet"
|
||||||
|
client={props.client}
|
||||||
|
defaultChainId={selectedChainId}
|
||||||
|
description="Use your card or crypto to deposit into this server wallet"
|
||||||
|
onOpenChange={setIsReceiveOpen}
|
||||||
|
open={isReceiveOpen}
|
||||||
|
recipientAddress={projectWallet.address}
|
||||||
|
title="Fund project wallet"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Dialog onOpenChange={setIsChangeWalletOpen} open={isChangeWalletOpen}>
|
||||||
|
<DialogContent className="gap-0 p-0 overflow-hidden">
|
||||||
|
<ChangeProjectWalletDialogContent
|
||||||
|
isOpen={isChangeWalletOpen}
|
||||||
|
setIsOpen={setIsChangeWalletOpen}
|
||||||
|
serverWallets={{
|
||||||
|
data: serverWalletsQuery.data ?? [],
|
||||||
|
isPending: serverWalletsQuery.isLoading,
|
||||||
|
}}
|
||||||
|
projectWallet={projectWallet}
|
||||||
|
client={props.client}
|
||||||
|
project={project}
|
||||||
|
managementAccessToken={managementAccessToken}
|
||||||
|
/>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChangeProjectWalletDialogContent(props: {
|
||||||
|
isOpen: boolean;
|
||||||
|
setIsOpen: (isOpen: boolean) => void;
|
||||||
|
serverWallets: {
|
||||||
|
data: ProjectWalletSummary[];
|
||||||
|
isPending: boolean;
|
||||||
|
};
|
||||||
|
projectWallet: ProjectWalletSummary;
|
||||||
|
managementAccessToken: string | undefined;
|
||||||
|
project: Project;
|
||||||
|
client: ThirdwebClient;
|
||||||
|
}) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const router = useDashboardRouter();
|
||||||
|
|
||||||
|
const [selectedWalletId, setSelectedWalletId] = useState<string | undefined>(
|
||||||
|
props.projectWallet.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
const serverWallets = props.serverWallets.data;
|
||||||
|
|
||||||
|
const currentWalletAddressLower = props.projectWallet.address.toLowerCase();
|
||||||
|
|
||||||
|
const selectedWallet = useMemo(() => {
|
||||||
|
if (!selectedWalletId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serverWallets.find((wallet) => wallet.id === selectedWalletId);
|
||||||
|
}, [selectedWalletId, serverWallets]);
|
||||||
|
|
||||||
|
const isSelectionDifferent = Boolean(
|
||||||
|
selectedWallet &&
|
||||||
|
selectedWallet.address.toLowerCase() !== currentWalletAddressLower,
|
||||||
|
);
|
||||||
|
|
||||||
|
const changeWalletMutation = useMutation({
|
||||||
|
mutationFn: async (wallet: ProjectWalletSummary) => {
|
||||||
|
await updateDefaultProjectWallet({
|
||||||
|
project: props.project,
|
||||||
|
projectWalletAddress: wallet.address,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
const message =
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to update project wallet";
|
||||||
|
toast.error(message);
|
||||||
|
},
|
||||||
|
onSuccess: async () => {
|
||||||
|
toast.success("Project wallet updated");
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: [
|
||||||
|
"project",
|
||||||
|
props.project.id,
|
||||||
|
"server-wallets",
|
||||||
|
props.managementAccessToken,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
router.refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<DialogHeader className="p-4 lg:p-6">
|
||||||
|
<DialogTitle>Change Project Wallet</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Choose a server wallet to use as project wallet
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="px-4 pb-8 lg:px-6">
|
||||||
|
{props.serverWallets.isPending ? (
|
||||||
|
<div className="flex justify-center py-6">
|
||||||
|
<Spinner className="size-5" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<Select
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSelectedWalletId(value);
|
||||||
|
}}
|
||||||
|
value={selectedWalletId ?? ""}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full">
|
||||||
|
<SelectValue placeholder="Select server wallet">
|
||||||
|
{selectedWallet ? (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<WalletAddress
|
||||||
|
address={selectedWallet.address}
|
||||||
|
client={props.client}
|
||||||
|
/>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm text-foreground">
|
||||||
|
{selectedWallet.label ?? "Unnamed server wallet"}
|
||||||
|
</span>
|
||||||
|
{selectedWallet.address.toLowerCase() ===
|
||||||
|
currentWalletAddressLower && (
|
||||||
|
<Badge variant="success" className="text-xs">
|
||||||
|
current
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
"Select server wallet"
|
||||||
|
)}
|
||||||
|
</SelectValue>
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{serverWallets.map((wallet) => {
|
||||||
|
const isCurrent =
|
||||||
|
wallet.address.toLowerCase() === currentWalletAddressLower;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SelectItem key={wallet.id} value={wallet.id}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<WalletAddress
|
||||||
|
address={wallet.address}
|
||||||
|
client={props.client}
|
||||||
|
/>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm text-foreground">
|
||||||
|
{wallet.label ?? "Unnamed server wallet"}
|
||||||
|
</span>
|
||||||
|
{isCurrent && (
|
||||||
|
<Badge variant="success" className="text-xs">
|
||||||
|
current
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</SelectItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-3 border-t bg-card p-4 lg:p-6">
|
||||||
|
<Button
|
||||||
|
onClick={() => props.setIsOpen(false)}
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={changeWalletMutation.isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
disabled={
|
||||||
|
!selectedWallet ||
|
||||||
|
!isSelectionDifferent ||
|
||||||
|
changeWalletMutation.isPending
|
||||||
|
}
|
||||||
|
onClick={() => {
|
||||||
|
if (selectedWallet) {
|
||||||
|
changeWalletMutation.mutate(selectedWallet);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{changeWalletMutation.isPending && (
|
||||||
|
<Spinner className="mr-2 size-4" />
|
||||||
|
)}
|
||||||
|
Set as project wallet
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const createSendFormSchema = (secretKeyLabel: string) =>
|
||||||
|
z.object({
|
||||||
|
chainId: z.number({
|
||||||
|
required_error: "Select a network",
|
||||||
|
}),
|
||||||
|
toAddress: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(1, "Destination address is required")
|
||||||
|
.refine((value) => Boolean(isAddress(value)), {
|
||||||
|
message: "Enter a valid wallet address",
|
||||||
|
}),
|
||||||
|
amount: z.string().trim().min(1, "Amount is required"),
|
||||||
|
secretKey: z.string().trim().min(1, `${secretKeyLabel} is required`),
|
||||||
|
vaultAccessToken: z.string().trim(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const SECRET_KEY_LABEL = "Project secret key";
|
||||||
|
|
||||||
|
type SendFormValues = z.infer<ReturnType<typeof createSendFormSchema>>;
|
||||||
|
|
||||||
|
type SendProjectWalletModalProps = {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
onSuccess: () => void;
|
||||||
|
walletAddress: string;
|
||||||
|
publishableKey: string;
|
||||||
|
teamId: string;
|
||||||
|
chainId: number;
|
||||||
|
label: string;
|
||||||
|
client: ReturnType<typeof getClientThirdwebClient>;
|
||||||
|
isManagedVault: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const secretKeyLabel = SECRET_KEY_LABEL;
|
||||||
|
const secretKeyPlaceholder = "Enter your project secret key";
|
||||||
|
const secretKeyHelper =
|
||||||
|
"Your project secret key was generated when you created your project. If you lost it, regenerate one from Project settings.";
|
||||||
|
const vaultAccessTokenHelper =
|
||||||
|
"Vault access tokens are optional credentials with server wallet permissions. Manage them in Vault settings.";
|
||||||
|
|
||||||
|
function SendProjectWalletModal(props: SendProjectWalletModalProps) {
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
onOpenChange={(nextOpen) => {
|
||||||
|
if (!nextOpen) {
|
||||||
|
props.onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
open={props.open}
|
||||||
|
>
|
||||||
|
<DialogContent className="gap-0 p-0 overflow-hidden">
|
||||||
|
<SendProjectWalletModalContent {...props} />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SendProjectWalletModalContent(props: SendProjectWalletModalProps) {
|
||||||
|
const {
|
||||||
|
onClose,
|
||||||
|
onSuccess,
|
||||||
|
walletAddress,
|
||||||
|
publishableKey,
|
||||||
|
teamId,
|
||||||
|
chainId,
|
||||||
|
label,
|
||||||
|
client,
|
||||||
|
isManagedVault,
|
||||||
|
} = props;
|
||||||
|
|
||||||
|
const formSchema = useMemo(() => createSendFormSchema(SECRET_KEY_LABEL), []);
|
||||||
|
|
||||||
|
const form = useForm<SendFormValues>({
|
||||||
|
defaultValues: {
|
||||||
|
amount: "0",
|
||||||
|
chainId,
|
||||||
|
secretKey: "",
|
||||||
|
vaultAccessToken: "",
|
||||||
|
toAddress: "",
|
||||||
|
},
|
||||||
|
mode: "onChange",
|
||||||
|
resolver: zodResolver(formSchema),
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectedChain = useV5DashboardChain(form.watch("chainId"));
|
||||||
|
|
||||||
|
const sendMutation = useMutation({
|
||||||
|
mutationFn: async (values: SendFormValues) => {
|
||||||
|
const quantityWei = toWei(values.amount).toString();
|
||||||
|
const secretKeyValue = values.secretKey.trim();
|
||||||
|
const vaultAccessTokenValue = values.vaultAccessToken.trim();
|
||||||
|
|
||||||
|
const result = await sendProjectWalletTokens({
|
||||||
|
chainId: values.chainId,
|
||||||
|
publishableKey,
|
||||||
|
quantityWei,
|
||||||
|
recipientAddress: values.toAddress,
|
||||||
|
teamId,
|
||||||
|
walletAddress,
|
||||||
|
secretKey: secretKeyValue,
|
||||||
|
...(vaultAccessTokenValue
|
||||||
|
? { vaultAccessToken: vaultAccessTokenValue }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
const errorMessage =
|
||||||
|
typeof result.error === "string"
|
||||||
|
? result.error
|
||||||
|
: "Failed to send funds";
|
||||||
|
throw new Error(errorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.transactionIds;
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
toast.error(error.message);
|
||||||
|
},
|
||||||
|
onSuccess: (transactionIds) => {
|
||||||
|
toast.success("Transfer submitted", {
|
||||||
|
description:
|
||||||
|
transactionIds && transactionIds.length > 0
|
||||||
|
? `Transaction ID: ${transactionIds[0]}`
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
onSuccess();
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="gap-0 p-0">
|
||||||
|
<DialogHeader className="p-4 lg:p-6">
|
||||||
|
<DialogTitle>Send from {label}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Execute a one-off transfer using your server wallet.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<Form {...form}>
|
||||||
|
<form
|
||||||
|
onSubmit={form.handleSubmit((values) => {
|
||||||
|
void sendMutation.mutateAsync(values);
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<div className="space-y-4 px-4 pb-8 lg:px-6">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="chainId"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Network</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<SingleNetworkSelector
|
||||||
|
chainId={field.value}
|
||||||
|
className="bg-card"
|
||||||
|
client={client}
|
||||||
|
disableDeprecated
|
||||||
|
onChange={(nextChainId) => {
|
||||||
|
field.onChange(nextChainId);
|
||||||
|
}}
|
||||||
|
placeholder="Select network"
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="toAddress"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Send to</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input autoComplete="off" placeholder="0x..." {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="amount"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Amount</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input inputMode="decimal" min="0" step="any" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormDescription>
|
||||||
|
Sending native token
|
||||||
|
{selectedChain?.nativeCurrency?.symbol
|
||||||
|
? ` (${selectedChain.nativeCurrency.symbol})`
|
||||||
|
: ""}
|
||||||
|
</FormDescription>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="secretKey"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>{secretKeyLabel}</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
autoComplete="off"
|
||||||
|
autoCorrect="off"
|
||||||
|
placeholder={secretKeyPlaceholder}
|
||||||
|
spellCheck={false}
|
||||||
|
type="password"
|
||||||
|
{...field}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormDescription>{secretKeyHelper}</FormDescription>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{!isManagedVault && (
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="vaultAccessToken"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>
|
||||||
|
Vault access token
|
||||||
|
<span className="text-muted-foreground"> (optional)</span>
|
||||||
|
</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
autoComplete="off"
|
||||||
|
autoCorrect="off"
|
||||||
|
placeholder="Enter a vault access token (optional)"
|
||||||
|
spellCheck={false}
|
||||||
|
type="password"
|
||||||
|
{...field}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormDescription>{vaultAccessTokenHelper}</FormDescription>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-3 border-t bg-card p-4 lg:p-6">
|
||||||
|
<Button onClick={onClose} type="button" variant="outline">
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
className="gap-2"
|
||||||
|
disabled={!form.formState.isValid || sendMutation.isPending}
|
||||||
|
type="submit"
|
||||||
|
>
|
||||||
|
{sendMutation.isPending && <Spinner className="size-4" />}
|
||||||
|
Submit transfer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||||
|
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
||||||
|
import { projectStub } from "@/storybook/stubs";
|
||||||
|
import { storybookThirdwebClient } from "@/storybook/utils";
|
||||||
|
import { ProjectWalletSectionUI } from "./project-wallet";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
component: ProjectWalletSectionUI,
|
||||||
|
title: "Project/ProjectWalletSection",
|
||||||
|
parameters: {
|
||||||
|
nextjs: {
|
||||||
|
appDirectory: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
decorators: [
|
||||||
|
(Story) => (
|
||||||
|
<div className="container py-8 pb-20 max-w-7xl">
|
||||||
|
<Story />
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
],
|
||||||
|
} satisfies Meta<typeof ProjectWalletSectionUI>;
|
||||||
|
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
|
||||||
|
const projectWithManagedAccessToken = projectStub("foo", "bar");
|
||||||
|
projectWithManagedAccessToken.services = [
|
||||||
|
{
|
||||||
|
name: "engineCloud",
|
||||||
|
actions: [],
|
||||||
|
managementAccessToken: "managed-access-token",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const projectWithoutManagedAccessToken = projectStub("foo", "bar");
|
||||||
|
|
||||||
|
const projectWallet1: ProjectWalletSummary = {
|
||||||
|
id: "server-wallet-id",
|
||||||
|
address: "0x1F846F6DAE38E1C88D71EAA191760B15f38B7A37",
|
||||||
|
label: "Project Wallet 1",
|
||||||
|
};
|
||||||
|
|
||||||
|
const projectWallet2: ProjectWalletSummary = {
|
||||||
|
id: "server-wallet-id-2",
|
||||||
|
address: "0x83Dd93fA5D8343094f850f90B3fb90088C1bB425",
|
||||||
|
label: "Project Wallet 2",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const NoProjectWalletSetNoManagedAccessToken: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithoutManagedAccessToken,
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
teamSlug: "bar",
|
||||||
|
projectWallet: undefined,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const NoProjectWalletSetWithManagedAccessToken: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithManagedAccessToken,
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
teamSlug: "bar",
|
||||||
|
projectWallet: undefined,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const NoProjectWalletSetWithManagedAccessTokenAndServerWallets: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithManagedAccessToken,
|
||||||
|
teamSlug: "bar",
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
projectWallet: undefined,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
return [projectWallet1, projectWallet2];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const NoProjectWalletSetLoading: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithManagedAccessToken,
|
||||||
|
teamSlug: "bar",
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
projectWallet: undefined,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 100000));
|
||||||
|
return [projectWallet1, projectWallet2];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ProjectWalletSetMultipleServerWallets: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithManagedAccessToken,
|
||||||
|
teamSlug: "bar",
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
projectWallet: projectWallet1,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
return [projectWallet1, projectWallet2];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ProjectWalletSetSingleServerWallet: Story = {
|
||||||
|
args: {
|
||||||
|
project: projectWithManagedAccessToken,
|
||||||
|
teamSlug: "bar",
|
||||||
|
projectWallet: projectWallet1,
|
||||||
|
client: storybookThirdwebClient,
|
||||||
|
getProjectServerWallets: async () => {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
return [projectWallet1];
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
+331
@@ -0,0 +1,331 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { UnderlineLink } from "@workspace/ui/components/UnderlineLink";
|
||||||
|
import { ChevronDownIcon, XIcon } from "lucide-react";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import type { ThirdwebClient } from "thirdweb";
|
||||||
|
import { listProjectServerWallets } from "@/actions/project-wallet/list-server-wallets";
|
||||||
|
import type { Project } from "@/api/project/projects";
|
||||||
|
import { WalletAddress } from "@/components/blocks/wallet-address";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Spinner } from "@/components/ui/Spinner";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||||
|
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||||
|
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
||||||
|
import { updateDefaultProjectWallet } from "../../transactions/lib/vault.client";
|
||||||
|
import { CreateServerWallet } from "../../transactions/server-wallets/components/create-server-wallet.client";
|
||||||
|
import { ProjectWalletDetailsSection } from "./project-wallet-details";
|
||||||
|
|
||||||
|
type GetProjectServerWallets = (params: {
|
||||||
|
managementAccessToken: string;
|
||||||
|
projectId: string;
|
||||||
|
}) => Promise<ProjectWalletSummary[]>;
|
||||||
|
|
||||||
|
function CreateProjectWalletSection(props: {
|
||||||
|
project: Project;
|
||||||
|
teamSlug: string;
|
||||||
|
getProjectServerWallets: GetProjectServerWallets;
|
||||||
|
}) {
|
||||||
|
const { project, teamSlug } = props;
|
||||||
|
const router = useDashboardRouter();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const client = useMemo(() => getClientThirdwebClient(), []);
|
||||||
|
const [selectedWalletId, setSelectedWalletId] = useState<string | undefined>(
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
const [isSelectDialogOpen, setIsSelectDialogOpen] = useState(false);
|
||||||
|
|
||||||
|
const managementAccessToken =
|
||||||
|
props.project.services?.find((service) => service.name === "engineCloud")
|
||||||
|
?.managementAccessToken ?? undefined;
|
||||||
|
|
||||||
|
const serverWalletsQuery = useQuery({
|
||||||
|
enabled: Boolean(managementAccessToken),
|
||||||
|
queryFn: async () => {
|
||||||
|
if (!managementAccessToken) {
|
||||||
|
return [] as ProjectWalletSummary[];
|
||||||
|
}
|
||||||
|
|
||||||
|
return props.getProjectServerWallets({
|
||||||
|
managementAccessToken,
|
||||||
|
projectId: project.id,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
queryKey: ["project", project.id, "server-wallets", managementAccessToken],
|
||||||
|
refetchOnWindowFocus: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const serverWallets = serverWalletsQuery.data ?? [];
|
||||||
|
|
||||||
|
const effectiveSelectedWalletId = useMemo(() => {
|
||||||
|
if (
|
||||||
|
selectedWalletId &&
|
||||||
|
serverWallets.some((wallet) => wallet.id === selectedWalletId)
|
||||||
|
) {
|
||||||
|
return selectedWalletId;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serverWallets[0]?.id;
|
||||||
|
}, [selectedWalletId, serverWallets]);
|
||||||
|
|
||||||
|
const selectedWallet = useMemo(() => {
|
||||||
|
if (!effectiveSelectedWalletId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serverWallets.find(
|
||||||
|
(wallet) => wallet.id === effectiveSelectedWalletId,
|
||||||
|
);
|
||||||
|
}, [effectiveSelectedWalletId, serverWallets]);
|
||||||
|
|
||||||
|
const setDefaultWalletMutation = useMutation({
|
||||||
|
mutationFn: async (wallet: ProjectWalletSummary) => {
|
||||||
|
await updateDefaultProjectWallet({
|
||||||
|
project,
|
||||||
|
projectWalletAddress: wallet.address,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
const message =
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to update project wallet";
|
||||||
|
toast.error(message);
|
||||||
|
},
|
||||||
|
onSuccess: async (_, wallet) => {
|
||||||
|
const descriptionLabel = wallet.label ?? wallet.address;
|
||||||
|
toast.success("Project wallet updated", {
|
||||||
|
description: `Now pointing to ${descriptionLabel}`,
|
||||||
|
});
|
||||||
|
await queryClient.invalidateQueries({
|
||||||
|
queryKey: [
|
||||||
|
"project",
|
||||||
|
project.id,
|
||||||
|
"server-wallets",
|
||||||
|
managementAccessToken,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
setIsSelectDialogOpen(false);
|
||||||
|
router.refresh();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const canSelectExisting =
|
||||||
|
Boolean(managementAccessToken) && serverWallets.length > 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-xl border p-4 bg-card">
|
||||||
|
<div className="rounded-full p-2 border bg-background inline-flex mb-4">
|
||||||
|
<XIcon className="size-3.5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-sm font-medium text-foreground mb-0.5">
|
||||||
|
No Project Wallet set
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Set a project wallet to set the default sender in thirdweb API.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-5 text-foreground">
|
||||||
|
{serverWalletsQuery.isLoading ? (
|
||||||
|
<Skeleton className="h-[36px] max-w-lg rounded-full" />
|
||||||
|
) : canSelectExisting ? (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button
|
||||||
|
className="bg-background rounded-full gap-2"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedWalletId(effectiveSelectedWalletId);
|
||||||
|
setIsSelectDialogOpen(true);
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<ChevronDownIcon className="size-4 text-muted-foreground" />
|
||||||
|
Select a server wallet
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<CreateServerWallet
|
||||||
|
project={project}
|
||||||
|
teamSlug={teamSlug}
|
||||||
|
setAsProjectWallet
|
||||||
|
button={{ size: "sm", iconClassName: "size-3.5" }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
onOpenChange={(nextOpen) => {
|
||||||
|
if (!nextOpen) {
|
||||||
|
setIsSelectDialogOpen(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
open={isSelectDialogOpen}
|
||||||
|
>
|
||||||
|
<DialogContent className="gap-0 p-0 overflow-hidden">
|
||||||
|
<DialogHeader className="p-4 lg:p-6">
|
||||||
|
<DialogTitle>Select project wallet</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Choose a server wallet to use as the default for this
|
||||||
|
project.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="px-4 pb-8 lg:px-6">
|
||||||
|
{serverWalletsQuery.isLoading ? (
|
||||||
|
<div className="flex justify-center py-6">
|
||||||
|
<Spinner className="size-5" />
|
||||||
|
</div>
|
||||||
|
) : serverWallets.length === 0 ? (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
No server wallets found.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<Select
|
||||||
|
onValueChange={(value) => setSelectedWalletId(value)}
|
||||||
|
value={selectedWalletId ?? ""}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-full">
|
||||||
|
<SelectValue placeholder="Select server wallet" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{serverWallets.map((wallet) => (
|
||||||
|
<SelectItem key={wallet.id} value={wallet.id}>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<WalletAddress
|
||||||
|
address={wallet.address}
|
||||||
|
client={client}
|
||||||
|
className="h-auto py-1"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-muted-foreground">
|
||||||
|
{wallet.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-3 border-t bg-card p-4 lg:p-6">
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setIsSelectDialogOpen(false);
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={setDefaultWalletMutation.isPending}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
disabled={
|
||||||
|
!selectedWallet || setDefaultWalletMutation.isPending
|
||||||
|
}
|
||||||
|
onClick={() => {
|
||||||
|
if (selectedWallet) {
|
||||||
|
setDefaultWalletMutation.mutate(selectedWallet);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{setDefaultWalletMutation.isPending && (
|
||||||
|
<Spinner className="mr-2 size-4" />
|
||||||
|
)}
|
||||||
|
Set as project wallet
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-3 text-sm text-muted-foreground">
|
||||||
|
<CreateServerWallet
|
||||||
|
project={project}
|
||||||
|
teamSlug={teamSlug}
|
||||||
|
setAsProjectWallet
|
||||||
|
button={{ size: "sm", iconClassName: "size-3.5" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectWalletSectionUI(props: {
|
||||||
|
project: Project;
|
||||||
|
teamSlug: string;
|
||||||
|
projectWallet: ProjectWalletSummary | undefined;
|
||||||
|
getProjectServerWallets: GetProjectServerWallets;
|
||||||
|
client: ThirdwebClient;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-3">
|
||||||
|
<h2 className="mb-1 font-semibold text-xl tracking-tight">
|
||||||
|
Project Wallet
|
||||||
|
</h2>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
The server wallet to be used as the default sender in{" "}
|
||||||
|
<UnderlineLink
|
||||||
|
href="https://portal.thirdweb.com/reference"
|
||||||
|
target="_blank"
|
||||||
|
>
|
||||||
|
thirdweb API
|
||||||
|
</UnderlineLink>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{props.projectWallet ? (
|
||||||
|
<ProjectWalletDetailsSection
|
||||||
|
project={props.project}
|
||||||
|
projectWallet={props.projectWallet}
|
||||||
|
client={props.client}
|
||||||
|
teamSlug={props.teamSlug}
|
||||||
|
getProjectServerWallets={props.getProjectServerWallets}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<CreateProjectWalletSection
|
||||||
|
project={props.project}
|
||||||
|
teamSlug={props.teamSlug}
|
||||||
|
getProjectServerWallets={props.getProjectServerWallets}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectWalletSection(props: {
|
||||||
|
project: Project;
|
||||||
|
teamSlug: string;
|
||||||
|
projectWallet: ProjectWalletSummary | undefined;
|
||||||
|
client: ThirdwebClient;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ProjectWalletSectionUI
|
||||||
|
project={props.project}
|
||||||
|
teamSlug={props.teamSlug}
|
||||||
|
client={props.client}
|
||||||
|
projectWallet={props.projectWallet}
|
||||||
|
getProjectServerWallets={listProjectServerWallets}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
-1
@@ -59,7 +59,6 @@ export function ErrorRate({ datapoints }: { datapoints: ResultItem[] }) {
|
|||||||
key={tag}
|
key={tag}
|
||||||
stackId="a"
|
stackId="a"
|
||||||
stroke={`var(--color-${tag})`}
|
stroke={`var(--color-${tag})`}
|
||||||
type="natural"
|
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+8
@@ -14,6 +14,7 @@ type AggregatedMetrics = {
|
|||||||
|
|
||||||
export function ProjectHighlightsCard(props: {
|
export function ProjectHighlightsCard(props: {
|
||||||
selectedChart: string | undefined;
|
selectedChart: string | undefined;
|
||||||
|
aggregatedUserStats: InAppWalletStats[];
|
||||||
userStats: InAppWalletStats[];
|
userStats: InAppWalletStats[];
|
||||||
volumeStats: UniversalBridgeStats[];
|
volumeStats: UniversalBridgeStats[];
|
||||||
teamSlug: string;
|
teamSlug: string;
|
||||||
@@ -22,6 +23,7 @@ export function ProjectHighlightsCard(props: {
|
|||||||
}) {
|
}) {
|
||||||
const {
|
const {
|
||||||
selectedChart,
|
selectedChart,
|
||||||
|
aggregatedUserStats,
|
||||||
userStats,
|
userStats,
|
||||||
volumeStats,
|
volumeStats,
|
||||||
teamSlug,
|
teamSlug,
|
||||||
@@ -70,6 +72,12 @@ export function ProjectHighlightsCard(props: {
|
|||||||
: "activeUsers"
|
: "activeUsers"
|
||||||
}
|
}
|
||||||
aggregateFn={(_data, key) => {
|
aggregateFn={(_data, key) => {
|
||||||
|
if (key === "activeUsers") {
|
||||||
|
return aggregatedUserStats.reduce(
|
||||||
|
(acc, curr) => acc + curr.uniqueWalletsConnected,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}
|
||||||
return timeSeriesData.reduce((acc, curr) => acc + curr[key], 0);
|
return timeSeriesData.reduce((acc, curr) => acc + curr[key], 0);
|
||||||
}}
|
}}
|
||||||
chartConfig={chartConfig}
|
chartConfig={chartConfig}
|
||||||
|
|||||||
@@ -39,10 +39,8 @@ import type {
|
|||||||
import { loginRedirect } from "@/utils/redirects";
|
import { loginRedirect } from "@/utils/redirects";
|
||||||
import { PieChartCard } from "../../../components/Analytics/PieChartCard";
|
import { PieChartCard } from "../../../components/Analytics/PieChartCard";
|
||||||
import { EngineCloudChartCardAsync } from "./components/EngineCloudChartCard";
|
import { EngineCloudChartCardAsync } from "./components/EngineCloudChartCard";
|
||||||
import {
|
import { ProjectFTUX } from "./components/ProjectFTUX/ProjectFTUX";
|
||||||
ProjectFTUX,
|
import { ProjectWalletSection } from "./components/project-wallet/project-wallet";
|
||||||
ProjectWalletSection,
|
|
||||||
} from "./components/ProjectFTUX/ProjectFTUX";
|
|
||||||
import { RpcMethodBarChartCardAsync } from "./components/RpcMethodBarChartCard";
|
import { RpcMethodBarChartCardAsync } from "./components/RpcMethodBarChartCard";
|
||||||
import { TransactionsChartCardAsync } from "./components/Transactions";
|
import { TransactionsChartCardAsync } from "./components/Transactions";
|
||||||
import { ProjectHighlightsCard } from "./overview/highlights-card";
|
import { ProjectHighlightsCard } from "./overview/highlights-card";
|
||||||
@@ -112,9 +110,6 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const projectWallet = await getProjectWallet(project);
|
const projectWallet = await getProjectWallet(project);
|
||||||
const managementAccessToken =
|
|
||||||
project.services?.find((service) => service.name === "engineCloud")
|
|
||||||
?.managementAccessToken ?? undefined;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ResponsiveSearchParamsProvider value={searchParams}>
|
<ResponsiveSearchParamsProvider value={searchParams}>
|
||||||
@@ -135,14 +130,17 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
|||||||
actions: null,
|
actions: null,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isActive ? (
|
|
||||||
<div className="flex flex-col gap-4 md:gap-6">
|
|
||||||
<ProjectWalletSection
|
<ProjectWalletSection
|
||||||
project={project}
|
project={project}
|
||||||
teamSlug={params.team_slug}
|
teamSlug={params.team_slug}
|
||||||
wallet={projectWallet}
|
projectWallet={projectWallet}
|
||||||
managementAccessToken={managementAccessToken}
|
client={client}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div className="h-10" />
|
||||||
|
|
||||||
|
{isActive ? (
|
||||||
|
<div className="flex flex-col gap-4 md:gap-6">
|
||||||
<ResponsiveTimeFilters defaultRange={defaultRange} />
|
<ResponsiveTimeFilters defaultRange={defaultRange} />
|
||||||
<ProjectAnalytics
|
<ProjectAnalytics
|
||||||
authToken={authToken}
|
authToken={authToken}
|
||||||
@@ -155,12 +153,7 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<ProjectFTUX
|
<ProjectFTUX project={project} teamSlug={params.team_slug} />
|
||||||
project={project}
|
|
||||||
teamSlug={params.team_slug}
|
|
||||||
wallet={projectWallet}
|
|
||||||
managementAccessToken={managementAccessToken}
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</ProjectPage>
|
</ProjectPage>
|
||||||
</ResponsiveSearchParamsProvider>
|
</ResponsiveSearchParamsProvider>
|
||||||
@@ -385,8 +378,18 @@ async function AsyncAppHighlightsCard(props: {
|
|||||||
params: PageParams;
|
params: PageParams;
|
||||||
authToken: string;
|
authToken: string;
|
||||||
}) {
|
}) {
|
||||||
const [walletUserStatsTimeSeries, universalBridgeUsage] =
|
const [aggregatedUserStats, walletUserStatsTimeSeries, universalBridgeUsage] =
|
||||||
await Promise.allSettled([
|
await Promise.allSettled([
|
||||||
|
getInAppWalletUsage(
|
||||||
|
{
|
||||||
|
from: props.range.from,
|
||||||
|
period: "all",
|
||||||
|
projectId: props.project.id,
|
||||||
|
teamId: props.project.teamId,
|
||||||
|
to: props.range.to,
|
||||||
|
},
|
||||||
|
props.authToken,
|
||||||
|
),
|
||||||
getInAppWalletUsage(
|
getInAppWalletUsage(
|
||||||
{
|
{
|
||||||
from: props.range.from,
|
from: props.range.from,
|
||||||
@@ -415,6 +418,11 @@ async function AsyncAppHighlightsCard(props: {
|
|||||||
) {
|
) {
|
||||||
return (
|
return (
|
||||||
<ProjectHighlightsCard
|
<ProjectHighlightsCard
|
||||||
|
aggregatedUserStats={
|
||||||
|
aggregatedUserStats.status === "fulfilled"
|
||||||
|
? aggregatedUserStats.value
|
||||||
|
: []
|
||||||
|
}
|
||||||
selectedChart={props.selectedChart}
|
selectedChart={props.selectedChart}
|
||||||
selectedChartQueryParam={props.selectedChartQueryParam}
|
selectedChartQueryParam={props.selectedChartQueryParam}
|
||||||
teamSlug={props.params.team_slug}
|
teamSlug={props.params.team_slug}
|
||||||
|
|||||||
+4
-21
@@ -3,14 +3,13 @@ import { useMemo } from "react";
|
|||||||
import type { ThirdwebClient } from "thirdweb";
|
import type { ThirdwebClient } from "thirdweb";
|
||||||
import type { Project } from "@/api/project/projects";
|
import type { Project } from "@/api/project/projects";
|
||||||
import { type Step, StepsCard } from "@/components/blocks/StepsCard";
|
import { type Step, StepsCard } from "@/components/blocks/StepsCard";
|
||||||
import CreateServerWallet from "../server-wallets/components/create-server-wallet.client";
|
import { CreateServerWallet } from "../server-wallets/components/create-server-wallet.client";
|
||||||
import type { Wallet } from "../server-wallets/wallet-table/types";
|
import type { Wallet } from "../server-wallets/wallet-table/types";
|
||||||
import type { SolanaWallet } from "../solana-wallets/wallet-table/types";
|
import type { SolanaWallet } from "../solana-wallets/wallet-table/types";
|
||||||
import { SendTestSolanaTransaction } from "./send-test-solana-tx.client";
|
import { SendTestSolanaTransaction } from "./send-test-solana-tx.client";
|
||||||
import { SendTestTransaction } from "./send-test-tx.client";
|
import { SendTestTransaction } from "./send-test-tx.client";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
project: Project;
|
project: Project;
|
||||||
wallets: Wallet[];
|
wallets: Wallet[];
|
||||||
solanaWallets: SolanaWallet[];
|
solanaWallets: SolanaWallet[];
|
||||||
@@ -29,11 +28,12 @@ export const EngineChecklist: React.FC<Props> = (props) => {
|
|||||||
const steps: Step[] = [];
|
const steps: Step[] = [];
|
||||||
steps.push({
|
steps.push({
|
||||||
children: (
|
children: (
|
||||||
<CreateServerWalletStep
|
<div className="mt-4 flex flex-row gap-4">
|
||||||
managementAccessToken={props.managementAccessToken}
|
<CreateServerWallet
|
||||||
project={props.project}
|
project={props.project}
|
||||||
teamSlug={props.teamSlug}
|
teamSlug={props.teamSlug}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
completed: props.wallets.length > 0 || props.hasTransactions,
|
completed: props.wallets.length > 0 || props.hasTransactions,
|
||||||
description:
|
description:
|
||||||
@@ -61,7 +61,6 @@ export const EngineChecklist: React.FC<Props> = (props) => {
|
|||||||
});
|
});
|
||||||
return steps;
|
return steps;
|
||||||
}, [
|
}, [
|
||||||
props.managementAccessToken,
|
|
||||||
props.project,
|
props.project,
|
||||||
props.wallets,
|
props.wallets,
|
||||||
props.hasTransactions,
|
props.hasTransactions,
|
||||||
@@ -113,19 +112,3 @@ export const EngineChecklist: React.FC<Props> = (props) => {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
function CreateServerWalletStep(props: {
|
|
||||||
project: Project;
|
|
||||||
teamSlug: string;
|
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div className="mt-4 flex flex-row gap-4">
|
|
||||||
<CreateServerWallet
|
|
||||||
managementAccessToken={props.managementAccessToken}
|
|
||||||
project={props.project}
|
|
||||||
teamSlug={props.teamSlug}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
+67
-17
@@ -40,6 +40,13 @@ import {
|
|||||||
PaginationNext,
|
PaginationNext,
|
||||||
PaginationPrevious,
|
PaginationPrevious,
|
||||||
} from "@/components/ui/pagination";
|
} from "@/components/ui/pagination";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { Switch } from "@/components/ui/switch";
|
import { Switch } from "@/components/ui/switch";
|
||||||
import {
|
import {
|
||||||
@@ -57,8 +64,9 @@ import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
|||||||
import { WalletProductIcon } from "@/icons/WalletProductIcon";
|
import { WalletProductIcon } from "@/icons/WalletProductIcon";
|
||||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { fetchSolanaBalance } from "../lib/getSolanaBalance";
|
||||||
import { updateDefaultProjectWallet } from "../lib/vault.client";
|
import { updateDefaultProjectWallet } from "../lib/vault.client";
|
||||||
import CreateServerWallet from "../server-wallets/components/create-server-wallet.client";
|
import { CreateServerWallet } from "../server-wallets/components/create-server-wallet.client";
|
||||||
import type { Wallet as EVMWallet } from "../server-wallets/wallet-table/types";
|
import type { Wallet as EVMWallet } from "../server-wallets/wallet-table/types";
|
||||||
import { CreateSolanaWallet } from "../solana-wallets/components/create-solana-wallet.client";
|
import { CreateSolanaWallet } from "../solana-wallets/components/create-solana-wallet.client";
|
||||||
import { UpgradeSolanaPermissions } from "../solana-wallets/components/upgrade-solana-permissions.client";
|
import { UpgradeSolanaPermissions } from "../solana-wallets/components/upgrade-solana-permissions.client";
|
||||||
@@ -77,9 +85,9 @@ interface ServerWalletsTableProps {
|
|||||||
solanaTotalPages: number;
|
solanaTotalPages: number;
|
||||||
project: Project;
|
project: Project;
|
||||||
teamSlug: string;
|
teamSlug: string;
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
client: ThirdwebClient;
|
client: ThirdwebClient;
|
||||||
solanaPermissionError?: boolean;
|
solanaPermissionError?: boolean;
|
||||||
|
authToken: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
||||||
@@ -88,7 +96,6 @@ export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
|||||||
solanaWallets,
|
solanaWallets,
|
||||||
project,
|
project,
|
||||||
teamSlug,
|
teamSlug,
|
||||||
managementAccessToken,
|
|
||||||
evmTotalRecords,
|
evmTotalRecords,
|
||||||
evmCurrentPage,
|
evmCurrentPage,
|
||||||
evmTotalPages,
|
evmTotalPages,
|
||||||
@@ -97,10 +104,14 @@ export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
|||||||
solanaTotalPages,
|
solanaTotalPages,
|
||||||
client,
|
client,
|
||||||
solanaPermissionError,
|
solanaPermissionError,
|
||||||
|
authToken,
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const [activeChain, setActiveChain] = useState<WalletChain>("evm");
|
const [activeChain, setActiveChain] = useState<WalletChain>("evm");
|
||||||
const [selectedChainId, setSelectedChainId] = useState<number>(1);
|
const [selectedChainId, setSelectedChainId] = useState<number>(1);
|
||||||
|
const [selectedSolanaChain, setSelectedSolanaChain] = useState<
|
||||||
|
"solana:mainnet" | "solana:devnet"
|
||||||
|
>("solana:mainnet");
|
||||||
const [showSmartAccount, setShowSmartAccount] = useState(false);
|
const [showSmartAccount, setShowSmartAccount] = useState(false);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -134,11 +145,7 @@ export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
|||||||
<div className="flex flex-row gap-2.5">
|
<div className="flex flex-row gap-2.5">
|
||||||
{activeChain === "evm" && (
|
{activeChain === "evm" && (
|
||||||
<>
|
<>
|
||||||
<CreateServerWallet
|
<CreateServerWallet project={project} teamSlug={teamSlug} />
|
||||||
managementAccessToken={managementAccessToken}
|
|
||||||
project={project}
|
|
||||||
teamSlug={teamSlug}
|
|
||||||
/>
|
|
||||||
<SingleNetworkSelector
|
<SingleNetworkSelector
|
||||||
chainId={selectedChainId}
|
chainId={selectedChainId}
|
||||||
onChange={setSelectedChainId}
|
onChange={setSelectedChainId}
|
||||||
@@ -151,12 +158,33 @@ export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{activeChain === "solana" && (
|
{activeChain === "solana" && (
|
||||||
|
<>
|
||||||
<CreateSolanaWallet
|
<CreateSolanaWallet
|
||||||
managementAccessToken={managementAccessToken}
|
|
||||||
project={project}
|
project={project}
|
||||||
teamSlug={teamSlug}
|
teamSlug={teamSlug}
|
||||||
disabled={solanaPermissionError}
|
disabled={solanaPermissionError}
|
||||||
/>
|
/>
|
||||||
|
<Select
|
||||||
|
value={selectedSolanaChain}
|
||||||
|
onValueChange={(value) =>
|
||||||
|
setSelectedSolanaChain(
|
||||||
|
value as "solana:mainnet" | "solana:devnet",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-fit min-w-[180px] rounded-full bg-background hover:bg-accent/50">
|
||||||
|
<SelectValue placeholder="Select network" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="rounded-xl">
|
||||||
|
<SelectItem value="solana:mainnet" className="rounded-lg">
|
||||||
|
Solana Mainnet
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value="solana:devnet" className="rounded-lg">
|
||||||
|
Solana Devnet
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -285,6 +313,8 @@ export function ServerWalletsTable(props: ServerWalletsTableProps) {
|
|||||||
project={project}
|
project={project}
|
||||||
teamSlug={teamSlug}
|
teamSlug={teamSlug}
|
||||||
client={client}
|
client={client}
|
||||||
|
authToken={authToken}
|
||||||
|
chainId={selectedSolanaChain}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
@@ -514,11 +544,15 @@ function SolanaWalletRow({
|
|||||||
project,
|
project,
|
||||||
teamSlug,
|
teamSlug,
|
||||||
client,
|
client,
|
||||||
|
authToken,
|
||||||
|
chainId,
|
||||||
}: {
|
}: {
|
||||||
wallet: SolanaWallet;
|
wallet: SolanaWallet;
|
||||||
project: Project;
|
project: Project;
|
||||||
teamSlug: string;
|
teamSlug: string;
|
||||||
client: ThirdwebClient;
|
client: ThirdwebClient;
|
||||||
|
authToken: string;
|
||||||
|
chainId: "solana:mainnet" | "solana:devnet";
|
||||||
}) {
|
}) {
|
||||||
const engineService = project.services.find(
|
const engineService = project.services.find(
|
||||||
(s) => s.name === "engineCloud",
|
(s) => s.name === "engineCloud",
|
||||||
@@ -554,7 +588,12 @@ function SolanaWalletRow({
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<SolanaWalletBalance publicKey={wallet.publicKey} />
|
<SolanaWalletBalance
|
||||||
|
publicKey={wallet.publicKey}
|
||||||
|
authToken={authToken}
|
||||||
|
clientId={project.publishableKey}
|
||||||
|
chainId={chainId}
|
||||||
|
/>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
|
|
||||||
<TableCell>
|
<TableCell>
|
||||||
@@ -746,16 +785,27 @@ function WalletBalance({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SolanaWalletBalance({ publicKey }: { publicKey: string }) {
|
function SolanaWalletBalance({
|
||||||
|
publicKey,
|
||||||
|
authToken,
|
||||||
|
clientId,
|
||||||
|
chainId,
|
||||||
|
}: {
|
||||||
|
publicKey: string;
|
||||||
|
authToken: string;
|
||||||
|
clientId: string;
|
||||||
|
chainId: "solana:mainnet" | "solana:devnet";
|
||||||
|
}) {
|
||||||
const balance = useQuery({
|
const balance = useQuery({
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
// TODO: Implement actual Solana balance fetching
|
return await fetchSolanaBalance({
|
||||||
return {
|
publicKey,
|
||||||
displayValue: "0",
|
authToken,
|
||||||
symbol: "SOL",
|
clientId,
|
||||||
};
|
chainId,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
queryKey: ["solanaWalletBalance", publicKey],
|
queryKey: ["solanaWalletBalance", publicKey, chainId],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (balance.isFetching) {
|
if (balance.isFetching) {
|
||||||
|
|||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
import { configure, getSolanaWalletBalance } from "@thirdweb-dev/api";
|
||||||
|
import { THIRDWEB_API_HOST } from "@/constants/urls";
|
||||||
|
|
||||||
|
// Configure the API client to use the correct base URL
|
||||||
|
configure({
|
||||||
|
override: {
|
||||||
|
baseUrl: THIRDWEB_API_HOST,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function fetchSolanaBalance({
|
||||||
|
publicKey,
|
||||||
|
authToken,
|
||||||
|
clientId,
|
||||||
|
chainId = "solana:mainnet",
|
||||||
|
}: {
|
||||||
|
publicKey: string;
|
||||||
|
authToken: string;
|
||||||
|
clientId: string;
|
||||||
|
chainId?: "solana:mainnet" | "solana:devnet";
|
||||||
|
}): Promise<{
|
||||||
|
displayValue: string;
|
||||||
|
symbol: string;
|
||||||
|
value: string;
|
||||||
|
decimals: number;
|
||||||
|
} | null> {
|
||||||
|
try {
|
||||||
|
const response = await getSolanaWalletBalance({
|
||||||
|
path: {
|
||||||
|
address: publicKey,
|
||||||
|
},
|
||||||
|
query: {
|
||||||
|
chainId,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${authToken}`,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"x-client-id": clientId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.error || !response.data) {
|
||||||
|
console.error(
|
||||||
|
"Error fetching Solana balance:",
|
||||||
|
response.error || "No data returned",
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
displayValue: response.data.result.displayValue,
|
||||||
|
symbol: "SOL",
|
||||||
|
value: response.data.result.value,
|
||||||
|
decimals: response.data.result.decimals,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching Solana balance:", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-2
@@ -156,7 +156,6 @@ export default async function TransactionsAnalyticsPage(props: {
|
|||||||
isManagedVault={isManagedVault}
|
isManagedVault={isManagedVault}
|
||||||
client={client}
|
client={client}
|
||||||
hasTransactions={hasTransactions}
|
hasTransactions={hasTransactions}
|
||||||
managementAccessToken={managementAccessToken ?? undefined}
|
|
||||||
project={project}
|
project={project}
|
||||||
teamSlug={params.team_slug}
|
teamSlug={params.team_slug}
|
||||||
testTxWithWallet={searchParams.testTxWithWallet as string | undefined}
|
testTxWithWallet={searchParams.testTxWithWallet as string | undefined}
|
||||||
@@ -207,7 +206,6 @@ export default async function TransactionsAnalyticsPage(props: {
|
|||||||
evmTotalPages={Math.ceil(eoas.data.totalRecords / pageSize)}
|
evmTotalPages={Math.ceil(eoas.data.totalRecords / pageSize)}
|
||||||
evmTotalRecords={eoas.data.totalRecords}
|
evmTotalRecords={eoas.data.totalRecords}
|
||||||
evmWallets={eoas.data.items as Wallet[]}
|
evmWallets={eoas.data.items as Wallet[]}
|
||||||
managementAccessToken={managementAccessToken ?? undefined}
|
|
||||||
project={project}
|
project={project}
|
||||||
solanaCurrentPage={solanCurrentPage}
|
solanaCurrentPage={solanCurrentPage}
|
||||||
solanaTotalPages={Math.ceil(
|
solanaTotalPages={Math.ceil(
|
||||||
@@ -217,6 +215,7 @@ export default async function TransactionsAnalyticsPage(props: {
|
|||||||
solanaWallets={solanaAccounts.data.items}
|
solanaWallets={solanaAccounts.data.items}
|
||||||
teamSlug={params.team_slug}
|
teamSlug={params.team_slug}
|
||||||
solanaPermissionError={isSolanaPermissionError}
|
solanaPermissionError={isSolanaPermissionError}
|
||||||
|
authToken={authToken}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+28
-9
@@ -15,18 +15,26 @@ import { Input } from "@/components/ui/input";
|
|||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Spinner } from "@/components/ui/Spinner";
|
import { Spinner } from "@/components/ui/Spinner";
|
||||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { createProjectServerWallet } from "../../lib/vault.client";
|
import { createProjectServerWallet } from "../../lib/vault.client";
|
||||||
|
|
||||||
export default function CreateServerWallet(props: {
|
export function CreateServerWallet(props: {
|
||||||
project: Project;
|
project: Project;
|
||||||
teamSlug: string;
|
teamSlug: string;
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
setAsProjectWallet?: boolean;
|
setAsProjectWallet?: boolean;
|
||||||
|
button?: {
|
||||||
|
size?: "default" | "sm" | "lg";
|
||||||
|
iconClassName?: string;
|
||||||
|
};
|
||||||
}) {
|
}) {
|
||||||
const router = useDashboardRouter();
|
const router = useDashboardRouter();
|
||||||
const [label, setLabel] = useState("");
|
const [label, setLabel] = useState("");
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
|
||||||
|
const managementAccessToken =
|
||||||
|
props.project.services?.find((service) => service.name === "engineCloud")
|
||||||
|
?.managementAccessToken ?? undefined;
|
||||||
|
|
||||||
const createEoaMutation = useMutation({
|
const createEoaMutation = useMutation({
|
||||||
mutationFn: async ({
|
mutationFn: async ({
|
||||||
managementAccessToken,
|
managementAccessToken,
|
||||||
@@ -53,12 +61,12 @@ export default function CreateServerWallet(props: {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleCreateServerWallet = async () => {
|
const handleCreateServerWallet = async () => {
|
||||||
if (!props.managementAccessToken) {
|
if (!managementAccessToken) {
|
||||||
router.push(`/team/${props.teamSlug}/${props.project.slug}/vault`);
|
router.push(`/team/${props.teamSlug}/${props.project.slug}/vault`);
|
||||||
} else {
|
} else {
|
||||||
await createEoaMutation.mutateAsync({
|
await createEoaMutation.mutateAsync({
|
||||||
label,
|
label,
|
||||||
managementAccessToken: props.managementAccessToken,
|
managementAccessToken: managementAccessToken,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -68,21 +76,32 @@ export default function CreateServerWallet(props: {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
className="gap-1.5 rounded-full bg-background"
|
className="gap-1.5 rounded-full bg-background text-foreground"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
|
size={props.button?.size}
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
props.managementAccessToken
|
managementAccessToken
|
||||||
? setModalOpen(true)
|
? setModalOpen(true)
|
||||||
: router.push(`/team/${props.teamSlug}/${props.project.slug}/vault`)
|
: router.push(`/team/${props.teamSlug}/${props.project.slug}/vault`)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<Spinner className="size-4" />
|
<Spinner
|
||||||
|
className={cn(
|
||||||
|
"size-4 text-muted-foreground",
|
||||||
|
props.button?.iconClassName,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
) : (
|
) : (
|
||||||
<PlusIcon className="size-4 text-muted-foreground" />
|
<PlusIcon
|
||||||
|
className={cn(
|
||||||
|
"size-4 text-muted-foreground",
|
||||||
|
props.button?.iconClassName,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{props.managementAccessToken
|
{managementAccessToken
|
||||||
? isLoading
|
? isLoading
|
||||||
? "Creating..."
|
? "Creating..."
|
||||||
: "Create Server Wallet"
|
: "Create Server Wallet"
|
||||||
|
|||||||
+8
-5
@@ -20,7 +20,6 @@ import { useDashboardRouter } from "@/lib/DashboardRouter";
|
|||||||
import { createSolanaAccount } from "../lib/vault.client";
|
import { createSolanaAccount } from "../lib/vault.client";
|
||||||
|
|
||||||
export function CreateSolanaWallet(props: {
|
export function CreateSolanaWallet(props: {
|
||||||
managementAccessToken: string | undefined;
|
|
||||||
project: Project;
|
project: Project;
|
||||||
teamSlug: string;
|
teamSlug: string;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
@@ -29,14 +28,18 @@ export function CreateSolanaWallet(props: {
|
|||||||
const [label, setLabel] = useState("");
|
const [label, setLabel] = useState("");
|
||||||
const router = useDashboardRouter();
|
const router = useDashboardRouter();
|
||||||
|
|
||||||
|
const managementAccessToken =
|
||||||
|
props.project.services?.find((service) => service.name === "engineCloud")
|
||||||
|
?.managementAccessToken ?? undefined;
|
||||||
|
|
||||||
const createMutation = useMutation({
|
const createMutation = useMutation({
|
||||||
mutationFn: async () => {
|
mutationFn: async () => {
|
||||||
if (!props.managementAccessToken) {
|
if (!managementAccessToken) {
|
||||||
throw new Error("No management access token");
|
throw new Error("No management access token");
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await createSolanaAccount({
|
const result = await createSolanaAccount({
|
||||||
managementAccessToken: props.managementAccessToken,
|
managementAccessToken: managementAccessToken,
|
||||||
label: label.trim(),
|
label: label.trim(),
|
||||||
projectId: props.project.id,
|
projectId: props.project.id,
|
||||||
teamId: props.project.teamId,
|
teamId: props.project.teamId,
|
||||||
@@ -67,8 +70,8 @@ export function CreateSolanaWallet(props: {
|
|||||||
<Dialog open={open} onOpenChange={setOpen}>
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="default"
|
variant="outline"
|
||||||
className="gap-2 rounded-full bg-foreground hover:bg-foreground/90"
|
className="gap-1.5 rounded-full bg-background text-foreground"
|
||||||
disabled={props.disabled}
|
disabled={props.disabled}
|
||||||
>
|
>
|
||||||
<PlusIcon className="size-4" />
|
<PlusIcon className="size-4" />
|
||||||
|
|||||||
+1
-1
@@ -193,7 +193,6 @@ export default async function Page(props: {
|
|||||||
evmTotalPages={Math.ceil(eoas.data.totalRecords / pageSize)}
|
evmTotalPages={Math.ceil(eoas.data.totalRecords / pageSize)}
|
||||||
evmTotalRecords={eoas.data.totalRecords}
|
evmTotalRecords={eoas.data.totalRecords}
|
||||||
evmWallets={eoas.data.items as Wallet[]}
|
evmWallets={eoas.data.items as Wallet[]}
|
||||||
managementAccessToken={managementAccessToken ?? undefined}
|
|
||||||
project={project}
|
project={project}
|
||||||
solanaCurrentPage={solanCurrentPage}
|
solanaCurrentPage={solanCurrentPage}
|
||||||
solanaTotalPages={Math.ceil(
|
solanaTotalPages={Math.ceil(
|
||||||
@@ -203,6 +202,7 @@ export default async function Page(props: {
|
|||||||
solanaWallets={solanaAccounts.data.items}
|
solanaWallets={solanaAccounts.data.items}
|
||||||
teamSlug={params.team_slug}
|
teamSlug={params.team_slug}
|
||||||
solanaPermissionError={isSolanaPermissionError || false}
|
solanaPermissionError={isSolanaPermissionError || false}
|
||||||
|
authToken={authToken}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@@ -1,6 +1,13 @@
|
|||||||
|
import type { Format } from "@number-flow/react";
|
||||||
import { cn } from "@workspace/ui/lib/utils";
|
import { cn } from "@workspace/ui/lib/utils";
|
||||||
|
import Image, { type StaticImageData } from "next/image";
|
||||||
import type { BuyAndSwapEmbedProps } from "@/components/blocks/BuyAndSwapEmbed";
|
import type { BuyAndSwapEmbedProps } from "@/components/blocks/BuyAndSwapEmbed";
|
||||||
import { FaqAccordion } from "@/components/blocks/faq-section";
|
import { FaqAccordion } from "@/components/blocks/faq-section";
|
||||||
|
import ChainsImage from "../assets/chains.png";
|
||||||
|
import RoutesImage from "../assets/routes.png";
|
||||||
|
import TokensImage from "../assets/tokens.png";
|
||||||
|
import { bridgeStats } from "../data";
|
||||||
|
import { AnimatedNumbers } from "./client/animated-numbers";
|
||||||
import { UniversalBridgeEmbed } from "./client/UniversalBridgeEmbed";
|
import { UniversalBridgeEmbed } from "./client/UniversalBridgeEmbed";
|
||||||
import { BridgePageHeader } from "./header";
|
import { BridgePageHeader } from "./header";
|
||||||
|
|
||||||
@@ -13,7 +20,7 @@ export function BridgePageUI(props: {
|
|||||||
<div className="grow flex flex-col">
|
<div className="grow flex flex-col">
|
||||||
<BridgePageHeader />
|
<BridgePageHeader />
|
||||||
|
|
||||||
<div className="flex grow items-center justify-center px-4 relative pt-12 pb-20 lg:py-28 min-h-[calc(100dvh-60px)]">
|
<div className="flex grow items-center justify-center px-4 relative pt-12 pb-20 lg:py-28 min-h-[calc(100dvh-60px)] overflow-hidden">
|
||||||
<DotsBackgroundPattern />
|
<DotsBackgroundPattern />
|
||||||
<UniversalBridgeEmbed buyTab={props.buyTab} swapTab={props.swapTab} />
|
<UniversalBridgeEmbed buyTab={props.buyTab} swapTab={props.swapTab} />
|
||||||
</div>
|
</div>
|
||||||
@@ -35,24 +42,58 @@ function HeadingSection(props: { title: React.ReactNode }) {
|
|||||||
<div className="mb-3 lg:mb-6">{props.title}</div>
|
<div className="mb-3 lg:mb-6">{props.title}</div>
|
||||||
|
|
||||||
<p className="text-muted-foreground text-sm text-pretty text-center lg:text-lg mb-6 lg:mb-8">
|
<p className="text-muted-foreground text-sm text-pretty text-center lg:text-lg mb-6 lg:mb-8">
|
||||||
Seamlessly move your assets across 85+ chains with the best rates and
|
Seamlessly move your assets across {bridgeStats.supportedChains} chains
|
||||||
fastest execution
|
with the best rates and fastest execution
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="flex flex-col lg:flex-row gap-3 lg:gap-2 items-center justify-center">
|
<div className="flex gap-3 items-center lg:justify-center flex-wrap">
|
||||||
<DataPill>85+ Chains Supported</DataPill>
|
<DataSquare data={90} label="Chains Supported" src={ChainsImage} />
|
||||||
<DataPill>4500+ Tokens Supported</DataPill>
|
<DataSquare
|
||||||
<DataPill>9+ Million Routes Available</DataPill>
|
data={6700}
|
||||||
|
label="Tokens Supported"
|
||||||
|
src={TokensImage}
|
||||||
|
format={{ notation: "compact" }}
|
||||||
|
/>
|
||||||
|
<DataSquare
|
||||||
|
data={14000000}
|
||||||
|
format={{ notation: "compact" }}
|
||||||
|
label="Routes Available"
|
||||||
|
src={RoutesImage}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function DataPill(props: { children: React.ReactNode }) {
|
function DataSquare(props: {
|
||||||
|
data: number;
|
||||||
|
label: string;
|
||||||
|
src: StaticImageData;
|
||||||
|
format?: Format;
|
||||||
|
imageClassName?: string;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<p className="bg-card flex items-center text-xs lg:text-sm gap-1.5 text-foreground border rounded-full px-8 lg:px-3 py-1.5 hover:text-foreground transition-colors duration-300">
|
<div className="py-2 lg:py-0 size-full lg:size-[220px] rounded-xl border hover:bg-card bg-card/50 relative shrink-0 overflow-hidden">
|
||||||
{props.children}
|
<div className="p-4">
|
||||||
</p>
|
<div className="flex items-center gap-1 text-3xl lg:text-5xl font-medium tracking-tight font-mono mb-1 h-[45px] lg:h-[56px]">
|
||||||
|
<AnimatedNumbers
|
||||||
|
value={props.data}
|
||||||
|
format={props.format}
|
||||||
|
suffix="+"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-foreground">{props.label}</p>
|
||||||
|
</div>
|
||||||
|
<Image
|
||||||
|
draggable={false}
|
||||||
|
src={props.src}
|
||||||
|
className={cn(
|
||||||
|
"object-cover h-full lg:h-auto absolute right-0 top-0 bottom-0 left-1/2 lg:left-0 lg:top-auto invert dark:invert-0 opacity-50 lg:opacity-100",
|
||||||
|
props.imageClassName,
|
||||||
|
)}
|
||||||
|
alt=""
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export const bridgeWallets = [
|
|||||||
createWallet("me.rainbow"),
|
createWallet("me.rainbow"),
|
||||||
createWallet("io.rabby"),
|
createWallet("io.rabby"),
|
||||||
createWallet("io.zerion.wallet"),
|
createWallet("io.zerion.wallet"),
|
||||||
|
createWallet("com.okex.wallet"),
|
||||||
];
|
];
|
||||||
|
|
||||||
export function UniversalBridgeEmbed(props: {
|
export function UniversalBridgeEmbed(props: {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import NumberFlow, { type Format } from "@number-flow/react";
|
||||||
|
import { useLayoutEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
export function AnimatedNumbers(props: {
|
||||||
|
value: number;
|
||||||
|
format?: Format;
|
||||||
|
suffix?: string;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const [value, setValue] = useState(props.value);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (ref.current) {
|
||||||
|
// when the div becomes visible, set the value to the props value
|
||||||
|
const observer = new IntersectionObserver((entries) => {
|
||||||
|
entries.forEach((entry) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
setValue(props.value);
|
||||||
|
} else {
|
||||||
|
setValue(0);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
observer.observe(ref.current);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}
|
||||||
|
}, [props.value]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={ref}>
|
||||||
|
<NumberFlow
|
||||||
|
willChange
|
||||||
|
value={value}
|
||||||
|
format={props.format}
|
||||||
|
suffix={props.suffix}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export const bridgeStats = {
|
||||||
|
supportedChains: "90+",
|
||||||
|
supportedTokens: "6700+",
|
||||||
|
supportedRoutes: "14M+",
|
||||||
|
};
|
||||||
@@ -5,6 +5,7 @@ import type { ChainMetadata } from "thirdweb/chains";
|
|||||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||||
import { fetchChain } from "@/utils/fetchChain";
|
import { fetchChain } from "@/utils/fetchChain";
|
||||||
import { BridgePageUI } from "../../components/bridge-page";
|
import { BridgePageUI } from "../../components/bridge-page";
|
||||||
|
import { bridgeStats } from "../../data";
|
||||||
import { generateTokenPairSlugs, getTokenPairData } from "./slug-map";
|
import { generateTokenPairSlugs, getTokenPairData } from "./slug-map";
|
||||||
|
|
||||||
type Params = {
|
type Params = {
|
||||||
@@ -35,8 +36,7 @@ export async function generateMetadata(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const title = getTitle(tokenMetadata);
|
const title = getTitle(tokenMetadata);
|
||||||
const description =
|
const description = `Bridge and swap ${bridgeStats.supportedTokens} tokens across ${bridgeStats.supportedChains} chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing with near-instant finality`;
|
||||||
"Bridge and swap 4500+ tokens across 85+ chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing with near-instant finality";
|
|
||||||
|
|
||||||
const result: Metadata = {
|
const result: Metadata = {
|
||||||
title,
|
title,
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
|
import { isAddress, NATIVE_TOKEN_ADDRESS } from "thirdweb";
|
||||||
import { BridgePageUI } from "./components/bridge-page";
|
import { BridgePageUI } from "./components/bridge-page";
|
||||||
|
import { bridgeStats } from "./data";
|
||||||
|
|
||||||
const title = "thirdweb Bridge: Buy, Bridge & Swap Crypto on 85+ Chains";
|
const title = `thirdweb Bridge: Buy, Bridge & Swap Crypto on ${bridgeStats.supportedChains} Chains`;
|
||||||
const description =
|
const description = `Bridge and swap ${bridgeStats.supportedTokens} tokens across ${bridgeStats.supportedChains} chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing with near-instant finality`;
|
||||||
"Bridge and swap 4500+ tokens across 85+ chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing with near-instant finality";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
description,
|
description,
|
||||||
@@ -14,11 +15,50 @@ export const metadata: Metadata = {
|
|||||||
title,
|
title,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function Page() {
|
type SearchParams = {
|
||||||
|
[key: string]: string | string[] | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function Page(props: {
|
||||||
|
searchParams: Promise<SearchParams>;
|
||||||
|
}) {
|
||||||
|
const searchParams = await props.searchParams;
|
||||||
|
|
||||||
|
const onlyAddress = (v: string) => (isAddress(v) ? v : undefined);
|
||||||
|
const onlyNumber = (v: string) =>
|
||||||
|
Number.isNaN(Number(v)) ? undefined : Number(v);
|
||||||
|
|
||||||
|
// output is buy, input is sell
|
||||||
|
const sellChain = parse(searchParams.inputChain, onlyNumber);
|
||||||
|
const sellCurrency = parse(searchParams.inputCurrency, onlyAddress);
|
||||||
|
|
||||||
|
const buyChain = parse(searchParams.outputChain, onlyNumber);
|
||||||
|
const buyCurrency = parse(searchParams.outputCurrency, onlyAddress);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BridgePageUI
|
<BridgePageUI
|
||||||
buyTab={undefined}
|
buyTab={{
|
||||||
swapTab={undefined}
|
buyToken: buyChain
|
||||||
|
? {
|
||||||
|
chainId: buyChain,
|
||||||
|
tokenAddress: buyCurrency || NATIVE_TOKEN_ADDRESS,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
swapTab={{
|
||||||
|
sellToken: sellChain
|
||||||
|
? {
|
||||||
|
chainId: sellChain,
|
||||||
|
tokenAddress: sellCurrency || NATIVE_TOKEN_ADDRESS,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
buyToken: buyChain
|
||||||
|
? {
|
||||||
|
chainId: buyChain,
|
||||||
|
tokenAddress: buyCurrency || NATIVE_TOKEN_ADDRESS,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
title={
|
title={
|
||||||
<h1 className="text-3xl md:text-6xl font-semibold tracking-tighter text-balance text-center">
|
<h1 className="text-3xl md:text-6xl font-semibold tracking-tighter text-balance text-center">
|
||||||
Bridge and Swap tokens <br className="max-sm:hidden" /> across any
|
Bridge and Swap tokens <br className="max-sm:hidden" /> across any
|
||||||
@@ -28,3 +68,13 @@ export default function Page() {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parse<T>(
|
||||||
|
value: string | string[] | undefined,
|
||||||
|
fn: (value: string) => T | undefined,
|
||||||
|
): T | undefined {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
return fn(value);
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ const loginOptions = [
|
|||||||
createWallet("io.rabby"),
|
createWallet("io.rabby"),
|
||||||
createWallet("me.rainbow"),
|
createWallet("me.rainbow"),
|
||||||
createWallet("io.zerion.wallet"),
|
createWallet("io.zerion.wallet"),
|
||||||
|
createWallet("com.okex.wallet"),
|
||||||
];
|
];
|
||||||
|
|
||||||
const inAppWalletLoginOptions = [
|
const inAppWalletLoginOptions = [
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"use client";
|
||||||
|
import { Img } from "@workspace/ui/components/img";
|
||||||
|
import { MoonIcon, SunIcon } from "lucide-react";
|
||||||
|
import { useTheme } from "next-themes";
|
||||||
|
import { ClientOnly } from "@/components/blocks/client-only";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { resolveSchemeWithErrorHandler } from "@/utils/resolveSchemeWithErrorHandler";
|
||||||
|
import { payAppThirdwebClient } from "../constants";
|
||||||
|
|
||||||
|
export function PayIdPageHeader(props: {
|
||||||
|
projectName: string;
|
||||||
|
projectIcon: string | undefined;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="border-b border-border/70">
|
||||||
|
<header className="container flex max-w-7xl justify-between py-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{props.projectIcon && (
|
||||||
|
<Img
|
||||||
|
src={
|
||||||
|
resolveSchemeWithErrorHandler({
|
||||||
|
uri: props.projectIcon,
|
||||||
|
client: payAppThirdwebClient,
|
||||||
|
}) || ""
|
||||||
|
}
|
||||||
|
alt=""
|
||||||
|
className="rounded-full size-6 object-cover"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<h2 className="text-xl font-semibold tracking-tight">
|
||||||
|
{props.projectName}
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 lg:gap-5">
|
||||||
|
<ToggleThemeButton />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToggleThemeButton(props: { className?: string }) {
|
||||||
|
const { setTheme, theme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ClientOnly
|
||||||
|
ssr={<Skeleton className="size-[36px] rounded-full border bg-accent" />}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
aria-label="Toggle theme"
|
||||||
|
className={cn(
|
||||||
|
"h-auto w-auto rounded-full p-2 text-muted-foreground hover:text-foreground",
|
||||||
|
props.className,
|
||||||
|
)}
|
||||||
|
onClick={() => {
|
||||||
|
setTheme(theme === "dark" ? "light" : "dark");
|
||||||
|
}}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
{theme === "light" ? (
|
||||||
|
<SunIcon className="size-5 " />
|
||||||
|
) : (
|
||||||
|
<MoonIcon className="size-5 " />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</ClientOnly>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,21 +1,16 @@
|
|||||||
import { ShieldCheckIcon } from "lucide-react";
|
import { cn } from "@workspace/ui/lib/utils";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { ThemeProvider } from "next-themes";
|
import { ThemeProvider } from "next-themes";
|
||||||
import { Bridge, defineChain, toTokens } from "thirdweb";
|
import { Bridge } from "thirdweb";
|
||||||
import { getChainMetadata } from "thirdweb/chains";
|
|
||||||
import { shortenAddress } from "thirdweb/utils";
|
|
||||||
import { getPaymentLink } from "@/api/universal-bridge/links";
|
import { getPaymentLink } from "@/api/universal-bridge/links";
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { NEXT_PUBLIC_THIRDWEB_API_HOST } from "@/constants/public-envs";
|
import { NEXT_PUBLIC_THIRDWEB_API_HOST } from "@/constants/public-envs";
|
||||||
import {
|
import {
|
||||||
API_SERVER_SECRET,
|
API_SERVER_SECRET,
|
||||||
DASHBOARD_THIRDWEB_SECRET_KEY,
|
DASHBOARD_THIRDWEB_SECRET_KEY,
|
||||||
} from "@/constants/server-envs";
|
} from "@/constants/server-envs";
|
||||||
import { getConfiguredThirdwebClient } from "@/constants/thirdweb.server";
|
import { getConfiguredThirdwebClient } from "@/constants/thirdweb.server";
|
||||||
import { resolveEns } from "@/lib/ens";
|
|
||||||
import { resolveSchemeWithErrorHandler } from "@/utils/resolveSchemeWithErrorHandler";
|
|
||||||
import { PayPageWidget } from "../components/client/PayPageWidget.client";
|
import { PayPageWidget } from "../components/client/PayPageWidget.client";
|
||||||
import { payAppThirdwebClient } from "../constants";
|
import { PayIdPageHeader } from "./header";
|
||||||
|
|
||||||
const title = "thirdweb Pay";
|
const title = "thirdweb Pay";
|
||||||
const description = "Fast, secure, and simple payments.";
|
const description = "Fast, secure, and simple payments.";
|
||||||
@@ -54,25 +49,9 @@ export default async function PayPage({
|
|||||||
tokenAddress: paymentLink.destinationToken.address,
|
tokenAddress: paymentLink.destinationToken.address,
|
||||||
});
|
});
|
||||||
|
|
||||||
const chainPromise = getChainMetadata(
|
const [tokens, projectMetadata] = await Promise.all([
|
||||||
// eslint-disable-next-line no-restricted-syntax
|
|
||||||
defineChain(Number(paymentLink.destinationToken.chainId)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const recipientPromise = resolveEns(
|
|
||||||
paymentLink.receiver,
|
|
||||||
getConfiguredThirdwebClient({
|
|
||||||
secretKey: DASHBOARD_THIRDWEB_SECRET_KEY,
|
|
||||||
teamId: undefined,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const [tokens, projectMetadata, chain, recipientEnsOrAddress] =
|
|
||||||
await Promise.all([
|
|
||||||
tokensPromise,
|
tokensPromise,
|
||||||
projectMetadataPromise,
|
projectMetadataPromise,
|
||||||
chainPromise,
|
|
||||||
recipientPromise,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const token = tokens[0];
|
const token = tokens[0];
|
||||||
@@ -81,122 +60,20 @@ export default async function PayPage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<div className="relative flex flex-col min-h-dvh w-full">
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
forcedTheme={theme === "light" ? "light" : "dark"}
|
defaultTheme={theme === "light" ? "light" : "dark"}
|
||||||
attribute="class"
|
attribute="class"
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
enableSystem={false}
|
enableSystem={false}
|
||||||
>
|
>
|
||||||
<div className="flex z-10 flex-col lg:flex-row h-full w-full">
|
<PayIdPageHeader
|
||||||
<header className="min-w-full lg:min-w-[500px] border-b lg:border-r lg:h-full bg-card flex flex-col gap-4 items-start p-4 lg:p-8">
|
projectIcon={projectMetadata.image || undefined}
|
||||||
<div>
|
projectName={projectMetadata.name}
|
||||||
<div className="flex flex-row items-center justify-start gap-4">
|
|
||||||
{projectMetadata.image && (
|
|
||||||
<img
|
|
||||||
src={
|
|
||||||
resolveSchemeWithErrorHandler({
|
|
||||||
uri: projectMetadata.image,
|
|
||||||
client: payAppThirdwebClient,
|
|
||||||
}) || ""
|
|
||||||
}
|
|
||||||
alt={projectMetadata.name}
|
|
||||||
width={25}
|
|
||||||
height={25}
|
|
||||||
className="rounded-full overflow-hidden"
|
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
<h2 className="text-xl font-bold">{projectMetadata.name}</h2>
|
|
||||||
</div>
|
|
||||||
{projectMetadata.description && (
|
|
||||||
<p className="mt-2 text-sm text-muted-foreground">
|
|
||||||
{projectMetadata.description}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="hidden lg:block my-4 w-full">
|
<main className="flex justify-center py-12 w-full items-center grow overflow-hidden relative">
|
||||||
{paymentLink.amount && (
|
<DotsBackgroundPattern />
|
||||||
<div className="flex flex-col gap-1 w-full my-4">
|
|
||||||
<span className="text-muted-foreground text-xs">Details</span>
|
|
||||||
<div className="font-medium flex-row flex justify-between items-center w-full">
|
|
||||||
<div className="flex flex-row items-center gap-2">
|
|
||||||
{token.iconUri && (
|
|
||||||
<img
|
|
||||||
src={resolveSchemeWithErrorHandler({
|
|
||||||
uri: token.iconUri,
|
|
||||||
client: getConfiguredThirdwebClient({
|
|
||||||
secretKey: DASHBOARD_THIRDWEB_SECRET_KEY,
|
|
||||||
teamId: undefined,
|
|
||||||
}),
|
|
||||||
})}
|
|
||||||
alt={token.name}
|
|
||||||
width={25}
|
|
||||||
height={25}
|
|
||||||
className="size-5 rounded-full overflow-hidden"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{toTokens(BigInt(paymentLink.amount), token.decimals)}{" "}
|
|
||||||
{token.symbol}
|
|
||||||
</div>
|
|
||||||
{token.prices.USD && (
|
|
||||||
<span>
|
|
||||||
$
|
|
||||||
{(
|
|
||||||
Number(token.prices.USD) *
|
|
||||||
Number(
|
|
||||||
toTokens(BigInt(paymentLink.amount), token.decimals),
|
|
||||||
)
|
|
||||||
).toFixed(2)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{chain && (
|
|
||||||
<div className="flex flex-col gap-1 w-full my-4">
|
|
||||||
<span className="text-muted-foreground text-xs">Network</span>
|
|
||||||
<div className="font-medium flex-row flex justify-between items-center w-full">
|
|
||||||
<div className="flex flex-row items-center gap-2">
|
|
||||||
{chain.icon?.url && (
|
|
||||||
<img
|
|
||||||
src={resolveSchemeWithErrorHandler({
|
|
||||||
uri: chain.icon.url,
|
|
||||||
client: getConfiguredThirdwebClient({
|
|
||||||
secretKey: DASHBOARD_THIRDWEB_SECRET_KEY,
|
|
||||||
teamId: undefined,
|
|
||||||
}),
|
|
||||||
})}
|
|
||||||
alt={chain.name}
|
|
||||||
width={chain.icon.width}
|
|
||||||
height={chain.icon.height}
|
|
||||||
className="size-5 rounded-full overflow-hidden"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{chain.name}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{recipientEnsOrAddress.ensName ||
|
|
||||||
(recipientEnsOrAddress.address && (
|
|
||||||
<div className="flex flex-col gap-1 w-full my-4">
|
|
||||||
<span className="text-muted-foreground text-xs">Seller</span>
|
|
||||||
<div className="font-medium flex-row flex justify-between items-center w-full">
|
|
||||||
{recipientEnsOrAddress.ensName ??
|
|
||||||
shortenAddress(recipientEnsOrAddress.address)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="mt-auto hidden lg:block">
|
|
||||||
<Badge className="flex items-center gap-1.5 bg-purple-100 text-purple-800 border-purple-200 dark:bg-purple-950 dark:text-purple-300 dark:border-purple-800">
|
|
||||||
<ShieldCheckIcon className="size-3" />
|
|
||||||
Secured by thirdweb
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<main className="flex justify-center p-12 w-full items-center">
|
|
||||||
<PayPageWidget
|
<PayPageWidget
|
||||||
amount={paymentLink.amount ? BigInt(paymentLink.amount) : undefined}
|
amount={paymentLink.amount ? BigInt(paymentLink.amount) : undefined}
|
||||||
chainId={Number(paymentLink.destinationToken.chainId)}
|
chainId={Number(paymentLink.destinationToken.chainId)}
|
||||||
@@ -210,8 +87,8 @@ export default async function PayPage({
|
|||||||
token={token}
|
token={token}
|
||||||
/>
|
/>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,7 +105,24 @@ async function getProjectMetadata(clientId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { data } = (await response.json()) as {
|
const { data } = (await response.json()) as {
|
||||||
data: { name: string; image: string | null; description: string | null };
|
data: { name: string; image: string | null };
|
||||||
};
|
};
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DotsBackgroundPattern(props: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none absolute -inset-x-36 -inset-y-24 text-foreground/20 dark:text-muted-foreground/15 hidden lg:block",
|
||||||
|
props.className,
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
backgroundImage: "radial-gradient(currentColor 1px, transparent 1px)",
|
||||||
|
backgroundSize: "24px 24px",
|
||||||
|
maskImage:
|
||||||
|
"radial-gradient(ellipse 100% 100% at 50% 50%, black 30%, transparent 50%)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { cn } from "@workspace/ui/lib/utils";
|
||||||
import { payAppThirdwebClient } from "app/pay/constants";
|
import { payAppThirdwebClient } from "app/pay/constants";
|
||||||
import { useTheme } from "next-themes";
|
import { useTheme } from "next-themes";
|
||||||
import { createThirdwebClient, NATIVE_TOKEN_ADDRESS, toTokens } from "thirdweb";
|
import { createThirdwebClient, NATIVE_TOKEN_ADDRESS, toTokens } from "thirdweb";
|
||||||
@@ -63,7 +64,12 @@ export function PayPageWidget({
|
|||||||
client={
|
client={
|
||||||
clientId ? createThirdwebClient({ clientId }) : payAppThirdwebClient
|
clientId ? createThirdwebClient({ clientId }) : payAppThirdwebClient
|
||||||
}
|
}
|
||||||
image={image}
|
className={cn(
|
||||||
|
"shadow-xl",
|
||||||
|
!image &&
|
||||||
|
"[&_.tw-header-image]:invert dark:[&_.tw-header-image]:invert-0",
|
||||||
|
)}
|
||||||
|
image={image || "/assets/pay/general-pay.png"}
|
||||||
name={name}
|
name={name}
|
||||||
onSuccess={() => {
|
onSuccess={() => {
|
||||||
reportPaymentLinkBuySuccessful();
|
reportPaymentLinkBuySuccessful();
|
||||||
|
|||||||
@@ -1,399 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { payAppThirdwebClient } from "app/pay/constants";
|
|
||||||
import { ChevronDownIcon, CreditCardIcon } from "lucide-react";
|
|
||||||
import { useCallback, useId, useMemo, useState } from "react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import {
|
|
||||||
createThirdwebClient,
|
|
||||||
defineChain,
|
|
||||||
getContract,
|
|
||||||
type ThirdwebClient,
|
|
||||||
toUnits,
|
|
||||||
} from "thirdweb";
|
|
||||||
import { getCurrencyMetadata } from "thirdweb/extensions/erc20";
|
|
||||||
import { resolveScheme, upload } from "thirdweb/storage";
|
|
||||||
import { FileInput } from "@/components/blocks/FileInput";
|
|
||||||
import { SingleNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
|
||||||
import { TokenSelector } from "@/components/blocks/TokenSelector";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
import { resolveEns } from "@/lib/ens";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
export function PaymentLinkForm() {
|
|
||||||
const [chainId, setChainId] = useState<number>();
|
|
||||||
const [recipientAddress, setRecipientAddress] = useState("");
|
|
||||||
// TODO - clean this up later
|
|
||||||
const [tokenAddressWithChain, setTokenAddressWithChain] = useState("");
|
|
||||||
const [amount, setAmount] = useState("");
|
|
||||||
const [title, setTitle] = useState("");
|
|
||||||
const [image, setImage] = useState<File | null>(null);
|
|
||||||
const [imageUri, setImageUri] = useState<string>("");
|
|
||||||
const [uploadingImage, setUploadingImage] = useState(false);
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
|
||||||
const [paymentUrl, setPaymentUrl] = useState<string>("");
|
|
||||||
|
|
||||||
const isFormComplete = useMemo(() => {
|
|
||||||
return chainId && recipientAddress && tokenAddressWithChain && amount;
|
|
||||||
}, [chainId, recipientAddress, tokenAddressWithChain, amount]);
|
|
||||||
|
|
||||||
const handleImageUpload = useCallback(async (file: File) => {
|
|
||||||
try {
|
|
||||||
setImage(file);
|
|
||||||
setUploadingImage(true);
|
|
||||||
|
|
||||||
const uploadClient = createThirdwebClient({
|
|
||||||
clientId: "7ae789153cf9ecde8f35649f2d8a4333",
|
|
||||||
});
|
|
||||||
const uri = await upload({
|
|
||||||
client: uploadClient,
|
|
||||||
files: [file],
|
|
||||||
});
|
|
||||||
|
|
||||||
// eslint-disable-next-line no-restricted-syntax
|
|
||||||
const resolvedUrl = resolveScheme({
|
|
||||||
client: uploadClient,
|
|
||||||
uri,
|
|
||||||
});
|
|
||||||
|
|
||||||
setImageUri(resolvedUrl);
|
|
||||||
toast.success("Image uploaded successfully");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error uploading image:", error);
|
|
||||||
toast.error("Failed to upload image");
|
|
||||||
setImage(null);
|
|
||||||
} finally {
|
|
||||||
setUploadingImage(false);
|
|
||||||
}
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleSubmit = useCallback(
|
|
||||||
async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setIsLoading(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (
|
|
||||||
!chainId ||
|
|
||||||
!recipientAddress ||
|
|
||||||
!tokenAddressWithChain ||
|
|
||||||
!amount
|
|
||||||
) {
|
|
||||||
throw new Error("All fields are required");
|
|
||||||
}
|
|
||||||
|
|
||||||
const inputs = await parseInputs(
|
|
||||||
payAppThirdwebClient,
|
|
||||||
chainId,
|
|
||||||
tokenAddressWithChain,
|
|
||||||
recipientAddress,
|
|
||||||
amount,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Build payment URL
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
amount: inputs.amount.toString(),
|
|
||||||
chainId: inputs.chainId.toString(),
|
|
||||||
clientId: payAppThirdwebClient.clientId,
|
|
||||||
recipientAddress: inputs.recipientAddress,
|
|
||||||
tokenAddress: inputs.tokenAddress,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add title as name parameter if provided
|
|
||||||
if (title) {
|
|
||||||
params.set("name", title);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add image URI if available
|
|
||||||
if (imageUri) {
|
|
||||||
params.set("image", imageUri);
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `${window.location.origin}/pay?${params.toString()}`;
|
|
||||||
setPaymentUrl(url);
|
|
||||||
toast.success("Payment created!");
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "An error occurred");
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[amount, chainId, imageUri, recipientAddress, title, tokenAddressWithChain],
|
|
||||||
);
|
|
||||||
|
|
||||||
const handlePreview = useCallback(async () => {
|
|
||||||
if (!chainId || !recipientAddress || !tokenAddressWithChain || !amount) {
|
|
||||||
toast.error("Please fill in all fields first");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const inputs = await parseInputs(
|
|
||||||
payAppThirdwebClient,
|
|
||||||
chainId,
|
|
||||||
tokenAddressWithChain,
|
|
||||||
recipientAddress,
|
|
||||||
amount,
|
|
||||||
);
|
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
amount: inputs.amount.toString(),
|
|
||||||
chainId: inputs.chainId.toString(),
|
|
||||||
clientId: payAppThirdwebClient.clientId,
|
|
||||||
recipientAddress: inputs.recipientAddress,
|
|
||||||
tokenAddress: inputs.tokenAddress,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add title as name parameter if provided
|
|
||||||
if (title) {
|
|
||||||
params.set("name", title);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add image URI if available
|
|
||||||
if (imageUri) {
|
|
||||||
params.set("image", imageUri);
|
|
||||||
}
|
|
||||||
|
|
||||||
window.open(`/pay?${params.toString()}`, "_blank");
|
|
||||||
} catch (err) {
|
|
||||||
toast.error(err instanceof Error ? err.message : "An error occurred");
|
|
||||||
}
|
|
||||||
}, [
|
|
||||||
amount,
|
|
||||||
chainId,
|
|
||||||
imageUri,
|
|
||||||
recipientAddress,
|
|
||||||
title,
|
|
||||||
tokenAddressWithChain,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const [selectedChainId, selectedTokenAddress] = tokenAddressWithChain
|
|
||||||
? tokenAddressWithChain.split(":")
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const recipientId = useId();
|
|
||||||
const amountId = useId();
|
|
||||||
const titleId = useId();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card className="mx-auto w-full max-w-[500px]">
|
|
||||||
<CardHeader>
|
|
||||||
<div className="flex flex-col items-center gap-2 sm:flex-row sm:gap-2">
|
|
||||||
<div className="rounded-lg border border-muted p-1.5 sm:p-2">
|
|
||||||
<CreditCardIcon className="size-5 sm:size-6" />
|
|
||||||
</div>
|
|
||||||
<CardTitle className="text-center sm:text-left">
|
|
||||||
Create a Payment
|
|
||||||
</CardTitle>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<form className="space-y-6" onSubmit={handleSubmit}>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm">Network</Label>
|
|
||||||
<SingleNetworkSelector
|
|
||||||
chainId={chainId}
|
|
||||||
className="w-full"
|
|
||||||
client={payAppThirdwebClient}
|
|
||||||
disableTestnets
|
|
||||||
onChange={setChainId}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm">Token</Label>
|
|
||||||
<TokenSelector
|
|
||||||
addNativeTokenIfMissing={false}
|
|
||||||
chainId={chainId ?? undefined}
|
|
||||||
className="w-full"
|
|
||||||
client={payAppThirdwebClient}
|
|
||||||
disabled={!chainId}
|
|
||||||
enabled={!!chainId}
|
|
||||||
onChange={(value) => {
|
|
||||||
setTokenAddressWithChain(`${value.chainId}:${value.address}`);
|
|
||||||
}}
|
|
||||||
selectedToken={
|
|
||||||
selectedChainId && selectedTokenAddress
|
|
||||||
? {
|
|
||||||
address: selectedTokenAddress,
|
|
||||||
chainId: Number(selectedChainId),
|
|
||||||
}
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
showCheck={false}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm" htmlFor={recipientId}>
|
|
||||||
Recipient Address
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
className="w-full"
|
|
||||||
id={recipientId}
|
|
||||||
onChange={(e) => setRecipientAddress(e.target.value)}
|
|
||||||
placeholder="Address or ENS"
|
|
||||||
required
|
|
||||||
value={recipientAddress}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm" htmlFor={amountId}>
|
|
||||||
Amount
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
className="w-full"
|
|
||||||
id={amountId}
|
|
||||||
onChange={(e) => setAmount(e.target.value)}
|
|
||||||
placeholder="0.0"
|
|
||||||
required
|
|
||||||
step="any"
|
|
||||||
type="number"
|
|
||||||
value={amount}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Button
|
|
||||||
className={cn(
|
|
||||||
"flex w-full items-center justify-between px-0 text-muted-foreground hover:bg-transparent",
|
|
||||||
)}
|
|
||||||
onClick={() => setShowAdvanced(!showAdvanced)}
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
>
|
|
||||||
<span>Advanced Options</span>
|
|
||||||
<ChevronDownIcon
|
|
||||||
className={`size-4 transition-transform duration-200 ease-in-out ${
|
|
||||||
showAdvanced ? "rotate-180" : ""
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"grid transition-all duration-200 ease-in-out",
|
|
||||||
showAdvanced
|
|
||||||
? "grid-rows-[1fr] opacity-100"
|
|
||||||
: "grid-rows-[0fr] opacity-0",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className={cn(showAdvanced ? "" : "overflow-hidden")}>
|
|
||||||
<div className="space-y-3">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm" htmlFor={titleId}>
|
|
||||||
Title
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
className="w-full"
|
|
||||||
id={titleId}
|
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
|
||||||
placeholder="Payment for..."
|
|
||||||
value={title}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label className="font-medium text-sm">Image</Label>
|
|
||||||
<div className="w-full">
|
|
||||||
<FileInput
|
|
||||||
accept={{ "image/*": [] }}
|
|
||||||
className="!rounded-md aspect-square h-24 w-full"
|
|
||||||
client={payAppThirdwebClient}
|
|
||||||
helperText="image"
|
|
||||||
isDisabled={uploadingImage}
|
|
||||||
isDisabledText="Uploading..."
|
|
||||||
selectOrUpload="Upload"
|
|
||||||
setValue={handleImageUpload}
|
|
||||||
value={image || imageUri}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col space-y-4">
|
|
||||||
{paymentUrl && (
|
|
||||||
<CopyTextButton
|
|
||||||
className="w-full justify-between truncate bg-background px-3 py-2"
|
|
||||||
copyIconPosition="right"
|
|
||||||
textToCopy={paymentUrl}
|
|
||||||
textToShow={paymentUrl}
|
|
||||||
tooltip="Copy Payment Link"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<Button
|
|
||||||
className="flex-1"
|
|
||||||
disabled={isLoading || !isFormComplete}
|
|
||||||
onClick={handlePreview}
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
>
|
|
||||||
Preview
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
className="flex-1"
|
|
||||||
disabled={isLoading || !isFormComplete}
|
|
||||||
type="submit"
|
|
||||||
>
|
|
||||||
{isLoading ? "Creating..." : "Create"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function parseInputs(
|
|
||||||
client: ThirdwebClient,
|
|
||||||
chainId: number,
|
|
||||||
tokenAddressWithChain: string,
|
|
||||||
recipientAddressOrEns: string,
|
|
||||||
decimalAmount: string,
|
|
||||||
) {
|
|
||||||
const [_chainId, tokenAddress] = tokenAddressWithChain.split(":");
|
|
||||||
if (Number(_chainId) !== chainId) {
|
|
||||||
throw new Error("Chain ID does not match token chain");
|
|
||||||
}
|
|
||||||
if (!tokenAddress) {
|
|
||||||
throw new Error("Missing token address");
|
|
||||||
}
|
|
||||||
|
|
||||||
const ensPromise = resolveEns(recipientAddressOrEns, client);
|
|
||||||
const currencyPromise = getCurrencyMetadata({
|
|
||||||
contract: getContract({
|
|
||||||
address: tokenAddress,
|
|
||||||
// eslint-disable-next-line no-restricted-syntax
|
|
||||||
chain: defineChain(chainId),
|
|
||||||
client,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const [ens, currencyMetadata] = await Promise.all([
|
|
||||||
ensPromise,
|
|
||||||
currencyPromise,
|
|
||||||
]);
|
|
||||||
if (!ens.address) {
|
|
||||||
throw new Error("Invalid recipient address");
|
|
||||||
}
|
|
||||||
|
|
||||||
const amountInWei = toUnits(decimalAmount, currencyMetadata.decimals);
|
|
||||||
|
|
||||||
return {
|
|
||||||
amount: amountInWei,
|
|
||||||
chainId,
|
|
||||||
recipientAddress: ens.address,
|
|
||||||
tokenAddress,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
export type PayParams = {
|
|
||||||
chainId: string;
|
|
||||||
recipientAddress: string;
|
|
||||||
tokenAddress: string;
|
|
||||||
amount: string;
|
|
||||||
name?: string;
|
|
||||||
image?: string;
|
|
||||||
theme?: "light" | "dark";
|
|
||||||
redirectUri?: string;
|
|
||||||
clientId?: string;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"use client";
|
||||||
|
import { MoonIcon, SunIcon } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useTheme } from "next-themes";
|
||||||
|
import { ClientOnly } from "@/components/blocks/client-only";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ThirdwebMiniLogo } from "../../(app)/components/ThirdwebMiniLogo";
|
||||||
|
|
||||||
|
export function PayLandingHeader(props: { containerClassName?: string }) {
|
||||||
|
return (
|
||||||
|
<div className="border-b border-border/70">
|
||||||
|
<header
|
||||||
|
className={cn(
|
||||||
|
"container flex max-w-7xl justify-between py-4",
|
||||||
|
props.containerClassName,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-6">
|
||||||
|
<Link className="flex items-center gap-2" href="/home">
|
||||||
|
<ThirdwebMiniLogo className="h-5" />
|
||||||
|
<span className="font-bold text-2xl tracking-tight">thirdweb</span>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 lg:gap-5">
|
||||||
|
<ToggleThemeButton />
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToggleThemeButton(props: { className?: string }) {
|
||||||
|
const { setTheme, theme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ClientOnly
|
||||||
|
ssr={<Skeleton className="size-[36px] rounded-full border bg-accent" />}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
aria-label="Toggle theme"
|
||||||
|
className={cn(
|
||||||
|
"h-auto w-auto rounded-full p-2 text-muted-foreground hover:text-foreground",
|
||||||
|
props.className,
|
||||||
|
)}
|
||||||
|
onClick={() => {
|
||||||
|
setTheme(theme === "dark" ? "light" : "dark");
|
||||||
|
}}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
{theme === "light" ? (
|
||||||
|
<SunIcon className="size-5 " />
|
||||||
|
) : (
|
||||||
|
<MoonIcon className="size-5 " />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</ClientOnly>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useTheme } from "next-themes";
|
||||||
|
import { BuyWidget, type BuyWidgetProps } from "thirdweb/react";
|
||||||
|
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||||
|
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||||
|
import { payLandingWallets } from "./wallets";
|
||||||
|
|
||||||
|
const client = getClientThirdwebClient();
|
||||||
|
|
||||||
|
export function StyledBuyWidget(
|
||||||
|
props: Omit<
|
||||||
|
BuyWidgetProps,
|
||||||
|
"client" | "theme" | "onSuccess" | "onError" | "onCancel"
|
||||||
|
> & {
|
||||||
|
successUrl?: string;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { theme } = useTheme();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<BuyWidget
|
||||||
|
{...props}
|
||||||
|
theme={getSDKTheme(theme === "light" ? "light" : "dark")}
|
||||||
|
client={client}
|
||||||
|
className="shadow-xl"
|
||||||
|
connectOptions={{
|
||||||
|
wallets: payLandingWallets,
|
||||||
|
}}
|
||||||
|
onSuccess={() => {
|
||||||
|
if (props.successUrl) {
|
||||||
|
try {
|
||||||
|
const url = new URL(props.successUrl);
|
||||||
|
url.searchParams.set("success", "true");
|
||||||
|
window.location.href = url.toString();
|
||||||
|
} catch (error) {
|
||||||
|
// Log URL construction error for debugging
|
||||||
|
console.error(
|
||||||
|
"Failed to construct redirect URL:",
|
||||||
|
props.successUrl,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { createWallet } from "thirdweb/wallets";
|
||||||
|
import { appMetadata } from "@/constants/connect";
|
||||||
|
|
||||||
|
export const payLandingWallets = [
|
||||||
|
createWallet("io.metamask"),
|
||||||
|
createWallet("com.coinbase.wallet", {
|
||||||
|
appMetadata,
|
||||||
|
}),
|
||||||
|
createWallet("me.rainbow"),
|
||||||
|
createWallet("io.rabby"),
|
||||||
|
createWallet("io.zerion.wallet"),
|
||||||
|
createWallet("com.okex.wallet"),
|
||||||
|
];
|
||||||
@@ -18,15 +18,11 @@ export default async function PayLayout({
|
|||||||
<html lang="en" suppressHydrationWarning>
|
<html lang="en" suppressHydrationWarning>
|
||||||
<body
|
<body
|
||||||
className={cn(
|
className={cn(
|
||||||
"h-screen w-screen bg-background font-sans antialiased",
|
"min-h-dvh w-screen bg-background font-sans antialiased flex flex-col",
|
||||||
fontSans.variable,
|
fontSans.variable,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<PayProviders>
|
<PayProviders>{children}</PayProviders>
|
||||||
<div className="relative mx-auto flex h-full w-full items-center justify-center overflow-x-hidden overflow-y-scroll">
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</PayProviders>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,12 +1,9 @@
|
|||||||
|
import { cn } from "@workspace/ui/lib/utils";
|
||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { ThemeProvider } from "next-themes";
|
import { ThemeProvider } from "next-themes";
|
||||||
import { createThirdwebClient, defineChain, getContract } from "thirdweb";
|
import { defineChain, isAddress } from "thirdweb";
|
||||||
import { getCurrencyMetadata } from "thirdweb/extensions/erc20";
|
import { PayLandingHeader } from "./landing/header";
|
||||||
import { checksumAddress } from "thirdweb/utils";
|
import { StyledBuyWidget } from "./landing/styled-buy-widget";
|
||||||
import { PaymentLinkForm } from "./components/client/PaymentLinkForm.client";
|
|
||||||
import { PayPageWidget } from "./components/client/PayPageWidget.client";
|
|
||||||
import type { PayParams } from "./components/types";
|
|
||||||
import { payAppThirdwebClient } from "./constants";
|
|
||||||
|
|
||||||
const title = "thirdweb Payments";
|
const title = "thirdweb Payments";
|
||||||
const description = "Fast, secure, and simple payments.";
|
const description = "Fast, secure, and simple payments.";
|
||||||
@@ -20,97 +17,97 @@ export const metadata: Metadata = {
|
|||||||
title,
|
title,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default async function PayPage({
|
type SearchParams = {
|
||||||
searchParams,
|
[key: string]: string | string[] | undefined;
|
||||||
}: {
|
};
|
||||||
searchParams: Promise<PayParams>;
|
|
||||||
|
const onlyAddress = (v: string) => (isAddress(v) ? v : undefined);
|
||||||
|
const onlyNumber = (v: string) =>
|
||||||
|
Number.isNaN(Number(v)) ? undefined : Number(v);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates and normalizes a URL string.
|
||||||
|
* Only allows http: and https: protocols with a valid hostname.
|
||||||
|
* @returns normalized URL string on success, undefined on failure
|
||||||
|
*/
|
||||||
|
const onlyUrl = (v: string): string | undefined => {
|
||||||
|
try {
|
||||||
|
const url = new URL(v);
|
||||||
|
// Only allow http or https protocols
|
||||||
|
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
// Ensure hostname is non-empty
|
||||||
|
if (!url.hostname) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
// Return normalized URL
|
||||||
|
return url.toString();
|
||||||
|
} catch {
|
||||||
|
// Invalid URL format
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function PayPage(props: {
|
||||||
|
searchParams: Promise<SearchParams>;
|
||||||
}) {
|
}) {
|
||||||
const params = await searchParams;
|
const searchParams = await props.searchParams;
|
||||||
|
|
||||||
|
const receiver = parse(searchParams.receiver, onlyAddress);
|
||||||
|
const token = parse(searchParams.token, onlyAddress);
|
||||||
|
const chain = parse(searchParams.chain, onlyNumber);
|
||||||
|
const amount = parse(searchParams.amount, onlyNumber);
|
||||||
|
const successUrl = parse(searchParams.successUrl, onlyUrl);
|
||||||
|
|
||||||
// If no query parameters are provided, show the form
|
|
||||||
if (
|
|
||||||
!params.chainId &&
|
|
||||||
!params.recipientAddress &&
|
|
||||||
!params.tokenAddress &&
|
|
||||||
!params.amount
|
|
||||||
) {
|
|
||||||
return (
|
return (
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
forcedTheme={params.theme === "light" ? "light" : "dark"}
|
|
||||||
attribute="class"
|
attribute="class"
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
enableSystem={false}
|
enableSystem={false}
|
||||||
>
|
>
|
||||||
<PaymentLinkForm />
|
<div className="flex flex-col grow">
|
||||||
</ThemeProvider>
|
<PayLandingHeader />
|
||||||
);
|
<div className="flex-1 flex items-center justify-center py-20 relative overflow-hidden">
|
||||||
}
|
<DotsBackgroundPattern />
|
||||||
|
<StyledBuyWidget
|
||||||
// Validate query parameters
|
|
||||||
if (Array.isArray(params.chainId)) {
|
|
||||||
throw new Error("A single chainId parameter is required.");
|
|
||||||
}
|
|
||||||
if (Array.isArray(params.recipientAddress)) {
|
|
||||||
throw new Error("A single recipientAddress parameter is required.");
|
|
||||||
}
|
|
||||||
if (Array.isArray(params.tokenAddress)) {
|
|
||||||
throw new Error("A single tokenAddress parameter is required.");
|
|
||||||
}
|
|
||||||
if (Array.isArray(params.amount)) {
|
|
||||||
throw new Error("A single amount parameter is required.");
|
|
||||||
}
|
|
||||||
if (Array.isArray(params.clientId)) {
|
|
||||||
throw new Error("A single clientId parameter is required.");
|
|
||||||
}
|
|
||||||
if (Array.isArray(params.redirectUri)) {
|
|
||||||
throw new Error("A single redirectUri parameter is required.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use any provided clientId or use the dashboard client
|
|
||||||
const client =
|
|
||||||
params.clientId && !Array.isArray(params.clientId)
|
|
||||||
? createThirdwebClient({ clientId: params.clientId })
|
|
||||||
: payAppThirdwebClient;
|
|
||||||
|
|
||||||
const tokenContract = getContract({
|
|
||||||
address: params.tokenAddress,
|
|
||||||
// eslint-disable-next-line no-restricted-syntax
|
// eslint-disable-next-line no-restricted-syntax
|
||||||
chain: defineChain(Number(params.chainId)),
|
chain={chain ? defineChain(chain) : undefined}
|
||||||
client: payAppThirdwebClient,
|
tokenAddress={token}
|
||||||
});
|
receiverAddress={receiver}
|
||||||
const {
|
amount={amount ? amount.toString() : undefined}
|
||||||
symbol,
|
successUrl={successUrl}
|
||||||
decimals,
|
|
||||||
name: tokenName,
|
|
||||||
} = await getCurrencyMetadata({
|
|
||||||
contract: tokenContract,
|
|
||||||
});
|
|
||||||
const token = {
|
|
||||||
address: checksumAddress(params.tokenAddress),
|
|
||||||
chainId: Number(params.chainId),
|
|
||||||
decimals,
|
|
||||||
name: tokenName,
|
|
||||||
symbol,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ThemeProvider
|
|
||||||
forcedTheme={params.theme === "light" ? "light" : "dark"}
|
|
||||||
attribute="class"
|
|
||||||
disableTransitionOnChange
|
|
||||||
enableSystem={false}
|
|
||||||
>
|
|
||||||
<PayPageWidget
|
|
||||||
amount={BigInt(params.amount)}
|
|
||||||
chainId={Number(params.chainId)}
|
|
||||||
clientId={client.clientId}
|
|
||||||
image={params.image}
|
|
||||||
name={params.name}
|
|
||||||
purchaseData={undefined}
|
|
||||||
recipientAddress={params.recipientAddress}
|
|
||||||
redirectUri={params.redirectUri}
|
|
||||||
token={token}
|
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parse<T>(
|
||||||
|
value: string | string[] | undefined,
|
||||||
|
fn: (value: string) => T | undefined,
|
||||||
|
): T | undefined {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
return fn(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function DotsBackgroundPattern(props: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"pointer-events-none absolute -inset-x-36 -inset-y-24 text-foreground/20 dark:text-muted-foreground/20 hidden lg:block",
|
||||||
|
props.className,
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
backgroundImage: "radial-gradient(currentColor 1px, transparent 1px)",
|
||||||
|
backgroundSize: "24px 24px",
|
||||||
|
maskImage:
|
||||||
|
"radial-gradient(ellipse 100% 100% at 50% 50%, black 30%, transparent 50%)",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ export async function GET(request: NextRequest) {
|
|||||||
// const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_SMART_WALLET as string;
|
// const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_SMART_WALLET as string;
|
||||||
const ENGINE_VAULT_ACCESS_TOKEN = process.env
|
const ENGINE_VAULT_ACCESS_TOKEN = process.env
|
||||||
.ENGINE_VAULT_ACCESS_TOKEN as string;
|
.ENGINE_VAULT_ACCESS_TOKEN as string;
|
||||||
// const API_URL = `https://${process.env.NEXT_PUBLIC_API_URL || "api.thirdweb.com"}`;
|
const API_URL = `https://${process.env.NEXT_PUBLIC_API_URL || "api.thirdweb.com"}`;
|
||||||
const API_URL = "http://localhost:3030";
|
|
||||||
|
|
||||||
const twFacilitator = facilitator({
|
const twFacilitator = facilitator({
|
||||||
baseUrl: `${API_URL}/v1/payments/x402`,
|
baseUrl: `${API_URL}/v1/payments/x402`,
|
||||||
@@ -42,7 +41,7 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
const amount = queryParams.get("amount") || "0.01";
|
const amount = queryParams.get("amount") || "0.01";
|
||||||
const payTo = queryParams.get("payTo") ?? undefined;
|
const payTo = queryParams.get("payTo") ?? undefined;
|
||||||
const tokenAddress = queryParams.get("tokenAddress") || token.address;
|
const tokenAddress = queryParams.get("tokenAddress");
|
||||||
const decimals = queryParams.get("decimals") || token.decimals.toString();
|
const decimals = queryParams.get("decimals") || token.decimals.toString();
|
||||||
const waitUntil =
|
const waitUntil =
|
||||||
(queryParams.get("waitUntil") as "simulated" | "submitted" | "confirmed") ||
|
(queryParams.get("waitUntil") as "simulated" | "submitted" | "confirmed") ||
|
||||||
@@ -54,13 +53,15 @@ export async function GET(request: NextRequest) {
|
|||||||
paymentData,
|
paymentData,
|
||||||
network: defineChain(Number(chainId)),
|
network: defineChain(Number(chainId)),
|
||||||
payTo,
|
payTo,
|
||||||
price: {
|
price: tokenAddress
|
||||||
|
? {
|
||||||
amount: toUnits(amount, parseInt(decimals)).toString(),
|
amount: toUnits(amount, parseInt(decimals)).toString(),
|
||||||
asset: {
|
asset: {
|
||||||
address: tokenAddress as `0x${string}`,
|
address: tokenAddress as `0x${string}`,
|
||||||
decimals: decimals ? parseInt(decimals) : token.decimals,
|
decimals: decimals ? parseInt(decimals) : token.decimals,
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
|
: amount,
|
||||||
routeConfig: {
|
routeConfig: {
|
||||||
description: "Access to paid content",
|
description: "Access to paid content",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export default function Page() {
|
|||||||
<PageLayout
|
<PageLayout
|
||||||
icon={PlaneIcon}
|
icon={PlaneIcon}
|
||||||
description={description}
|
description={description}
|
||||||
docsLink="https://thirdweb-engine.apidocumentation.com/reference#tag/erc20/POST/contract/{chain}/{contractAddress}/erc20/mint-batch-to?utm_source=playground"
|
docsLink="https://engine.thirdweb.com/reference"
|
||||||
title={title}
|
title={title}
|
||||||
>
|
>
|
||||||
<EngineAirdropPreview />
|
<EngineAirdropPreview />
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ export default function Page() {
|
|||||||
<PageLayout
|
<PageLayout
|
||||||
icon={StampIcon}
|
icon={StampIcon}
|
||||||
description={description}
|
description={description}
|
||||||
docsLink="https://thirdweb-engine.apidocumentation.com/reference#tag/erc1155/POST/contract/{chain}/{contractAddress}/erc1155/mint-to?utm_source=playground"
|
docsLink="https://engine.thirdweb.com/reference"
|
||||||
title={title}
|
title={title}
|
||||||
>
|
>
|
||||||
<EngineMintPreview />
|
<EngineMintPreview />
|
||||||
|
|||||||
@@ -1,172 +0,0 @@
|
|||||||
import {
|
|
||||||
Callout,
|
|
||||||
OpenSourceCard,
|
|
||||||
createMetadata,
|
|
||||||
InstallTabs,
|
|
||||||
SDKCard,
|
|
||||||
Grid,
|
|
||||||
ArticleIconCard,
|
|
||||||
Tabs,
|
|
||||||
TabsList,
|
|
||||||
TabsTrigger,
|
|
||||||
TabsContent,
|
|
||||||
} from "@doc";
|
|
||||||
import {
|
|
||||||
ReactIcon,
|
|
||||||
TypeScriptIcon,
|
|
||||||
UnityIcon,
|
|
||||||
DotNetIcon,
|
|
||||||
UnrealEngineIcon,
|
|
||||||
} from "@/icons";
|
|
||||||
import { ExternalLink } from "lucide-react";
|
|
||||||
|
|
||||||
export const metadata = createMetadata({
|
|
||||||
image: {
|
|
||||||
title: "Find Routes",
|
|
||||||
icon: "payments",
|
|
||||||
},
|
|
||||||
title: "Find Routes",
|
|
||||||
description: "Find available routes for bridging, swapping, and paying.",
|
|
||||||
});
|
|
||||||
|
|
||||||
# Find Routes
|
|
||||||
|
|
||||||
Use thirdweb's `Bridge.routes` utility to find all routes between tokens.
|
|
||||||
|
|
||||||
### Get All Routes
|
|
||||||
|
|
||||||
Retrieve all supported routes:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
const routes = await Bridge.routes({
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
This returns an array of route objects with information about supported token pairs:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
[
|
|
||||||
{
|
|
||||||
destinationToken: {
|
|
||||||
address: "0x12c88a3C30A7AaBC1dd7f2c08a97145F5DCcD830",
|
|
||||||
chainId: 1,
|
|
||||||
decimals: 18,
|
|
||||||
iconUri: "https://assets.coingecko.com/coins/images/37207/standard/G.jpg",
|
|
||||||
name: "G7",
|
|
||||||
symbol: "G7",
|
|
||||||
},
|
|
||||||
originToken: {
|
|
||||||
address: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
chainId: 480,
|
|
||||||
decimals: 18,
|
|
||||||
iconUri: "https://assets.relay.link/icons/1/light.png",
|
|
||||||
name: "Ether",
|
|
||||||
symbol: "ETH",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// ... more routes
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
### Filter Routes by Origin
|
|
||||||
|
|
||||||
Get all routes starting from a specific chain and token:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
// Get all routes starting from mainnet ETH
|
|
||||||
const routes = await Bridge.routes({
|
|
||||||
originChainId: 1,
|
|
||||||
originTokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Filter Routes by Destination
|
|
||||||
|
|
||||||
Find routes that end at a specific destination:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
// Get all routes ending at USDC on Optimism
|
|
||||||
const routes = await Bridge.routes({
|
|
||||||
destinationChainId: 10,
|
|
||||||
destinationTokenAddress: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Filter Routes by Both Origin and Destination
|
|
||||||
|
|
||||||
Find direct routes between specific token pairs:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
// Get routes from mainnet ETH to USDC on Optimism
|
|
||||||
const routes = await Bridge.routes({
|
|
||||||
originChainId: 1,
|
|
||||||
originTokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
destinationChainId: 10,
|
|
||||||
destinationTokenAddress: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Pagination
|
|
||||||
|
|
||||||
For large result sets, use pagination to retrieve routes in chunks:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
// Get the first 10 routes starting from mainnet ETH
|
|
||||||
const routes = await Bridge.routes({
|
|
||||||
originChainId: 1,
|
|
||||||
originTokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
limit: 10,
|
|
||||||
offset: 0,
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get the next 10 routes
|
|
||||||
const nextRoutes = await Bridge.routes({
|
|
||||||
originChainId: 1,
|
|
||||||
originTokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
limit: 10,
|
|
||||||
offset: 10,
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Limit Route Complexity
|
|
||||||
|
|
||||||
Control the maximum number of steps in the returned routes:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Bridge } from "thirdweb";
|
|
||||||
|
|
||||||
// Get only direct routes (1 step)
|
|
||||||
const directRoutes = await Bridge.routes({
|
|
||||||
originChainId: 1,
|
|
||||||
originTokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",
|
|
||||||
maxSteps: 1,
|
|
||||||
client,
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Going further
|
|
||||||
|
|
||||||
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
|
||||||
|
|
||||||
- [Send a Payment](/payments/send)
|
|
||||||
- [Get Token Prices](/payments/prices)
|
|
||||||
|
|
||||||
## Explore Full API References
|
|
||||||
|
|
||||||
- [Bridge.routes](/references/typescript/v5/routes)
|
|
||||||
@@ -60,7 +60,6 @@ You can execute this quote exactly like a buy. See the [Send a Payment](/payment
|
|||||||
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
||||||
|
|
||||||
- [Send a Payment](/payments/send)
|
- [Send a Payment](/payments/send)
|
||||||
- [Get Routes](/payments/routes)
|
|
||||||
|
|
||||||
## Explore Full API References
|
## Explore Full API References
|
||||||
|
|
||||||
|
|||||||
@@ -28,10 +28,6 @@ export const sidebar: SideBar = {
|
|||||||
href: `${bridgeSlug}/tokens`,
|
href: `${bridgeSlug}/tokens`,
|
||||||
name: "Get Token Prices",
|
name: "Get Token Prices",
|
||||||
},
|
},
|
||||||
{
|
|
||||||
href: `${bridgeSlug}/routes`,
|
|
||||||
name: "Get Routes",
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
href: `${bridgeSlug}/bridge-widget-script`,
|
href: `${bridgeSlug}/bridge-widget-script`,
|
||||||
name: "BridgeWidget Script",
|
name: "BridgeWidget Script",
|
||||||
|
|||||||
@@ -255,23 +255,6 @@ export class SwapManager {
|
|||||||
|
|
||||||
throw new Error("Transaction timeout - please check status manually");
|
throw new Error("Transaction timeout - please check status manually");
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAvailableRoutes(params: {
|
|
||||||
originChainId?: number;
|
|
||||||
originTokenAddress?: string;
|
|
||||||
destinationChainId?: number;
|
|
||||||
destinationTokenAddress?: string;
|
|
||||||
limit?: number;
|
|
||||||
}) {
|
|
||||||
try {
|
|
||||||
return await Bridge.routes({
|
|
||||||
...params,
|
|
||||||
client: this.client,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
throw new Error(`Failed to get routes: ${error.message}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -319,92 +302,6 @@ async function swapEthToMatic(amount: string, userAccount: Account) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced Price Comparison
|
|
||||||
|
|
||||||
Compare prices across multiple routes to find the best deal:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
interface RouteComparison {
|
|
||||||
route: any;
|
|
||||||
quote: SwapQuote;
|
|
||||||
priceImpact: number;
|
|
||||||
gasEstimate: bigint;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class PriceComparator {
|
|
||||||
private swapManager: SwapManager;
|
|
||||||
|
|
||||||
constructor(swapManager: SwapManager) {
|
|
||||||
this.swapManager = swapManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
async compareRoutes(
|
|
||||||
fromToken: { chainId: number; address: string },
|
|
||||||
amount: bigint,
|
|
||||||
userAddress: string
|
|
||||||
): Promise<RouteComparison[]> {
|
|
||||||
// Get available routes
|
|
||||||
const routes = await this.swapManager.getAvailableRoutes({
|
|
||||||
originChainId: fromToken.chainId,
|
|
||||||
originTokenAddress: fromToken.address,
|
|
||||||
limit: 10,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Get quotes for each route
|
|
||||||
const comparisons: RouteComparison[] = [];
|
|
||||||
|
|
||||||
for (const route of routes) {
|
|
||||||
try {
|
|
||||||
const quote = await this.swapManager.getQuote({
|
|
||||||
fromChainId: route.originToken.chainId,
|
|
||||||
fromTokenAddress: route.originToken.address,
|
|
||||||
toChainId: route.destinationToken.chainId,
|
|
||||||
toTokenAddress: route.destinationToken.address,
|
|
||||||
amount,
|
|
||||||
userAddress,
|
|
||||||
client: this.swapManager.client,
|
|
||||||
});
|
|
||||||
|
|
||||||
const priceImpact = this.calculatePriceImpact(quote, amount);
|
|
||||||
const gasEstimate = this.estimateGasCosts(quote);
|
|
||||||
|
|
||||||
comparisons.push({
|
|
||||||
route,
|
|
||||||
quote,
|
|
||||||
priceImpact,
|
|
||||||
gasEstimate,
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to get quote for route ${route.originToken.symbol} -> ${route.destinationToken.symbol}:`, error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by best output amount
|
|
||||||
return comparisons.sort((a, b) =>
|
|
||||||
Number(b.quote.destinationAmount) - Number(a.quote.destinationAmount)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private calculatePriceImpact(quote: SwapQuote, inputAmount: bigint): number {
|
|
||||||
// Simplified price impact calculation
|
|
||||||
const ratio = Number(quote.destinationAmount) / Number(quote.originAmount);
|
|
||||||
return Math.abs(1 - ratio) * 100; // Percentage
|
|
||||||
}
|
|
||||||
|
|
||||||
private estimateGasCosts(quote: SwapQuote): bigint {
|
|
||||||
// Sum up gas estimates from all transactions
|
|
||||||
return quote.steps.reduce((total, step) => {
|
|
||||||
return total + step.transactions.reduce((stepTotal: bigint, tx: any) => {
|
|
||||||
return stepTotal + (tx.gasLimit || 200000n); // Default estimate
|
|
||||||
}, 0n);
|
|
||||||
}, 0n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
<Callout variant="info">
|
|
||||||
**Gas Optimization Tip:** For frequently traded pairs, consider caching route data to reduce API calls and improve UI responsiveness.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
@@ -415,20 +312,16 @@ export class PriceComparator {
|
|||||||
- **Cross-chain swaps** - Exchange tokens across 50+ supported chains
|
- **Cross-chain swaps** - Exchange tokens across 50+ supported chains
|
||||||
- **Real-time quotes** - Get up-to-date pricing and execution estimates
|
- **Real-time quotes** - Get up-to-date pricing and execution estimates
|
||||||
- **Route optimization** - Find the best path for any token pair
|
- **Route optimization** - Find the best path for any token pair
|
||||||
- **Price comparison** - Compare multiple routes to maximize output
|
|
||||||
- **Status tracking** - Monitor cross-chain transaction progress
|
- **Status tracking** - Monitor cross-chain transaction progress
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Going Further
|
## Going Further
|
||||||
|
|
||||||
- [Send a Payment](/payments/send) - Learn about peer-to-peer transfers
|
- [Send a Payment](/payments/send) - Learn about peer-to-peer transfers
|
||||||
- [Get Routes](/payments/routes) - Explore route discovery APIs
|
- [Token Prices](/bridge/tokens) - Access real-time token pricing
|
||||||
- [Token Prices](/payments/tokens) - Access real-time token pricing
|
|
||||||
- [Webhooks](/payments/webhooks) - Get notified when swaps complete
|
- [Webhooks](/payments/webhooks) - Get notified when swaps complete
|
||||||
|
|
||||||
## API Reference
|
## API Reference
|
||||||
|
|
||||||
- [Bridge.Buy.prepare](/references/typescript/v5/buy/prepare)
|
- [Bridge.Buy.prepare](/references/typescript/v5/buy/prepare)
|
||||||
- [Bridge.routes](/references/typescript/v5/routes)
|
|
||||||
- [Bridge.status](/references/typescript/v5/status)
|
- [Bridge.status](/references/typescript/v5/status)
|
||||||
@@ -119,7 +119,6 @@ const nextTokens = await Bridge.tokens({
|
|||||||
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
||||||
|
|
||||||
- [Send a Payment](/payments/send)
|
- [Send a Payment](/payments/send)
|
||||||
- [Get Routes](/payments/routes)
|
|
||||||
|
|
||||||
## Explore Full API References
|
## Explore Full API References
|
||||||
|
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ function Hero() {
|
|||||||
<h1 className="mb-3 font-bold text-4xl tracking-tighter lg:text-6xl">
|
<h1 className="mb-3 font-bold text-4xl tracking-tighter lg:text-6xl">
|
||||||
thirdweb Documentation
|
thirdweb Documentation
|
||||||
</h1>
|
</h1>
|
||||||
<p className="mb-8 max-w-md text-lg text-muted-foreground leading-normal">
|
<p className="mb-8 max-w-lg text-lg text-muted-foreground leading-normal text-pretty">
|
||||||
Development framework for building onchain apps, games, and agents.
|
Platform for building the next generation of internet products
|
||||||
</p>
|
</p>
|
||||||
<div className="flex gap-3">
|
<div className="flex gap-3">
|
||||||
<ChatButton />
|
<ChatButton />
|
||||||
|
|||||||
@@ -264,7 +264,6 @@ Once this code completes, your payment has been fully executed. Payments normall
|
|||||||
|
|
||||||
- [Sell a Product](/payments/products)
|
- [Sell a Product](/payments/products)
|
||||||
- [Token Prices](/payments/tokens)
|
- [Token Prices](/payments/tokens)
|
||||||
- [Routes](/payments/routes)
|
|
||||||
|
|
||||||
## Explore API References
|
## Explore API References
|
||||||
|
|
||||||
|
|||||||
@@ -49,10 +49,6 @@ export const sidebar: SideBar = {
|
|||||||
href: `/bridge/tokens`,
|
href: `/bridge/tokens`,
|
||||||
name: "Get Token Prices",
|
name: "Get Token Prices",
|
||||||
},
|
},
|
||||||
{
|
|
||||||
href: `/bridge/routes`,
|
|
||||||
name: "Get Routes",
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
href: `${paymentsSlug}/webhooks`,
|
href: `${paymentsSlug}/webhooks`,
|
||||||
name: "Webhooks",
|
name: "Webhooks",
|
||||||
|
|||||||
@@ -222,7 +222,6 @@ async function verifyWebhook(
|
|||||||
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
To connect with other auth strategies, use external wallets, or sponsor gas for users, check out the following guides:
|
||||||
|
|
||||||
- [Send a Payment](/payments/send)
|
- [Send a Payment](/payments/send)
|
||||||
- [Find Routes](/payments/routes)
|
|
||||||
- [Get Token Prices](/payments/tokens)
|
- [Get Token Prices](/payments/tokens)
|
||||||
|
|
||||||
## Explore Full API References
|
## Explore Full API References
|
||||||
|
|||||||
@@ -63,10 +63,48 @@ export const config = createConfig({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
Then in your application, you can use the connector to trigger the in-app wallet connection.
|
### Using the ConnectButton or ConnectEmbed with a wagmi application
|
||||||
|
|
||||||
|
You can use the thirdweb react connection components and hooks like ConnectButton, ConnectEmbed, useConnectModal, etc, but still keep using wagmi for the rest of the application.
|
||||||
|
|
||||||
|
To do so, you will need to connect the `inAppWalletConnector` connector from the `@thirdweb-dev/wagmi-adapter` package with the connected thirdweb wallet.
|
||||||
|
|
||||||
|
You can do this at any time after connecting the thirdweb wallet, a convenient place to do this is in the `onConnect` callback of the ConnectButton or ConnectEmbed.
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const { connectors, connect } = useConnect(); // from wagmi
|
||||||
|
|
||||||
|
<ConnectButton
|
||||||
|
client={client}
|
||||||
|
onConnect={(wallet) => {
|
||||||
|
// connect the wagmi connector with the connected thirdweb wallet
|
||||||
|
const twConnector = connectors.find(
|
||||||
|
(c) => c.id === "in-app-wallet",
|
||||||
|
);
|
||||||
|
if (twConnector) {
|
||||||
|
const options = {
|
||||||
|
wallet, // pass the connected wallet
|
||||||
|
} satisfies ConnectionOptions; // for type safety
|
||||||
|
connect({
|
||||||
|
connector: twConnector,
|
||||||
|
chainId: chain.id,
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
Make sure your app is wrapped in a `<ThirdwebProvider>` as well as a `<WagmiProvider>` since both contexts will be used here. From there, the wallet state will be in sync between the 2 libraries.
|
||||||
|
|
||||||
|
**Note:** the ConnectButton and ConnectEmbed handle reconnecting automatically on page reload. If not using those components (ie. useConnectModal or useConnect hooks directly), you will need to handle reconnecting by explicitely calling `useAutoConnect()`, and doing the same wagmi connection from the `onConnect` callback.
|
||||||
|
|
||||||
|
### Using the connector directly (headless mode)
|
||||||
|
|
||||||
|
You can also use the `inAppWalletConnector` connector directly in your application to connect to the thirdweb wallet without needing a `<ThirdwebProvider>` at all.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const { connect, connectors } = useConnect();
|
const { connect, connectors } = useConnect(); // from wagmi
|
||||||
|
|
||||||
const onClick = () => {
|
const onClick = () => {
|
||||||
// grab the connector
|
// grab the connector
|
||||||
@@ -79,9 +117,10 @@ const onClick = () => {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Converting a wagmi wallet client to a thirdweb wallet
|
### Converting a wagmi wallet client to a thirdweb wallet
|
||||||
|
|
||||||
You can use the thirdweb SDK within a wagmi application by setting the wagmi connected account as the thirdweb 'active wallet'. After that, you can use all of the react components and hooks normally, including `BuyWidget`, `TransactionButton`, etc.
|
You can also use the thirdweb SDK within a wagmi application by setting the wagmi connected account as the thirdweb 'active wallet'. After that, you can use all of the react components and hooks normally, including `BuyWidget`, `TransactionButton`, etc.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
// Assumes you've wrapped your application in a `<ThirdwebProvider>`
|
// Assumes you've wrapped your application in a `<ThirdwebProvider>`
|
||||||
|
|||||||
@@ -1,5 +1,77 @@
|
|||||||
# wagmi-inapp
|
# wagmi-inapp
|
||||||
|
|
||||||
|
## 0.0.22
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`1d54cff`](https://github.com/thirdweb-dev/js/commit/1d54cff7b442b8667ddd54bd783502c367ffc83e), [`fd04eef`](https://github.com/thirdweb-dev/js/commit/fd04eefea9a2a99eee3740d6746040c9f81cd43f)]:
|
||||||
|
- thirdweb@5.111.2
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.177
|
||||||
|
|
||||||
|
## 0.0.21
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`ccdce49`](https://github.com/thirdweb-dev/js/commit/ccdce496e09bc9420b0e15854328651c01f36279)]:
|
||||||
|
- thirdweb@5.111.1
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.176
|
||||||
|
|
||||||
|
## 0.0.20
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`c83f1c6`](https://github.com/thirdweb-dev/js/commit/c83f1c6f7a38c8a9f424798e6e726e1d037ed042), [`219fc69`](https://github.com/thirdweb-dev/js/commit/219fc69d72b1ca861bf0228589039788008ea0c0)]:
|
||||||
|
- thirdweb@5.111.0
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.175
|
||||||
|
|
||||||
|
## 0.0.19
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`6c318f8`](https://github.com/thirdweb-dev/js/commit/6c318f83d63aa8acce46da666e43638e410f799c), [`759b93b`](https://github.com/thirdweb-dev/js/commit/759b93beff7ab10a3a2fa3b9dd25ca628efb9267), [`8e357b3`](https://github.com/thirdweb-dev/js/commit/8e357b3cb39dcc7a8595a83224098a9c44585389)]:
|
||||||
|
- thirdweb@5.110.6
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.174
|
||||||
|
|
||||||
|
## 0.0.18
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`c08fb13`](https://github.com/thirdweb-dev/js/commit/c08fb1356e77be9eeb0569905fcb2ab76a516dc3), [`bcbb3f5`](https://github.com/thirdweb-dev/js/commit/bcbb3f540a8eab2b02f9261b779bd2aad3464598), [`e0c8312`](https://github.com/thirdweb-dev/js/commit/e0c83121c201eb2dbdfa6a6b1bbb637f5ad2a21d)]:
|
||||||
|
- thirdweb@5.110.5
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.173
|
||||||
|
|
||||||
|
## 0.0.17
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`23cb3bd`](https://github.com/thirdweb-dev/js/commit/23cb3bd98c5390e64f45da5a222042cdc76bd7f4), [`abf0bba`](https://github.com/thirdweb-dev/js/commit/abf0bbaf359c8de5b0ed0d481e3791c4b7cbf92b), [`e0abf2b`](https://github.com/thirdweb-dev/js/commit/e0abf2b2738661fda3c69551d78231cfac4b0767)]:
|
||||||
|
- thirdweb@5.110.4
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.172
|
||||||
|
|
||||||
|
## 0.0.16
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`bf46520`](https://github.com/thirdweb-dev/js/commit/bf46520a6b183c4beb873de5e63853cd3a23e685)]:
|
||||||
|
- thirdweb@5.110.3
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.171
|
||||||
|
|
||||||
|
## 0.0.15
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`3e9eb49`](https://github.com/thirdweb-dev/js/commit/3e9eb49787e00c09c3286aeb4ad73826a2856e65), [`bfd3be7`](https://github.com/thirdweb-dev/js/commit/bfd3be764c461c420f1f8520fe4d5d2cc83e42f7), [`ae3a122`](https://github.com/thirdweb-dev/js/commit/ae3a122cf1628f0fc997dd240d4b23842ac30f66), [`d5d5939`](https://github.com/thirdweb-dev/js/commit/d5d593956e12b2a15393ed32d1d742bc43575bdd), [`f757e60`](https://github.com/thirdweb-dev/js/commit/f757e6084648b6b6e5879abeab30954753a1020d)]:
|
||||||
|
- thirdweb@5.110.2
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.170
|
||||||
|
|
||||||
|
## 0.0.14
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`85fe949`](https://github.com/thirdweb-dev/js/commit/85fe9491cd6d2270847e9941ddb7df76aefd8b31), [`e978809`](https://github.com/thirdweb-dev/js/commit/e9788096d665afef7c2a933cea5d6f522fc67273), [`899051f`](https://github.com/thirdweb-dev/js/commit/899051f788b0c2521a022846782892a8c1405a66)]:
|
||||||
|
- thirdweb@5.110.1
|
||||||
|
- @thirdweb-dev/wagmi-adapter@0.2.169
|
||||||
|
|
||||||
## 0.0.13
|
## 0.0.13
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "wagmi-inapp",
|
"name": "wagmi-inapp",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.13",
|
"version": "0.0.22",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ import type { ConnectionOptions } from "@thirdweb-dev/wagmi-adapter";
|
|||||||
import { ConnectButton } from "thirdweb/react";
|
import { ConnectButton } from "thirdweb/react";
|
||||||
import {
|
import {
|
||||||
useAccount,
|
useAccount,
|
||||||
|
useCallsStatus,
|
||||||
useConnect,
|
useConnect,
|
||||||
useDisconnect,
|
useDisconnect,
|
||||||
|
useSendCalls,
|
||||||
useSendTransaction,
|
useSendTransaction,
|
||||||
} from "wagmi";
|
} from "wagmi";
|
||||||
import { chain, client } from "./wagmi.js";
|
import { chain, client, thirdwebChainForWallet, wallet } from "./wagmi.js";
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const account = useAccount();
|
const account = useAccount();
|
||||||
@@ -20,6 +22,17 @@ function App() {
|
|||||||
error: sendTxError,
|
error: sendTxError,
|
||||||
data: sendTxData,
|
data: sendTxData,
|
||||||
} = useSendTransaction();
|
} = useSendTransaction();
|
||||||
|
const { sendCalls, data, isPending: isPendingSendCalls } = useSendCalls();
|
||||||
|
const {
|
||||||
|
data: callStatus,
|
||||||
|
isLoading: isLoadingCallStatus,
|
||||||
|
error: callStatusError,
|
||||||
|
} = useCallsStatus({
|
||||||
|
id: data?.id || "",
|
||||||
|
query: {
|
||||||
|
enabled: !!data?.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div>
|
<div>
|
||||||
@@ -44,6 +57,8 @@ function App() {
|
|||||||
<h2>Connect</h2>
|
<h2>Connect</h2>
|
||||||
<ConnectButton
|
<ConnectButton
|
||||||
client={client}
|
client={client}
|
||||||
|
chain={thirdwebChainForWallet}
|
||||||
|
wallets={[wallet]}
|
||||||
onConnect={(wallet) => {
|
onConnect={(wallet) => {
|
||||||
// auto connect to wagmi on tw connect
|
// auto connect to wagmi on tw connect
|
||||||
const twConnector = connectors.find(
|
const twConnector = connectors.find(
|
||||||
@@ -95,7 +110,26 @@ function App() {
|
|||||||
>
|
>
|
||||||
Send Tx
|
Send Tx
|
||||||
</button>
|
</button>
|
||||||
<div>{isPending ? "Sending..." : ""}</div>
|
<button
|
||||||
|
onClick={() =>
|
||||||
|
sendCalls({
|
||||||
|
calls: [
|
||||||
|
{
|
||||||
|
to: "0x70997970c51812dc3a010c7d01b50e0d17dc79c8",
|
||||||
|
value: 0n,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
Send Calls
|
||||||
|
</button>
|
||||||
|
<div>
|
||||||
|
{isPending || isPendingSendCalls || isLoadingCallStatus
|
||||||
|
? "Sending..."
|
||||||
|
: ""}
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
{isSuccess
|
{isSuccess
|
||||||
? `Success: ${sendTxData}`
|
? `Success: ${sendTxData}`
|
||||||
@@ -103,6 +137,13 @@ function App() {
|
|||||||
? sendTxError?.message
|
? sendTxError?.message
|
||||||
: ""}
|
: ""}
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
{callStatus
|
||||||
|
? `Success: ${JSON.stringify(callStatus, null, 2)}`
|
||||||
|
: callStatusError
|
||||||
|
? callStatusError?.message
|
||||||
|
: ""}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { inAppWalletConnector } from "@thirdweb-dev/wagmi-adapter";
|
import { inAppWalletConnector } from "@thirdweb-dev/wagmi-adapter";
|
||||||
import { createThirdwebClient, defineChain as thirdwebChain } from "thirdweb";
|
import { createThirdwebClient, defineChain as thirdwebChain } from "thirdweb";
|
||||||
|
import { inAppWallet } from "thirdweb/wallets/in-app";
|
||||||
import { createConfig, http } from "wagmi";
|
import { createConfig, http } from "wagmi";
|
||||||
import { baseSepolia } from "wagmi/chains";
|
import { baseSepolia } from "wagmi/chains";
|
||||||
|
|
||||||
@@ -15,6 +16,13 @@ export const client = createThirdwebClient({
|
|||||||
clientId,
|
clientId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const wallet = inAppWallet({
|
||||||
|
executionMode: {
|
||||||
|
mode: "EIP7702",
|
||||||
|
sponsorGas: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
export const chain = baseSepolia;
|
export const chain = baseSepolia;
|
||||||
export const thirdwebChainForWallet = thirdwebChain(baseSepolia.id);
|
export const thirdwebChainForWallet = thirdwebChain(baseSepolia.id);
|
||||||
|
|
||||||
@@ -23,8 +31,8 @@ export const config = createConfig({
|
|||||||
connectors: [
|
connectors: [
|
||||||
inAppWalletConnector({
|
inAppWalletConnector({
|
||||||
client,
|
client,
|
||||||
smartAccount: {
|
executionMode: {
|
||||||
chain: thirdwebChain(chain.id),
|
mode: "EIP7702",
|
||||||
sponsorGas: true,
|
sponsorGas: true,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
# @thirdweb-dev/api
|
# @thirdweb-dev/api
|
||||||
|
|
||||||
|
## 0.1.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8338](https://github.com/thirdweb-dev/js/pull/8338) [`90b7791`](https://github.com/thirdweb-dev/js/commit/90b779107d3cb726adeca6a3f885129c12599c6a) Thanks [@0xFirekeeper](https://github.com/0xFirekeeper)! - added solana token balances endpoint
|
||||||
|
|
||||||
## 0.1.1
|
## 0.1.1
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@thirdweb-dev/api",
|
"name": "@thirdweb-dev/api",
|
||||||
"version": "0.1.1",
|
"version": "0.1.2",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git+https://github.com/thirdweb-dev/js.git#main"
|
"url": "git+https://github.com/thirdweb-dev/js.git#main"
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ import type {
|
|||||||
GetSolanaTransactionData,
|
GetSolanaTransactionData,
|
||||||
GetSolanaTransactionErrors,
|
GetSolanaTransactionErrors,
|
||||||
GetSolanaTransactionResponses,
|
GetSolanaTransactionResponses,
|
||||||
|
GetSolanaWalletBalanceData,
|
||||||
|
GetSolanaWalletBalanceErrors,
|
||||||
|
GetSolanaWalletBalanceResponses,
|
||||||
GetTokenOwnersData,
|
GetTokenOwnersData,
|
||||||
GetTokenOwnersErrors,
|
GetTokenOwnersErrors,
|
||||||
GetTokenOwnersResponses,
|
GetTokenOwnersResponses,
|
||||||
@@ -1590,6 +1593,31 @@ export const createSolanaWallet = <ThrowOnError extends boolean = false>(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get Solana Wallet Balance
|
||||||
|
* Get the SOL or SPL token balance for a Solana wallet on a specific Solana network.
|
||||||
|
*
|
||||||
|
* **Authentication**: Pass `x-client-id` for frontend usage from allowlisted origins or `x-secret-key` for backend usage.
|
||||||
|
*/
|
||||||
|
export const getSolanaWalletBalance = <ThrowOnError extends boolean = false>(
|
||||||
|
options: Options<GetSolanaWalletBalanceData, ThrowOnError>,
|
||||||
|
) => {
|
||||||
|
return (options.client ?? _heyApiClient).get<
|
||||||
|
GetSolanaWalletBalanceResponses,
|
||||||
|
GetSolanaWalletBalanceErrors,
|
||||||
|
ThrowOnError
|
||||||
|
>({
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
name: "x-client-id",
|
||||||
|
type: "apiKey",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
url: "/v1/solana/wallets/{address}/balance",
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sign Solana Message
|
* Sign Solana Message
|
||||||
* Sign an arbitrary message with a Solana wallet. Supports both text and hexadecimal message formats with automatic format detection.
|
* Sign an arbitrary message with a Solana wallet. Supports both text and hexadecimal message formats with automatic format detection.
|
||||||
|
|||||||
@@ -2135,6 +2135,10 @@ export type GetWalletTransactionsData = {
|
|||||||
address: string;
|
address: string;
|
||||||
};
|
};
|
||||||
query: {
|
query: {
|
||||||
|
/**
|
||||||
|
* Chain ID(s) to request transaction data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137
|
||||||
|
*/
|
||||||
|
chainId: Array<number>;
|
||||||
/**
|
/**
|
||||||
* Filter by block timestamp (Unix timestamp) greater than or equal to this value
|
* Filter by block timestamp (Unix timestamp) greater than or equal to this value
|
||||||
*/
|
*/
|
||||||
@@ -2171,10 +2175,6 @@ export type GetWalletTransactionsData = {
|
|||||||
* Sort order: 'asc' for ascending, 'desc' for descending
|
* Sort order: 'asc' for ascending, 'desc' for descending
|
||||||
*/
|
*/
|
||||||
sortOrder?: "asc" | "desc";
|
sortOrder?: "asc" | "desc";
|
||||||
/**
|
|
||||||
* Chain ID(s) to request transaction data for. You can specify multiple chain IDs by repeating the parameter, up to a maximum of 50. Example: ?chainId=1&chainId=137
|
|
||||||
*/
|
|
||||||
chainId: Array<number>;
|
|
||||||
};
|
};
|
||||||
url: "/v1/wallets/{address}/transactions";
|
url: "/v1/wallets/{address}/transactions";
|
||||||
};
|
};
|
||||||
@@ -3234,11 +3234,11 @@ export type WriteContractErrors = {
|
|||||||
/**
|
/**
|
||||||
* Payment ID
|
* Payment ID
|
||||||
*/
|
*/
|
||||||
id: string;
|
id?: string;
|
||||||
/**
|
/**
|
||||||
* Bridge quote for completing the payment
|
* Bridge quote for completing the payment
|
||||||
*/
|
*/
|
||||||
quote: {
|
quote?: {
|
||||||
/**
|
/**
|
||||||
* Block number when quote was generated
|
* Block number when quote was generated
|
||||||
*/
|
*/
|
||||||
@@ -4314,11 +4314,11 @@ export type SendTransactionsErrors = {
|
|||||||
/**
|
/**
|
||||||
* Payment ID
|
* Payment ID
|
||||||
*/
|
*/
|
||||||
id: string;
|
id?: string;
|
||||||
/**
|
/**
|
||||||
* Bridge quote for completing the payment
|
* Bridge quote for completing the payment
|
||||||
*/
|
*/
|
||||||
quote: {
|
quote?: {
|
||||||
/**
|
/**
|
||||||
* Block number when quote was generated
|
* Block number when quote was generated
|
||||||
*/
|
*/
|
||||||
@@ -4725,11 +4725,11 @@ export type PaymentsPurchaseErrors = {
|
|||||||
/**
|
/**
|
||||||
* Payment ID
|
* Payment ID
|
||||||
*/
|
*/
|
||||||
id: string;
|
id?: string;
|
||||||
/**
|
/**
|
||||||
* Bridge quote for completing the payment
|
* Bridge quote for completing the payment
|
||||||
*/
|
*/
|
||||||
quote: {
|
quote?: {
|
||||||
/**
|
/**
|
||||||
* Block number when quote was generated
|
* Block number when quote was generated
|
||||||
*/
|
*/
|
||||||
@@ -4914,17 +4914,7 @@ export type VerifyX402PaymentData = {
|
|||||||
paymentPayload: {
|
paymentPayload: {
|
||||||
x402Version: number;
|
x402Version: number;
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
payload:
|
payload:
|
||||||
| {
|
| {
|
||||||
signature: string;
|
signature: string;
|
||||||
@@ -4943,17 +4933,7 @@ export type VerifyX402PaymentData = {
|
|||||||
};
|
};
|
||||||
paymentRequirements: {
|
paymentRequirements: {
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
maxAmountRequired: string;
|
maxAmountRequired: string;
|
||||||
resource: string;
|
resource: string;
|
||||||
description: string;
|
description: string;
|
||||||
@@ -5015,7 +4995,6 @@ export type VerifyX402PaymentResponses = {
|
|||||||
| "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked"
|
| "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked"
|
||||||
| "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked"
|
| "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked"
|
||||||
| "invalid_exact_svm_payload_transaction_not_a_transfer_instruction"
|
| "invalid_exact_svm_payload_transaction_not_a_transfer_instruction"
|
||||||
| "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata"
|
|
||||||
| "invalid_exact_svm_payload_transaction_receiver_ata_not_found"
|
| "invalid_exact_svm_payload_transaction_receiver_ata_not_found"
|
||||||
| "invalid_exact_svm_payload_transaction_sender_ata_not_found"
|
| "invalid_exact_svm_payload_transaction_sender_ata_not_found"
|
||||||
| "invalid_exact_svm_payload_transaction_simulation_failed"
|
| "invalid_exact_svm_payload_transaction_simulation_failed"
|
||||||
@@ -5049,17 +5028,7 @@ export type SettleX402PaymentData = {
|
|||||||
paymentPayload: {
|
paymentPayload: {
|
||||||
x402Version: number;
|
x402Version: number;
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
payload:
|
payload:
|
||||||
| {
|
| {
|
||||||
signature: string;
|
signature: string;
|
||||||
@@ -5078,17 +5047,7 @@ export type SettleX402PaymentData = {
|
|||||||
};
|
};
|
||||||
paymentRequirements: {
|
paymentRequirements: {
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
maxAmountRequired: string;
|
maxAmountRequired: string;
|
||||||
resource: string;
|
resource: string;
|
||||||
description: string;
|
description: string;
|
||||||
@@ -5154,7 +5113,6 @@ export type SettleX402PaymentResponses = {
|
|||||||
| "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked"
|
| "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked"
|
||||||
| "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked"
|
| "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked"
|
||||||
| "invalid_exact_svm_payload_transaction_not_a_transfer_instruction"
|
| "invalid_exact_svm_payload_transaction_not_a_transfer_instruction"
|
||||||
| "invalid_exact_svm_payload_transaction_cannot_derive_receiver_ata"
|
|
||||||
| "invalid_exact_svm_payload_transaction_receiver_ata_not_found"
|
| "invalid_exact_svm_payload_transaction_receiver_ata_not_found"
|
||||||
| "invalid_exact_svm_payload_transaction_sender_ata_not_found"
|
| "invalid_exact_svm_payload_transaction_sender_ata_not_found"
|
||||||
| "invalid_exact_svm_payload_transaction_simulation_failed"
|
| "invalid_exact_svm_payload_transaction_simulation_failed"
|
||||||
@@ -5183,7 +5141,10 @@ export type SettleX402PaymentResponses = {
|
|||||||
| "solana-devnet"
|
| "solana-devnet"
|
||||||
| "solana"
|
| "solana"
|
||||||
| "sei"
|
| "sei"
|
||||||
| "sei-testnet";
|
| "sei-testnet"
|
||||||
|
| "polygon"
|
||||||
|
| "polygon-amoy"
|
||||||
|
| "peaq";
|
||||||
errorMessage?: string;
|
errorMessage?: string;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -5226,17 +5187,7 @@ export type SupportedX402PaymentsResponses = {
|
|||||||
kinds: Array<{
|
kinds: Array<{
|
||||||
x402Version: 1;
|
x402Version: 1;
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
extra?: {
|
extra?: {
|
||||||
defaultAsset?: {
|
defaultAsset?: {
|
||||||
/**
|
/**
|
||||||
@@ -5340,11 +5291,11 @@ export type FetchWithPaymentErrors = {
|
|||||||
/**
|
/**
|
||||||
* Payment ID
|
* Payment ID
|
||||||
*/
|
*/
|
||||||
id: string;
|
id?: string;
|
||||||
/**
|
/**
|
||||||
* Bridge quote for completing the payment
|
* Bridge quote for completing the payment
|
||||||
*/
|
*/
|
||||||
quote: {
|
quote?: {
|
||||||
/**
|
/**
|
||||||
* Block number when quote was generated
|
* Block number when quote was generated
|
||||||
*/
|
*/
|
||||||
@@ -5552,17 +5503,7 @@ export type ListPayableServicesResponses = {
|
|||||||
x402Version: number;
|
x402Version: number;
|
||||||
accepts: Array<{
|
accepts: Array<{
|
||||||
scheme: "exact";
|
scheme: "exact";
|
||||||
network:
|
network: string;
|
||||||
| "base-sepolia"
|
|
||||||
| "base"
|
|
||||||
| "avalanche-fuji"
|
|
||||||
| "avalanche"
|
|
||||||
| "iotex"
|
|
||||||
| "solana-devnet"
|
|
||||||
| "solana"
|
|
||||||
| "sei"
|
|
||||||
| "sei-testnet"
|
|
||||||
| string;
|
|
||||||
maxAmountRequired: string;
|
maxAmountRequired: string;
|
||||||
resource: string;
|
resource: string;
|
||||||
description: string;
|
description: string;
|
||||||
@@ -6298,11 +6239,11 @@ export type BridgeSwapErrors = {
|
|||||||
/**
|
/**
|
||||||
* Payment ID
|
* Payment ID
|
||||||
*/
|
*/
|
||||||
id: string;
|
id?: string;
|
||||||
/**
|
/**
|
||||||
* Bridge quote for completing the payment
|
* Bridge quote for completing the payment
|
||||||
*/
|
*/
|
||||||
quote: {
|
quote?: {
|
||||||
/**
|
/**
|
||||||
* Block number when quote was generated
|
* Block number when quote was generated
|
||||||
*/
|
*/
|
||||||
@@ -6640,6 +6581,74 @@ export type CreateSolanaWalletResponses = {
|
|||||||
export type CreateSolanaWalletResponse =
|
export type CreateSolanaWalletResponse =
|
||||||
CreateSolanaWalletResponses[keyof CreateSolanaWalletResponses];
|
CreateSolanaWalletResponses[keyof CreateSolanaWalletResponses];
|
||||||
|
|
||||||
|
export type GetSolanaWalletBalanceData = {
|
||||||
|
body?: never;
|
||||||
|
path: {
|
||||||
|
/**
|
||||||
|
* Public key of the Solana wallet.
|
||||||
|
*/
|
||||||
|
address: string;
|
||||||
|
};
|
||||||
|
query: {
|
||||||
|
/**
|
||||||
|
* Solana network to query. Choose either solana:mainnet or solana:devnet.
|
||||||
|
*/
|
||||||
|
chainId: "solana:mainnet" | "solana:devnet";
|
||||||
|
/**
|
||||||
|
* SPL token mint address. Omit to retrieve native SOL balance.
|
||||||
|
*/
|
||||||
|
tokenAddress?: string;
|
||||||
|
};
|
||||||
|
url: "/v1/solana/wallets/{address}/balance";
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GetSolanaWalletBalanceErrors = {
|
||||||
|
/**
|
||||||
|
* Invalid request parameters. This occurs when the wallet address or token mint is invalid, or the request mixes a token mint with multiple networks.
|
||||||
|
*/
|
||||||
|
400: unknown;
|
||||||
|
/**
|
||||||
|
* Authentication required. Include `x-client-id` or `x-secret-key` headers.
|
||||||
|
*/
|
||||||
|
401: unknown;
|
||||||
|
/**
|
||||||
|
* Internal server error. This may occur due to RPC connectivity issues or unexpected failures.
|
||||||
|
*/
|
||||||
|
500: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GetSolanaWalletBalanceResponses = {
|
||||||
|
/**
|
||||||
|
* Wallet balance retrieved successfully for the requested Solana network.
|
||||||
|
*/
|
||||||
|
200: {
|
||||||
|
/**
|
||||||
|
* Balance data for the requested Solana network.
|
||||||
|
*/
|
||||||
|
result: {
|
||||||
|
/**
|
||||||
|
* Requested Solana network.
|
||||||
|
*/
|
||||||
|
chainId: "solana:mainnet" | "solana:devnet";
|
||||||
|
/**
|
||||||
|
* Number of decimals used by the token.
|
||||||
|
*/
|
||||||
|
decimals: number;
|
||||||
|
/**
|
||||||
|
* Human-readable balance formatted using token decimals.
|
||||||
|
*/
|
||||||
|
displayValue: string;
|
||||||
|
/**
|
||||||
|
* Raw balance value expressed in base units (lamports).
|
||||||
|
*/
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type GetSolanaWalletBalanceResponse =
|
||||||
|
GetSolanaWalletBalanceResponses[keyof GetSolanaWalletBalanceResponses];
|
||||||
|
|
||||||
export type SignSolanaMessageData = {
|
export type SignSolanaMessageData = {
|
||||||
/**
|
/**
|
||||||
* Request payload for signing an arbitrary Solana message.
|
* Request payload for signing an arbitrary Solana message.
|
||||||
|
|||||||
@@ -1,5 +1,68 @@
|
|||||||
# @thirdweb-dev/nebula
|
# @thirdweb-dev/nebula
|
||||||
|
|
||||||
|
## 0.2.80
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`1d54cff`](https://github.com/thirdweb-dev/js/commit/1d54cff7b442b8667ddd54bd783502c367ffc83e), [`fd04eef`](https://github.com/thirdweb-dev/js/commit/fd04eefea9a2a99eee3740d6746040c9f81cd43f)]:
|
||||||
|
- thirdweb@5.111.2
|
||||||
|
|
||||||
|
## 0.2.79
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`ccdce49`](https://github.com/thirdweb-dev/js/commit/ccdce496e09bc9420b0e15854328651c01f36279)]:
|
||||||
|
- thirdweb@5.111.1
|
||||||
|
|
||||||
|
## 0.2.78
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`c83f1c6`](https://github.com/thirdweb-dev/js/commit/c83f1c6f7a38c8a9f424798e6e726e1d037ed042), [`219fc69`](https://github.com/thirdweb-dev/js/commit/219fc69d72b1ca861bf0228589039788008ea0c0)]:
|
||||||
|
- thirdweb@5.111.0
|
||||||
|
|
||||||
|
## 0.2.77
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`6c318f8`](https://github.com/thirdweb-dev/js/commit/6c318f83d63aa8acce46da666e43638e410f799c), [`759b93b`](https://github.com/thirdweb-dev/js/commit/759b93beff7ab10a3a2fa3b9dd25ca628efb9267), [`8e357b3`](https://github.com/thirdweb-dev/js/commit/8e357b3cb39dcc7a8595a83224098a9c44585389)]:
|
||||||
|
- thirdweb@5.110.6
|
||||||
|
|
||||||
|
## 0.2.76
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`c08fb13`](https://github.com/thirdweb-dev/js/commit/c08fb1356e77be9eeb0569905fcb2ab76a516dc3), [`bcbb3f5`](https://github.com/thirdweb-dev/js/commit/bcbb3f540a8eab2b02f9261b779bd2aad3464598), [`e0c8312`](https://github.com/thirdweb-dev/js/commit/e0c83121c201eb2dbdfa6a6b1bbb637f5ad2a21d)]:
|
||||||
|
- thirdweb@5.110.5
|
||||||
|
|
||||||
|
## 0.2.75
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`23cb3bd`](https://github.com/thirdweb-dev/js/commit/23cb3bd98c5390e64f45da5a222042cdc76bd7f4), [`abf0bba`](https://github.com/thirdweb-dev/js/commit/abf0bbaf359c8de5b0ed0d481e3791c4b7cbf92b), [`e0abf2b`](https://github.com/thirdweb-dev/js/commit/e0abf2b2738661fda3c69551d78231cfac4b0767)]:
|
||||||
|
- thirdweb@5.110.4
|
||||||
|
|
||||||
|
## 0.2.74
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`bf46520`](https://github.com/thirdweb-dev/js/commit/bf46520a6b183c4beb873de5e63853cd3a23e685)]:
|
||||||
|
- thirdweb@5.110.3
|
||||||
|
|
||||||
|
## 0.2.73
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`3e9eb49`](https://github.com/thirdweb-dev/js/commit/3e9eb49787e00c09c3286aeb4ad73826a2856e65), [`bfd3be7`](https://github.com/thirdweb-dev/js/commit/bfd3be764c461c420f1f8520fe4d5d2cc83e42f7), [`ae3a122`](https://github.com/thirdweb-dev/js/commit/ae3a122cf1628f0fc997dd240d4b23842ac30f66), [`d5d5939`](https://github.com/thirdweb-dev/js/commit/d5d593956e12b2a15393ed32d1d742bc43575bdd), [`f757e60`](https://github.com/thirdweb-dev/js/commit/f757e6084648b6b6e5879abeab30954753a1020d)]:
|
||||||
|
- thirdweb@5.110.2
|
||||||
|
|
||||||
|
## 0.2.72
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Updated dependencies [[`85fe949`](https://github.com/thirdweb-dev/js/commit/85fe9491cd6d2270847e9941ddb7df76aefd8b31), [`e978809`](https://github.com/thirdweb-dev/js/commit/e9788096d665afef7c2a933cea5d6f522fc67273), [`899051f`](https://github.com/thirdweb-dev/js/commit/899051f788b0c2521a022846782892a8c1405a66)]:
|
||||||
|
- thirdweb@5.110.1
|
||||||
|
|
||||||
## 0.2.71
|
## 0.2.71
|
||||||
|
|
||||||
### Patch Changes
|
### Patch Changes
|
||||||
|
|||||||
@@ -57,5 +57,5 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"types": "./dist/types/exports/thirdweb.d.ts",
|
"types": "./dist/types/exports/thirdweb.d.ts",
|
||||||
"typings": "./dist/types/exports/thirdweb.d.ts",
|
"typings": "./dist/types/exports/thirdweb.d.ts",
|
||||||
"version": "0.2.71"
|
"version": "0.2.80"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"import": "*",
|
||||||
|
"limit": "1 kB",
|
||||||
|
"name": "@thirdweb-dev/nexus (esm)",
|
||||||
|
"path": "./dist/esm/exports/nexus.js"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"limit": "1 kB",
|
||||||
|
"name": "@thirdweb-dev/nexus (cjs)",
|
||||||
|
"path": "./dist/cjs/exports/nexus.js"
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/2.0.6/schema.json",
|
||||||
|
"extends": "//",
|
||||||
|
"overrides": [
|
||||||
|
{
|
||||||
|
"assist": {
|
||||||
|
"actions": {
|
||||||
|
"source": {
|
||||||
|
"useSortedKeys": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"includes": ["package.json"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://unpkg.com/knip@5/schema.json",
|
||||||
|
"entry": ["src/exports/**"],
|
||||||
|
"ignore": ["src/**/__generated__/**", "**/*.bench.ts"],
|
||||||
|
"ignoreBinaries": ["printf"],
|
||||||
|
"ignoreDependencies": ["tslib"],
|
||||||
|
"project": ["src/**/*.{ts,tsx}"],
|
||||||
|
"rules": {
|
||||||
|
"enumMembers": "off",
|
||||||
|
"optionalPeerDependencies": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
{
|
||||||
|
"author": "thirdweb eng <[email protected]>",
|
||||||
|
"browser": {
|
||||||
|
"crypto": false
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/thirdweb-dev/js/issues"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@biomejs/biome": "2.0.6",
|
||||||
|
"@size-limit/preset-small-lib": "11.2.0",
|
||||||
|
"knip": "5.60.2",
|
||||||
|
"rimraf": "6.0.1",
|
||||||
|
"size-limit": "11.2.0",
|
||||||
|
"typescript": "5.8.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/types/exports/nexus-fetch.d.ts",
|
||||||
|
"import": "./dist/esm/exports/nexus-fetch.js",
|
||||||
|
"default": "./dist/cjs/exports/nexus-fetch.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist/*",
|
||||||
|
"src/*",
|
||||||
|
"!**/*.tsbuildinfo",
|
||||||
|
"!**/*.test.ts",
|
||||||
|
"!**/*.test.tsx",
|
||||||
|
"!**/*.test.ts.snap",
|
||||||
|
"!**/*.test-d.ts",
|
||||||
|
"!**/*.bench.ts",
|
||||||
|
"!tsconfig.build.json"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"main": "./dist/cjs/exports/nexus-fetch.js",
|
||||||
|
"module": "./dist/esm/exports/nexus-fetch.js",
|
||||||
|
"name": "@thirdweb-dev/fetch",
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=5.0.4"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"typescript": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/thirdweb-dev/js.git#main"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "pnpm clean && pnpm build:types && pnpm build:cjs && pnpm build:esm",
|
||||||
|
"build:cjs": "tsc --noCheck --project ./tsconfig.build.json --module commonjs --outDir ./dist/cjs --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./dist/cjs/package.json",
|
||||||
|
"build:esm": "tsc --noCheck --project ./tsconfig.build.json --module es2020 --outDir ./dist/esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./dist/esm/package.json",
|
||||||
|
"build:types": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --declarationDir ./dist/types --emitDeclarationOnly --declaration --declarationMap",
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"dev": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --outDir ./dist/esm --watch",
|
||||||
|
"dev:cjs": "printf '{\"type\":\"commonjs\"}' > ./dist/cjs/package.json && tsc --noCheck --project ./tsconfig.build.json --module commonjs --outDir ./dist/cjs --verbatimModuleSyntax false --watch",
|
||||||
|
"dev:esm": "printf '{\"type\": \"module\",\"sideEffects\":false}' > ./dist/esm/package.json && tsc --noCheck --project ./tsconfig.build.json --module es2020 --outDir ./dist/esm --watch",
|
||||||
|
"fix": "biome check ./src --fix",
|
||||||
|
"format": "biome format ./src --write",
|
||||||
|
"knip": "knip",
|
||||||
|
"lint": "knip && biome check ./src && tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --noEmit",
|
||||||
|
"size": "size-limit",
|
||||||
|
"typecheck": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --noEmit",
|
||||||
|
"test:ui": "bun ./testing/test.html --watch"
|
||||||
|
},
|
||||||
|
"sideEffects": false,
|
||||||
|
"type": "module",
|
||||||
|
"types": "./dist/types/exports/nexus-fetch.d.ts",
|
||||||
|
"typings": "./dist/types/exports/nexus-fetch.d.ts",
|
||||||
|
"version": "0.0.0"
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { wrap } from "../fetch.js";
|
||||||
@@ -0,0 +1,459 @@
|
|||||||
|
//---
|
||||||
|
// Constants
|
||||||
|
//---
|
||||||
|
const TOKEN_DATA_KEY = "tw:nexus:td";
|
||||||
|
const STATE_KEY = "tw:nexus:state";
|
||||||
|
const VERIFIER_KEY = "tw:nexus:verifier";
|
||||||
|
const NEXUS_API_BASE_URL = "https://nexus-api.thirdweb-dev.com";
|
||||||
|
const OAUTH_CLIENT_ID = "9ad56e84-5abe-4ea5-a6c2-9834b9d31245";
|
||||||
|
// Token expiry buffer: consider token expired 5 minutes before actual expiry
|
||||||
|
const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Types
|
||||||
|
//---
|
||||||
|
type TokenData = {
|
||||||
|
accessToken: string;
|
||||||
|
refreshToken: string;
|
||||||
|
expiresAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OAuthTokenResponse = {
|
||||||
|
access_token: string;
|
||||||
|
expires_in: number;
|
||||||
|
refresh_token: string;
|
||||||
|
token_type: "Bearer";
|
||||||
|
};
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Token Encoding/Decoding
|
||||||
|
//---
|
||||||
|
function encodeTokenData(data: TokenData): string {
|
||||||
|
return btoa(JSON.stringify(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeTokenData(encoded: string): TokenData | null {
|
||||||
|
try {
|
||||||
|
const decoded = atob(encoded);
|
||||||
|
return JSON.parse(decoded) as TokenData;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Initialization
|
||||||
|
// Automatically wrap global fetch and complete OAuth flow if returning from authorization
|
||||||
|
//---
|
||||||
|
(() => {
|
||||||
|
if (hasWindow()) {
|
||||||
|
completeOauthFlow();
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
try {
|
||||||
|
globalThis.fetch = wrap(originalFetch);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[thirdweb nexus] Error wrapping fetch", error);
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Main Fetch Wrapper
|
||||||
|
//---
|
||||||
|
/**
|
||||||
|
* Wraps a fetch function to automatically handle HTTP 402 (Payment Required) responses.
|
||||||
|
* When a 402 is encountered, it uses the Nexus API to process the payment and retry the request.
|
||||||
|
*
|
||||||
|
* @param fetchFn - The fetch function to wrap (typically globalThis.fetch)
|
||||||
|
* @param options - Optional configuration
|
||||||
|
* @param options.maxValue - Maximum payment value allowed in wei
|
||||||
|
* @returns A wrapped fetch function that handles 402 responses
|
||||||
|
*/
|
||||||
|
export function wrap(
|
||||||
|
fetchFn: typeof globalThis.fetch,
|
||||||
|
options?: {
|
||||||
|
maxValue?: bigint;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||||
|
const response = await fetchFn(input, init);
|
||||||
|
|
||||||
|
if (response.status !== 402) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AT = await getAuthToken();
|
||||||
|
if (!AT) {
|
||||||
|
// open login page in a new tab or throw an error if opening fails
|
||||||
|
startOauthFlow();
|
||||||
|
return new Response("Payment required", { status: 402 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// create the proxy request
|
||||||
|
const proxyUrl = new URL("/fetch", NEXUS_API_BASE_URL);
|
||||||
|
proxyUrl.searchParams.set(
|
||||||
|
"data",
|
||||||
|
btoa(
|
||||||
|
JSON.stringify({
|
||||||
|
// original request related information
|
||||||
|
request: {
|
||||||
|
url: new URL(
|
||||||
|
typeof input === "string"
|
||||||
|
? input
|
||||||
|
: input instanceof Request
|
||||||
|
? input.url
|
||||||
|
: input,
|
||||||
|
).toString(),
|
||||||
|
method:
|
||||||
|
(typeof input === "string"
|
||||||
|
? init?.method
|
||||||
|
: input instanceof Request
|
||||||
|
? input.method
|
||||||
|
: "GET") ?? "GET",
|
||||||
|
headers:
|
||||||
|
typeof input === "string"
|
||||||
|
? init?.headers
|
||||||
|
: input instanceof Request
|
||||||
|
? input.headers
|
||||||
|
: {},
|
||||||
|
},
|
||||||
|
// x402 options
|
||||||
|
x402Options: {
|
||||||
|
...(options?.maxValue
|
||||||
|
? { maxValue: options.maxValue.toString() }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
let proxyRes = await fetchFn(proxyUrl, {
|
||||||
|
method: "POST",
|
||||||
|
body:
|
||||||
|
(typeof input === "string"
|
||||||
|
? init?.body
|
||||||
|
: input instanceof Request
|
||||||
|
? input.body
|
||||||
|
: init?.body) ?? undefined,
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${AT}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle 401 (unauthorized) - try to refresh token and retry
|
||||||
|
if (proxyRes.status === 401) {
|
||||||
|
const refreshedToken = await refreshAccessToken();
|
||||||
|
if (refreshedToken) {
|
||||||
|
// Retry with refreshed token
|
||||||
|
proxyRes = await fetchFn(proxyUrl, {
|
||||||
|
method: "POST",
|
||||||
|
body:
|
||||||
|
(typeof input === "string"
|
||||||
|
? init?.body
|
||||||
|
: input instanceof Request
|
||||||
|
? input.body
|
||||||
|
: init?.body) ?? undefined,
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${refreshedToken}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Refresh failed, start OAuth flow
|
||||||
|
startOauthFlow();
|
||||||
|
return new Response("Unauthorized", { status: 401 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (proxyRes.status === 402) {
|
||||||
|
// means the wallet doesn't have funds and needs to onramp, open the funding link
|
||||||
|
const data = (await proxyRes.json()) as {
|
||||||
|
result: { link: string; message: string };
|
||||||
|
};
|
||||||
|
// TODO: we can await this and then retry the call after by setting up
|
||||||
|
// window.postMessage communication and opening this in a new tab
|
||||||
|
const paymentUrl = new URL(data.result.link);
|
||||||
|
paymentUrl.searchParams.set("successUrl", window.location.href);
|
||||||
|
window.location.href = paymentUrl.toString();
|
||||||
|
return new Response("Payment required", { status: 402 });
|
||||||
|
}
|
||||||
|
return proxyRes;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Browser/Environment Utilities
|
||||||
|
//---
|
||||||
|
function hasWindow(): boolean {
|
||||||
|
return typeof window !== "undefined";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getLocalStorage(): Storage | null {
|
||||||
|
try {
|
||||||
|
return hasWindow() ? window.localStorage : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Token Data Management
|
||||||
|
//---
|
||||||
|
let inMemoryTokenData: TokenData | null = null;
|
||||||
|
|
||||||
|
function getTokenData(): TokenData | null {
|
||||||
|
if (inMemoryTokenData !== null) {
|
||||||
|
return inMemoryTokenData;
|
||||||
|
}
|
||||||
|
const encoded = getLocalStorage()?.getItem(TOKEN_DATA_KEY);
|
||||||
|
if (encoded) {
|
||||||
|
const data = decodeTokenData(encoded);
|
||||||
|
if (data) {
|
||||||
|
inMemoryTokenData = data;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTokenData(
|
||||||
|
accessToken: string,
|
||||||
|
refreshToken: string,
|
||||||
|
expiresIn: number,
|
||||||
|
): void {
|
||||||
|
if (!accessToken || accessToken === "undefined") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!refreshToken || refreshToken === "undefined") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Calculate expiry timestamp (current time + expires_in seconds)
|
||||||
|
const expiresAt = Date.now() + expiresIn * 1000;
|
||||||
|
const tokenData: TokenData = { accessToken, refreshToken, expiresAt };
|
||||||
|
const encoded = encodeTokenData(tokenData);
|
||||||
|
getLocalStorage()?.setItem(TOKEN_DATA_KEY, encoded);
|
||||||
|
inMemoryTokenData = tokenData;
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteTokenData(): void {
|
||||||
|
getLocalStorage()?.removeItem(TOKEN_DATA_KEY);
|
||||||
|
inMemoryTokenData = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTokenExpired(tokenData: TokenData | null): boolean {
|
||||||
|
if (!tokenData) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return Date.now() >= tokenData.expiresAt - TOKEN_EXPIRY_BUFFER_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// Token Validation & Refresh
|
||||||
|
//---
|
||||||
|
/**
|
||||||
|
* Gets a valid access token, refreshing it if necessary.
|
||||||
|
* @returns A valid access token or null if unavailable
|
||||||
|
*/
|
||||||
|
async function getAuthToken(): Promise<string | null> {
|
||||||
|
const tokenData = getTokenData();
|
||||||
|
|
||||||
|
// If we have a token but it's expired, try to refresh
|
||||||
|
if (tokenData && isTokenExpired(tokenData)) {
|
||||||
|
const refreshedToken = await refreshAccessToken();
|
||||||
|
return refreshedToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokenData?.accessToken ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refreshes an expired access token using the refresh token.
|
||||||
|
* @returns A new access token or null if refresh fails
|
||||||
|
*/
|
||||||
|
async function refreshAccessToken(): Promise<string | null> {
|
||||||
|
const tokenData = getTokenData();
|
||||||
|
if (!tokenData) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${NEXUS_API_BASE_URL}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
grant_type: "refresh_token",
|
||||||
|
refresh_token: tokenData.refreshToken,
|
||||||
|
client_id: OAUTH_CLIENT_ID,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
// Refresh failed, clear all tokens
|
||||||
|
deleteTokenData();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as OAuthTokenResponse;
|
||||||
|
|
||||||
|
// Store new tokens
|
||||||
|
setTokenData(data.access_token, data.refresh_token, data.expires_in);
|
||||||
|
|
||||||
|
return data.access_token;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[thirdweb nexus] Error refreshing access token", error);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// OAuth PKCE (Proof Key for Code Exchange) Utilities
|
||||||
|
//---
|
||||||
|
function storeState(code: string): void {
|
||||||
|
getLocalStorage()?.setItem(STATE_KEY, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getState(): string | null | undefined {
|
||||||
|
return getLocalStorage()?.getItem(STATE_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteState(): void {
|
||||||
|
getLocalStorage()?.removeItem(STATE_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeVerifier(verifier: string): void {
|
||||||
|
getLocalStorage()?.setItem(VERIFIER_KEY, verifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getVerifier(): string | null | undefined {
|
||||||
|
return getLocalStorage()?.getItem(VERIFIER_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteVerifier(): void {
|
||||||
|
getLocalStorage()?.removeItem(VERIFIER_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a cryptographically random code verifier for PKCE.
|
||||||
|
*/
|
||||||
|
function generateCodeVerifier(): string {
|
||||||
|
const array = new Uint8Array(32);
|
||||||
|
crypto.getRandomValues(array);
|
||||||
|
return base64UrlEncode(array);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a code challenge from a verifier for PKCE using SHA-256.
|
||||||
|
*/
|
||||||
|
async function generateCodeChallenge(verifier: string): Promise<string> {
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const data = encoder.encode(verifier);
|
||||||
|
const hash = await crypto.subtle.digest("SHA-256", data);
|
||||||
|
return base64UrlEncode(new Uint8Array(hash));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base64 URL-safe encoding (without padding).
|
||||||
|
*/
|
||||||
|
function base64UrlEncode(array: Uint8Array): string {
|
||||||
|
const base64 = btoa(String.fromCharCode(...array));
|
||||||
|
return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
//---
|
||||||
|
// OAuth Flow
|
||||||
|
//---
|
||||||
|
/**
|
||||||
|
* Initiates the OAuth authorization flow by redirecting to the Nexus authorization endpoint.
|
||||||
|
*/
|
||||||
|
async function startOauthFlow(): Promise<void> {
|
||||||
|
const state = crypto.randomUUID();
|
||||||
|
const verifier = generateCodeVerifier();
|
||||||
|
const challenge = await generateCodeChallenge(verifier);
|
||||||
|
|
||||||
|
const redirectUri = new URL(window.location.href);
|
||||||
|
const url = new URL("/oauth/authorize", NEXUS_API_BASE_URL);
|
||||||
|
url.searchParams.set("response_type", "code");
|
||||||
|
url.searchParams.set("client_id", OAUTH_CLIENT_ID);
|
||||||
|
url.searchParams.set("code_challenge", challenge);
|
||||||
|
url.searchParams.set("code_challenge_method", "S256");
|
||||||
|
url.searchParams.set("state", state);
|
||||||
|
url.searchParams.set(
|
||||||
|
"redirect_uri",
|
||||||
|
`${redirectUri.origin}${redirectUri.pathname}`,
|
||||||
|
);
|
||||||
|
storeState(state);
|
||||||
|
storeVerifier(verifier);
|
||||||
|
|
||||||
|
// just open the page directly
|
||||||
|
window.location.href = url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Completes the OAuth flow by exchanging the authorization code for tokens.
|
||||||
|
* Called automatically on page load if code parameter is present in URL.
|
||||||
|
*/
|
||||||
|
async function completeOauthFlow(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const searchParams = new URL(window.location.href).searchParams;
|
||||||
|
const code = searchParams.get("code");
|
||||||
|
const state = searchParams.get("state");
|
||||||
|
const error = searchParams.get("error");
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("[thirdweb nexus] OAuth error:", error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!code || !state) {
|
||||||
|
// No code or state found, nothing to do
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state !== getState()) {
|
||||||
|
// State mismatch - possible CSRF attack
|
||||||
|
console.warn("[thirdweb nexus] OAuth state mismatch");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const verifier = getVerifier();
|
||||||
|
if (!verifier) {
|
||||||
|
// No verifier found, nothing to do
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the state and verifier so they can't be reused
|
||||||
|
deleteState();
|
||||||
|
deleteVerifier();
|
||||||
|
|
||||||
|
const redirectUri = new URL(window.location.href);
|
||||||
|
const response = await fetch(`${NEXUS_API_BASE_URL}/oauth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
code,
|
||||||
|
code_verifier: verifier,
|
||||||
|
grant_type: "authorization_code",
|
||||||
|
redirect_uri: `${redirectUri.origin}${redirectUri.pathname}`,
|
||||||
|
client_id: OAUTH_CLIENT_ID,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error(
|
||||||
|
"[thirdweb nexus] Failed to exchange authorization code for tokens",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as OAuthTokenResponse;
|
||||||
|
|
||||||
|
// Store all token data
|
||||||
|
setTokenData(data.access_token, data.refresh_token, data.expires_in);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("[thirdweb nexus] Error completing OAuth flow:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Nexus Fetch Testing</title>
|
||||||
|
<script src="../src/exports/nexus-fetch.ts"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<button id="test-button">Test</button>
|
||||||
|
<script>
|
||||||
|
const testButton = document.getElementById("test-button");
|
||||||
|
testButton.addEventListener("click", () => {
|
||||||
|
fetch("https://q1qkkomp.nx.link/kindle", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
recipient: "0x0890C23024089675D072E984f28A93bb391a35Ab",
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
testButton.click();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
// This tsconfig file contains the shared config for the build (tsconfig.build.json) and type checking (tsconfig.json) config.
|
||||||
|
"compilerOptions": {
|
||||||
|
// Incremental builds
|
||||||
|
// NOTE: Enabling incremental builds speeds up `tsc`. Keep in mind though that it does not reliably bust the cache when the `tsconfig.json` file changes.
|
||||||
|
"allowJs": false,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"checkJs": false,
|
||||||
|
|
||||||
|
// Interop constraints
|
||||||
|
"esModuleInterop": false,
|
||||||
|
"exactOptionalPropertyTypes": false,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"importHelpers": true,
|
||||||
|
// Incremental builds
|
||||||
|
// NOTE: Enabling incremental builds speeds up `tsc`. Keep in mind though that it does not reliably bust the cache when the `tsconfig.json` file changes.
|
||||||
|
"incremental": false,
|
||||||
|
|
||||||
|
// jsx for "/react" portion
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"lib": [
|
||||||
|
"ES2022", // By using ES2022 we get access to the `.cause` property on `Error` instances.
|
||||||
|
"DOM" // We are adding `DOM` here to get the `fetch`, etc. types. This should be removed once these types are available via DefinitelyTyped.
|
||||||
|
],
|
||||||
|
"module": "NodeNext",
|
||||||
|
|
||||||
|
// Language and environment
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"noImplicitReturns": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
|
||||||
|
// Skip type checking for node modules
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
// Type checking
|
||||||
|
"strict": true,
|
||||||
|
"target": "ES2021",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"useUnknownInCatchVariables": true,
|
||||||
|
"verbatimModuleSyntax": true
|
||||||
|
},
|
||||||
|
// This tsconfig file contains the shared config for the build (tsconfig.build.json) and type checking (tsconfig.json) config.
|
||||||
|
"include": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"src/**/*.test.ts",
|
||||||
|
"src/**/*.test.tsx",
|
||||||
|
"src/**/*.test-d.ts",
|
||||||
|
"src/**/*.bench.ts",
|
||||||
|
"src/**/*.macro.ts"
|
||||||
|
],
|
||||||
|
"extends": "./tsconfig.base.json",
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
// This configuration is used for local development and type checking.
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"outDir": "./dist",
|
||||||
|
"paths": {
|
||||||
|
"~test/*": ["./test/src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exclude": [],
|
||||||
|
"extends": "./tsconfig.base.json",
|
||||||
|
"include": ["src", "test"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"import": "*",
|
||||||
|
"limit": "110 kB",
|
||||||
|
"name": "@thirdweb-dev/nexus (esm)",
|
||||||
|
"path": "./dist/esm/exports/nexus.js"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"limit": "350 kB",
|
||||||
|
"name": "@thirdweb-dev/nexus (cjs)",
|
||||||
|
"path": "./dist/cjs/exports/nexus.js"
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# @thirdweb-dev/nexus
|
||||||
|
|
||||||
|
## 0.1.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#8332](https://github.com/thirdweb-dev/js/pull/8332) [`8e357b3`](https://github.com/thirdweb-dev/js/commit/8e357b3cb39dcc7a8595a83224098a9c44585389) Thanks [@jnsdls](https://github.com/jnsdls)! - initial release
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/2.0.6/schema.json",
|
||||||
|
"extends": "//",
|
||||||
|
"overrides": [
|
||||||
|
{
|
||||||
|
"assist": {
|
||||||
|
"actions": {
|
||||||
|
"source": {
|
||||||
|
"useSortedKeys": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"includes": ["package.json"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://unpkg.com/knip@5/schema.json",
|
||||||
|
"entry": ["src/exports/**"],
|
||||||
|
"ignore": ["src/**/__generated__/**", "**/*.bench.ts"],
|
||||||
|
"ignoreBinaries": ["printf"],
|
||||||
|
"ignoreDependencies": ["tslib"],
|
||||||
|
"project": ["src/**/*.{ts,tsx}"],
|
||||||
|
"rules": {
|
||||||
|
"enumMembers": "off",
|
||||||
|
"optionalPeerDependencies": "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
{
|
||||||
|
"author": "thirdweb eng <[email protected]>",
|
||||||
|
"browser": {
|
||||||
|
"crypto": false
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/thirdweb-dev/js/issues"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"x402": "0.7.0",
|
||||||
|
"zod": "3.25.75"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@biomejs/biome": "2.0.6",
|
||||||
|
"@size-limit/preset-small-lib": "11.2.0",
|
||||||
|
"knip": "5.60.2",
|
||||||
|
"rimraf": "6.0.1",
|
||||||
|
"size-limit": "11.2.0",
|
||||||
|
"typescript": "5.8.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/types/exports/nexus.d.ts",
|
||||||
|
"import": "./dist/esm/exports/nexus.js",
|
||||||
|
"default": "./dist/cjs/exports/nexus.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist/*",
|
||||||
|
"src/*",
|
||||||
|
"!**/*.tsbuildinfo",
|
||||||
|
"!**/*.test.ts",
|
||||||
|
"!**/*.test.tsx",
|
||||||
|
"!**/*.test.ts.snap",
|
||||||
|
"!**/*.test-d.ts",
|
||||||
|
"!**/*.bench.ts",
|
||||||
|
"!tsconfig.build.json"
|
||||||
|
],
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"main": "./dist/cjs/exports/nexus.js",
|
||||||
|
"module": "./dist/esm/exports/nexus.js",
|
||||||
|
"name": "@thirdweb-dev/nexus",
|
||||||
|
"peerDependencies": {
|
||||||
|
"typescript": ">=5.0.4"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"typescript": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/thirdweb-dev/js.git#main"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "pnpm clean && pnpm build:types && pnpm build:cjs && pnpm build:esm",
|
||||||
|
"build:cjs": "tsc --noCheck --project ./tsconfig.build.json --module commonjs --outDir ./dist/cjs --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./dist/cjs/package.json",
|
||||||
|
"build:esm": "tsc --noCheck --project ./tsconfig.build.json --module es2020 --outDir ./dist/esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./dist/esm/package.json",
|
||||||
|
"build:types": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --declarationDir ./dist/types --emitDeclarationOnly --declaration --declarationMap",
|
||||||
|
"clean": "rimraf dist",
|
||||||
|
"dev": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --outDir ./dist/esm --watch",
|
||||||
|
"dev:cjs": "printf '{\"type\":\"commonjs\"}' > ./dist/cjs/package.json && tsc --noCheck --project ./tsconfig.build.json --module commonjs --outDir ./dist/cjs --verbatimModuleSyntax false --watch",
|
||||||
|
"dev:esm": "printf '{\"type\": \"module\",\"sideEffects\":false}' > ./dist/esm/package.json && tsc --noCheck --project ./tsconfig.build.json --module es2020 --outDir ./dist/esm --watch",
|
||||||
|
"fix": "biome check ./src --fix",
|
||||||
|
"format": "biome format ./src --write",
|
||||||
|
"knip": "knip",
|
||||||
|
"lint": "knip && biome check ./src && tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --noEmit",
|
||||||
|
"size": "size-limit",
|
||||||
|
"typecheck": "tsc --project ./tsconfig.build.json --module nodenext --moduleResolution nodenext --noEmit"
|
||||||
|
},
|
||||||
|
"sideEffects": false,
|
||||||
|
"type": "module",
|
||||||
|
"types": "./dist/types/exports/nexus.d.ts",
|
||||||
|
"typings": "./dist/types/exports/nexus.d.ts",
|
||||||
|
"version": "0.1.0"
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
import { ChainIdToNetwork, type Money, moneySchema } from "x402/types";
|
||||||
|
import { decodePayment } from "./encode.js";
|
||||||
|
import type { ThirdwebX402Facilitator } from "./facilitator.js";
|
||||||
|
import {
|
||||||
|
networkToChainId,
|
||||||
|
type RequestedPaymentPayload,
|
||||||
|
type RequestedPaymentRequirements,
|
||||||
|
} from "./schemas.js";
|
||||||
|
import {
|
||||||
|
type DefaultAsset,
|
||||||
|
type ERC20TokenAmount,
|
||||||
|
type PaymentArgs,
|
||||||
|
type PaymentRequiredResult,
|
||||||
|
type SupportedSignatureType,
|
||||||
|
x402Version,
|
||||||
|
} from "./types.js";
|
||||||
|
import { toUnits } from "./utils.js";
|
||||||
|
|
||||||
|
type GetPaymentRequirementsResult = {
|
||||||
|
status: 200;
|
||||||
|
paymentRequirements: RequestedPaymentRequirements[];
|
||||||
|
selectedPaymentRequirements: RequestedPaymentRequirements;
|
||||||
|
decodedPayment: RequestedPaymentPayload;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes a payment request and returns the payment requirements, selected payment requirements, and decoded payment
|
||||||
|
* @param args
|
||||||
|
* @returns The payment requirements, selected payment requirements, and decoded payment
|
||||||
|
*/
|
||||||
|
export async function decodePaymentRequest(
|
||||||
|
args: PaymentArgs,
|
||||||
|
): Promise<GetPaymentRequirementsResult | PaymentRequiredResult> {
|
||||||
|
const {
|
||||||
|
price,
|
||||||
|
network,
|
||||||
|
facilitator,
|
||||||
|
payTo,
|
||||||
|
resourceUrl,
|
||||||
|
routeConfig = {},
|
||||||
|
method,
|
||||||
|
paymentData,
|
||||||
|
} = args;
|
||||||
|
const {
|
||||||
|
description,
|
||||||
|
mimeType,
|
||||||
|
maxTimeoutSeconds,
|
||||||
|
inputSchema,
|
||||||
|
outputSchema,
|
||||||
|
errorMessages,
|
||||||
|
discoverable,
|
||||||
|
} = routeConfig;
|
||||||
|
|
||||||
|
let chainId: number;
|
||||||
|
try {
|
||||||
|
chainId = networkToChainId(network);
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: { "Content-Type": "application/json" },
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error:
|
||||||
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: `Invalid network: ${network}`,
|
||||||
|
accepts: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const atomicAmountForAsset = await processPriceToAtomicAmount(
|
||||||
|
price,
|
||||||
|
chainId,
|
||||||
|
facilitator,
|
||||||
|
);
|
||||||
|
if ("error" in atomicAmountForAsset) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: { "Content-Type": "application/json" },
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error: atomicAmountForAsset.error,
|
||||||
|
accepts: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const { maxAmountRequired, asset } = atomicAmountForAsset;
|
||||||
|
|
||||||
|
const paymentRequirements: RequestedPaymentRequirements[] = [];
|
||||||
|
|
||||||
|
const mappedNetwork = ChainIdToNetwork[chainId];
|
||||||
|
paymentRequirements.push({
|
||||||
|
scheme: "exact",
|
||||||
|
network: mappedNetwork ? mappedNetwork : `eip155:${chainId}`,
|
||||||
|
maxAmountRequired,
|
||||||
|
resource: resourceUrl,
|
||||||
|
description: description ?? "",
|
||||||
|
mimeType: mimeType ?? "application/json",
|
||||||
|
payTo: facilitator.address as `0x${string}`, // always pay to the facilitator address first
|
||||||
|
maxTimeoutSeconds: maxTimeoutSeconds ?? 86400,
|
||||||
|
asset: asset.address as `0x${string}`,
|
||||||
|
outputSchema: {
|
||||||
|
input: {
|
||||||
|
type: "http",
|
||||||
|
method,
|
||||||
|
discoverable: discoverable ?? true,
|
||||||
|
...inputSchema,
|
||||||
|
},
|
||||||
|
output: outputSchema,
|
||||||
|
},
|
||||||
|
extra: {
|
||||||
|
recipientAddress: payTo, // input payTo is the final recipient address
|
||||||
|
...((asset as ERC20TokenAmount["asset"]).eip712 ?? {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Check for payment header
|
||||||
|
if (!paymentData) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error: errorMessages?.paymentRequired || "X-PAYMENT header is required",
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// decode b64 payment
|
||||||
|
let decodedPayment: RequestedPaymentPayload;
|
||||||
|
try {
|
||||||
|
decodedPayment = decodePayment(paymentData);
|
||||||
|
decodedPayment.x402Version = x402Version;
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error:
|
||||||
|
errorMessages?.invalidPayment ||
|
||||||
|
(error instanceof Error ? error.message : "Invalid payment"),
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedPaymentRequirements = paymentRequirements.find(
|
||||||
|
(value) =>
|
||||||
|
value.scheme === decodedPayment.scheme &&
|
||||||
|
networkToChainId(value.network) ===
|
||||||
|
networkToChainId(decodedPayment.network),
|
||||||
|
);
|
||||||
|
if (!selectedPaymentRequirements) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error:
|
||||||
|
errorMessages?.noMatchingRequirements ||
|
||||||
|
"Unable to find matching payment requirements",
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
paymentRequirements,
|
||||||
|
decodedPayment,
|
||||||
|
selectedPaymentRequirements,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses the amount from the given price
|
||||||
|
*
|
||||||
|
* @param price - The price to parse
|
||||||
|
* @param network - The network to get the default asset for
|
||||||
|
* @returns The parsed amount or an error message
|
||||||
|
*/
|
||||||
|
async function processPriceToAtomicAmount(
|
||||||
|
price: Money | ERC20TokenAmount,
|
||||||
|
chainId: number,
|
||||||
|
facilitator: ThirdwebX402Facilitator,
|
||||||
|
): Promise<
|
||||||
|
{ maxAmountRequired: string; asset: DefaultAsset } | { error: string }
|
||||||
|
> {
|
||||||
|
// Handle USDC amount (string) or token amount (ERC20TokenAmount)
|
||||||
|
let maxAmountRequired: string;
|
||||||
|
let asset: DefaultAsset;
|
||||||
|
|
||||||
|
if (typeof price === "string" || typeof price === "number") {
|
||||||
|
// USDC amount in dollars
|
||||||
|
const parsedAmount = moneySchema.safeParse(price);
|
||||||
|
if (!parsedAmount.success) {
|
||||||
|
return {
|
||||||
|
error: `Invalid price (price: ${price}). Must be in the form "$3.10", 0.10, "0.001", ${parsedAmount.error}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const parsedUsdAmount = parsedAmount.data;
|
||||||
|
const defaultAsset = await getDefaultAsset(chainId, facilitator);
|
||||||
|
if (!defaultAsset) {
|
||||||
|
return {
|
||||||
|
error: `Unable to get default asset on chain ${chainId}. Please specify an asset in the payment requirements.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
asset = defaultAsset;
|
||||||
|
maxAmountRequired = toUnits(
|
||||||
|
parsedUsdAmount.toString(),
|
||||||
|
defaultAsset.decimals,
|
||||||
|
).toString();
|
||||||
|
} else {
|
||||||
|
// Token amount in atomic units
|
||||||
|
maxAmountRequired = price.amount;
|
||||||
|
const tokenExtras = await getOrDetectTokenExtras({
|
||||||
|
facilitator,
|
||||||
|
partialAsset: price.asset,
|
||||||
|
chainId,
|
||||||
|
});
|
||||||
|
if (!tokenExtras) {
|
||||||
|
return {
|
||||||
|
error: `Unable to find token information for ${price.asset.address} on chain ${chainId}. Please specify the asset decimals and eip712 information in the asset options.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
asset = {
|
||||||
|
address: price.asset.address,
|
||||||
|
decimals: tokenExtras.decimals,
|
||||||
|
eip712: {
|
||||||
|
name: tokenExtras.name,
|
||||||
|
version: tokenExtras.version,
|
||||||
|
primaryType: tokenExtras.primaryType,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
maxAmountRequired,
|
||||||
|
asset,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getDefaultAsset(
|
||||||
|
chainId: number,
|
||||||
|
facilitator: ThirdwebX402Facilitator,
|
||||||
|
): Promise<DefaultAsset | undefined> {
|
||||||
|
const supportedAssets = await facilitator.supported();
|
||||||
|
const matchingAsset = supportedAssets.kinds.find(
|
||||||
|
(supported) => networkToChainId(supported.network) === chainId,
|
||||||
|
);
|
||||||
|
const assetConfig = matchingAsset?.extra?.defaultAsset as DefaultAsset;
|
||||||
|
return assetConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getOrDetectTokenExtras(args: {
|
||||||
|
facilitator: ThirdwebX402Facilitator;
|
||||||
|
partialAsset: ERC20TokenAmount["asset"];
|
||||||
|
chainId: number;
|
||||||
|
}): Promise<
|
||||||
|
| {
|
||||||
|
name: string;
|
||||||
|
version: string;
|
||||||
|
decimals: number;
|
||||||
|
primaryType: SupportedSignatureType;
|
||||||
|
}
|
||||||
|
| undefined
|
||||||
|
> {
|
||||||
|
const { facilitator, partialAsset, chainId } = args;
|
||||||
|
if (
|
||||||
|
partialAsset.eip712?.name &&
|
||||||
|
partialAsset.eip712?.version &&
|
||||||
|
partialAsset.decimals !== undefined
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
name: partialAsset.eip712.name,
|
||||||
|
version: partialAsset.eip712.version,
|
||||||
|
decimals: partialAsset.decimals,
|
||||||
|
primaryType: partialAsset.eip712.primaryType,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// read from facilitator
|
||||||
|
const response = await facilitator
|
||||||
|
.supported({
|
||||||
|
chainId,
|
||||||
|
tokenAddress: partialAsset.address,
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
return {
|
||||||
|
kinds: [],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const exactScheme = response.kinds?.find((kind) => kind.scheme === "exact");
|
||||||
|
if (!exactScheme) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const supportedAsset = exactScheme.extra?.supportedAssets?.find(
|
||||||
|
(asset) =>
|
||||||
|
asset.address.toLowerCase() === partialAsset.address.toLowerCase(),
|
||||||
|
);
|
||||||
|
if (!supportedAsset) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: supportedAsset.eip712.name,
|
||||||
|
version: supportedAsset.eip712.version,
|
||||||
|
decimals: supportedAsset.decimals,
|
||||||
|
primaryType: supportedAsset.eip712.primaryType as SupportedSignatureType,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import type { ExactEvmPayload } from "x402/types";
|
||||||
|
import {
|
||||||
|
type RequestedPaymentPayload,
|
||||||
|
RequestedPaymentPayloadSchema,
|
||||||
|
} from "./schemas.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a payment payload into a base64 string, ensuring bigint values are properly stringified
|
||||||
|
*
|
||||||
|
* @param payment - The payment payload to encode
|
||||||
|
* @returns A base64 encoded string representation of the payment payload
|
||||||
|
*/
|
||||||
|
export function encodePayment(payment: RequestedPaymentPayload): string {
|
||||||
|
let safe: RequestedPaymentPayload;
|
||||||
|
|
||||||
|
// evm
|
||||||
|
const evmPayload = payment.payload as ExactEvmPayload;
|
||||||
|
safe = {
|
||||||
|
...payment,
|
||||||
|
payload: {
|
||||||
|
...evmPayload,
|
||||||
|
authorization: Object.fromEntries(
|
||||||
|
Object.entries(evmPayload.authorization).map(([key, value]) => [
|
||||||
|
key,
|
||||||
|
typeof value === "bigint" ? (value as bigint).toString() : value,
|
||||||
|
]),
|
||||||
|
) as ExactEvmPayload["authorization"],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return safeBase64Encode(JSON.stringify(safe));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes a base64 encoded payment string back into a PaymentPayload object
|
||||||
|
*
|
||||||
|
* @param payment - The base64 encoded payment string to decode
|
||||||
|
* @returns The decoded and validated PaymentPayload object
|
||||||
|
*/
|
||||||
|
export function decodePayment(payment: string): RequestedPaymentPayload {
|
||||||
|
const decoded = safeBase64Decode(payment);
|
||||||
|
const parsed = JSON.parse(decoded);
|
||||||
|
|
||||||
|
const obj: RequestedPaymentPayload = {
|
||||||
|
...parsed,
|
||||||
|
payload: parsed.payload as ExactEvmPayload,
|
||||||
|
};
|
||||||
|
const validated = RequestedPaymentPayloadSchema.parse(obj);
|
||||||
|
return validated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encodes a string to base64 format
|
||||||
|
*
|
||||||
|
* @param data - The string to be encoded to base64
|
||||||
|
* @returns The base64 encoded string
|
||||||
|
*/
|
||||||
|
export function safeBase64Encode(data: string): string {
|
||||||
|
if (
|
||||||
|
typeof globalThis !== "undefined" &&
|
||||||
|
typeof globalThis.btoa === "function"
|
||||||
|
) {
|
||||||
|
return globalThis.btoa(data);
|
||||||
|
}
|
||||||
|
return Buffer.from(data).toString("base64");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decodes a base64 string back to its original format
|
||||||
|
*
|
||||||
|
* @param data - The base64 encoded string to be decoded
|
||||||
|
* @returns The decoded string in UTF-8 format
|
||||||
|
*/
|
||||||
|
function safeBase64Decode(data: string): string {
|
||||||
|
if (
|
||||||
|
typeof globalThis !== "undefined" &&
|
||||||
|
typeof globalThis.atob === "function"
|
||||||
|
) {
|
||||||
|
return globalThis.atob(data);
|
||||||
|
}
|
||||||
|
return Buffer.from(data, "base64").toString("utf-8");
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
export type {
|
||||||
|
HTTPRequestStructure,
|
||||||
|
Money,
|
||||||
|
PaymentMiddlewareConfig,
|
||||||
|
Resource,
|
||||||
|
} from "x402/types";
|
||||||
|
export { decodePayment, encodePayment } from "../encode.js";
|
||||||
|
export {
|
||||||
|
createFacilitator,
|
||||||
|
type ThirdwebX402Facilitator,
|
||||||
|
type ThirdwebX402FacilitatorConfig,
|
||||||
|
type WaitUntil,
|
||||||
|
} from "../facilitator.js";
|
||||||
|
export { settlePayment } from "../settle-payment.js";
|
||||||
|
export type {
|
||||||
|
ERC20TokenAmount,
|
||||||
|
PaymentArgs,
|
||||||
|
PaymentRequiredResult,
|
||||||
|
SettlePaymentArgs,
|
||||||
|
SettlePaymentResult,
|
||||||
|
SupportedSignatureType,
|
||||||
|
VerifyPaymentResult,
|
||||||
|
} from "../types.js";
|
||||||
|
export { verifyPayment } from "../verify-payment.js";
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import type { VerifyResponse } from "x402/types";
|
||||||
|
import type {
|
||||||
|
FacilitatorSettleResponse,
|
||||||
|
FacilitatorSupportedResponse,
|
||||||
|
FacilitatorVerifyResponse,
|
||||||
|
RequestedPaymentPayload,
|
||||||
|
RequestedPaymentRequirements,
|
||||||
|
} from "./schemas.js";
|
||||||
|
import { stringify } from "./utils.js";
|
||||||
|
|
||||||
|
export type WaitUntil = "simulated" | "submitted" | "confirmed";
|
||||||
|
|
||||||
|
export type ThirdwebX402FacilitatorConfig = {
|
||||||
|
walletSecret: string;
|
||||||
|
walletAddress: string;
|
||||||
|
waitUntil?: WaitUntil;
|
||||||
|
baseUrl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* facilitator for the x402 payment protocol.
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type ThirdwebX402Facilitator = {
|
||||||
|
url: `${string}://${string}`;
|
||||||
|
address: string;
|
||||||
|
createAuthHeaders: () => Promise<{
|
||||||
|
verify: Record<string, string>;
|
||||||
|
settle: Record<string, string>;
|
||||||
|
supported: Record<string, string>;
|
||||||
|
list: Record<string, string>;
|
||||||
|
}>;
|
||||||
|
verify: (
|
||||||
|
payload: RequestedPaymentPayload,
|
||||||
|
paymentRequirements: RequestedPaymentRequirements,
|
||||||
|
) => Promise<FacilitatorVerifyResponse>;
|
||||||
|
settle: (
|
||||||
|
payload: RequestedPaymentPayload,
|
||||||
|
paymentRequirements: RequestedPaymentRequirements,
|
||||||
|
waitUntil?: WaitUntil,
|
||||||
|
) => Promise<FacilitatorSettleResponse>;
|
||||||
|
supported: (filters?: {
|
||||||
|
chainId: number;
|
||||||
|
tokenAddress?: string;
|
||||||
|
}) => Promise<FacilitatorSupportedResponse>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_BASE_URL = "https://nexus-api.thirdweb.com";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a facilitator for the x402 payment protocol.
|
||||||
|
* You can use this with `settlePayment` or with any x402 middleware to enable settling transactions with your thirdweb server wallet.
|
||||||
|
*
|
||||||
|
* @param config - The configuration for the facilitator
|
||||||
|
* @returns a x402 compatible FacilitatorConfig
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* import { createFacilitator } from "@thirdweb-dev/nexus";
|
||||||
|
* import { paymentMiddleware } from 'x402-hono'
|
||||||
|
*
|
||||||
|
* const facilitator = createFacilitator({
|
||||||
|
* walletSecret: <your-wallet-secret>,
|
||||||
|
* walletAddress: <your-wallet-address>,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // add the facilitator to any x402 payment middleware
|
||||||
|
* const middleware = paymentMiddleware(
|
||||||
|
* facilitator.address,
|
||||||
|
* {
|
||||||
|
* "/api/paywall": {
|
||||||
|
* price: "$0.01",
|
||||||
|
* network: "base-sepolia",
|
||||||
|
* config: {
|
||||||
|
* description: "Access to paid content",
|
||||||
|
* },
|
||||||
|
* },
|
||||||
|
* },
|
||||||
|
* facilitator,
|
||||||
|
* );
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* #### Configuration Options
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* const thirdwebX402Facilitator = createFacilitator({
|
||||||
|
* walletSecret: <your-wallet-secret>,
|
||||||
|
* walletAddress: <your-wallet-address>,
|
||||||
|
* // Optional: Wait behavior for settlements
|
||||||
|
* // - "simulated": Only simulate the transaction (fastest)
|
||||||
|
* // - "submitted": Wait until transaction is submitted
|
||||||
|
* // - "confirmed": Wait for full on-chain confirmation (slowest, default)
|
||||||
|
* waitUntil: "confirmed",
|
||||||
|
* });
|
||||||
|
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
export function createFacilitator(
|
||||||
|
config: ThirdwebX402FacilitatorConfig,
|
||||||
|
): ThirdwebX402Facilitator {
|
||||||
|
if (!config.walletSecret) {
|
||||||
|
throw new Error("Wallet secret is required for the x402 facilitator");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!config.walletAddress) {
|
||||||
|
throw new Error("Wallet address is required for the x402 facilitator");
|
||||||
|
}
|
||||||
|
|
||||||
|
const BASE_URL = config.baseUrl ?? DEFAULT_BASE_URL;
|
||||||
|
|
||||||
|
const AUTH_HEADERS = {
|
||||||
|
verify: {
|
||||||
|
authorization: `Bearer ${config.walletSecret}`,
|
||||||
|
},
|
||||||
|
settle: {
|
||||||
|
authorization: `Bearer ${config.walletSecret}`,
|
||||||
|
},
|
||||||
|
supported: {
|
||||||
|
authorization: `Bearer ${config.walletSecret}`,
|
||||||
|
},
|
||||||
|
list: {
|
||||||
|
authorization: `Bearer ${config.walletSecret}`,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
return {
|
||||||
|
url: BASE_URL as `${string}://${string}`,
|
||||||
|
address: config.walletAddress,
|
||||||
|
createAuthHeaders: async () => AUTH_HEADERS,
|
||||||
|
/**
|
||||||
|
* Verifies a payment payload with the facilitator service
|
||||||
|
*
|
||||||
|
* @param payload - The payment payload to verify
|
||||||
|
* @param paymentRequirements - The payment requirements to verify against
|
||||||
|
* @returns A promise that resolves to the verification response
|
||||||
|
*/
|
||||||
|
async verify(
|
||||||
|
payload: RequestedPaymentPayload,
|
||||||
|
paymentRequirements: RequestedPaymentRequirements,
|
||||||
|
): Promise<FacilitatorVerifyResponse> {
|
||||||
|
let headers = { "Content-Type": "application/json" };
|
||||||
|
|
||||||
|
headers = { ...headers, ...AUTH_HEADERS.verify };
|
||||||
|
|
||||||
|
const res = await fetch(new URL("/verify", BASE_URL), {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: stringify({
|
||||||
|
x402Version: payload.x402Version,
|
||||||
|
paymentPayload: payload,
|
||||||
|
paymentRequirements: paymentRequirements,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status !== 200) {
|
||||||
|
const text = `${res.statusText} ${await res.text()}`;
|
||||||
|
throw new Error(`Failed to verify payment: ${res.status} ${text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
return data as VerifyResponse;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settles a payment with the facilitator service
|
||||||
|
*
|
||||||
|
* @param payload - The payment payload to settle
|
||||||
|
* @param paymentRequirements - The payment requirements for the settlement
|
||||||
|
* @returns A promise that resolves to the settlement response
|
||||||
|
*/
|
||||||
|
async settle(
|
||||||
|
payload: RequestedPaymentPayload,
|
||||||
|
paymentRequirements: RequestedPaymentRequirements,
|
||||||
|
waitUntil?: WaitUntil,
|
||||||
|
): Promise<FacilitatorSettleResponse> {
|
||||||
|
let headers = { "Content-Type": "application/json" };
|
||||||
|
headers = { ...headers, ...AUTH_HEADERS.settle };
|
||||||
|
const waitUntilParam = waitUntil || config.waitUntil;
|
||||||
|
|
||||||
|
const res = await fetch(new URL("/settle", BASE_URL), {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: stringify({
|
||||||
|
x402Version: payload.x402Version,
|
||||||
|
paymentPayload: payload,
|
||||||
|
paymentRequirements: paymentRequirements,
|
||||||
|
...(waitUntilParam ? { waitUntil: waitUntilParam } : {}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (res.status !== 200) {
|
||||||
|
const text = `${res.statusText} ${await res.text()}`;
|
||||||
|
throw new Error(`Failed to settle payment: ${res.status} ${text}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
return data as FacilitatorSettleResponse;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the supported payment kinds from the facilitator service.
|
||||||
|
*
|
||||||
|
* @returns A promise that resolves to the supported payment kinds
|
||||||
|
*/
|
||||||
|
async supported(filters?: {
|
||||||
|
chainId: number;
|
||||||
|
tokenAddress?: string;
|
||||||
|
}): Promise<FacilitatorSupportedResponse> {
|
||||||
|
const headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...AUTH_HEADERS.supported,
|
||||||
|
};
|
||||||
|
const supportedUrl = new URL("/supported", BASE_URL);
|
||||||
|
if (filters?.chainId) {
|
||||||
|
supportedUrl.searchParams.set("chainId", filters.chainId.toString());
|
||||||
|
}
|
||||||
|
if (filters?.tokenAddress) {
|
||||||
|
supportedUrl.searchParams.set("tokenAddress", filters.tokenAddress);
|
||||||
|
}
|
||||||
|
const res = await fetch(supportedUrl, { headers });
|
||||||
|
|
||||||
|
if (res.status !== 200) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to get supported payment kinds: ${res.statusText}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await res.json();
|
||||||
|
return data as FacilitatorSupportedResponse;
|
||||||
|
},
|
||||||
|
} as const satisfies ThirdwebX402Facilitator;
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import {
|
||||||
|
EvmNetworkToChainId,
|
||||||
|
type Network,
|
||||||
|
PaymentPayloadSchema,
|
||||||
|
PaymentRequirementsSchema,
|
||||||
|
SettleResponseSchema,
|
||||||
|
SupportedPaymentKindsResponseSchema,
|
||||||
|
VerifyResponseSchema,
|
||||||
|
} from "x402/types";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const FacilitatorNetworkSchema = z.string();
|
||||||
|
|
||||||
|
export type FacilitatorNetwork = z.infer<typeof FacilitatorNetworkSchema>;
|
||||||
|
|
||||||
|
export const RequestedPaymentPayloadSchema = PaymentPayloadSchema.extend({
|
||||||
|
network: FacilitatorNetworkSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type RequestedPaymentPayload = z.infer<
|
||||||
|
typeof RequestedPaymentPayloadSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
const RequestedPaymentRequirementsSchema = PaymentRequirementsSchema.extend({
|
||||||
|
network: FacilitatorNetworkSchema,
|
||||||
|
});
|
||||||
|
|
||||||
|
export type RequestedPaymentRequirements = z.infer<
|
||||||
|
typeof RequestedPaymentRequirementsSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
const FacilitatorSettleResponseSchema = SettleResponseSchema.extend({
|
||||||
|
network: FacilitatorNetworkSchema,
|
||||||
|
errorMessage: z.string().optional(),
|
||||||
|
});
|
||||||
|
export type FacilitatorSettleResponse = z.infer<
|
||||||
|
typeof FacilitatorSettleResponseSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
const FacilitatorVerifyResponseSchema = VerifyResponseSchema.extend({
|
||||||
|
errorMessage: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type FacilitatorVerifyResponse = z.infer<
|
||||||
|
typeof FacilitatorVerifyResponseSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
export const SupportedSignatureTypeSchema = z.enum([
|
||||||
|
"TransferWithAuthorization",
|
||||||
|
"Permit",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const FacilitatorSupportedAssetSchema = z.object({
|
||||||
|
address: z.string(),
|
||||||
|
decimals: z.number(),
|
||||||
|
eip712: z.object({
|
||||||
|
name: z.string(),
|
||||||
|
version: z.string(),
|
||||||
|
primaryType: SupportedSignatureTypeSchema,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const FacilitatorSupportedResponseSchema =
|
||||||
|
SupportedPaymentKindsResponseSchema.extend({
|
||||||
|
kinds: z.array(
|
||||||
|
z.object({
|
||||||
|
x402Version: z.literal(1),
|
||||||
|
scheme: z.literal("exact"),
|
||||||
|
network: FacilitatorNetworkSchema,
|
||||||
|
extra: z
|
||||||
|
.object({
|
||||||
|
defaultAsset: FacilitatorSupportedAssetSchema.optional(),
|
||||||
|
supportedAssets: z
|
||||||
|
.array(FacilitatorSupportedAssetSchema)
|
||||||
|
.optional(),
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}).describe("Supported payment kinds for this facilitator");
|
||||||
|
|
||||||
|
export type FacilitatorSupportedResponse = z.infer<
|
||||||
|
typeof FacilitatorSupportedResponseSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function networkToChainId(network: string): number {
|
||||||
|
if (network.startsWith("eip155:")) {
|
||||||
|
const chainId = parseInt(network.split(":")[1] ?? "0");
|
||||||
|
if (!Number.isNaN(chainId) && chainId > 0) {
|
||||||
|
return chainId;
|
||||||
|
} else {
|
||||||
|
throw new Error(`Invalid network: ${network}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// attempt to parse it as just an integer
|
||||||
|
const maybeChainId = parseInt(network);
|
||||||
|
if (!Number.isNaN(maybeChainId) && maybeChainId > 0) {
|
||||||
|
return maybeChainId;
|
||||||
|
}
|
||||||
|
const mappedChainId = EvmNetworkToChainId.get(network as Network);
|
||||||
|
if (!mappedChainId) {
|
||||||
|
throw new Error(`Invalid network: ${network}`);
|
||||||
|
}
|
||||||
|
// TODO (402): support solana networks
|
||||||
|
if (mappedChainId === 101 || mappedChainId === 103) {
|
||||||
|
throw new Error("Solana networks not supported yet.");
|
||||||
|
}
|
||||||
|
return mappedChainId;
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import { decodePaymentRequest } from "./common.js";
|
||||||
|
import { safeBase64Encode } from "./encode.js";
|
||||||
|
import {
|
||||||
|
type SettlePaymentArgs,
|
||||||
|
type SettlePaymentResult,
|
||||||
|
x402Version,
|
||||||
|
} from "./types.js";
|
||||||
|
import { stringify } from "./utils.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies and processes X402 payments for protected resources.
|
||||||
|
*
|
||||||
|
* This function implements the X402 payment protocol, verifying payment proofs
|
||||||
|
* and settling payments through a facilitator service. It handles the complete
|
||||||
|
* payment flow from validation to settlement.
|
||||||
|
*
|
||||||
|
* @param args - Configuration object containing payment verification parameters
|
||||||
|
* @returns A promise that resolves to either a successful payment result (200) or payment required error (402)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
*
|
||||||
|
* ### Next.js API route example
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* // Usage in a Next.js API route
|
||||||
|
* import { settlePayment, createFacilitator } from "@thirdweb-dev/nexus";
|
||||||
|
* import { arbitrumSepolia } from "thirdweb/chains";
|
||||||
|
*
|
||||||
|
* const facilitator = createFacilitator({
|
||||||
|
* walletSecret: <your-wallet-secret>,
|
||||||
|
* walletAddress: <your-wallet-address>,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* export async function GET(request: Request) {
|
||||||
|
* const paymentData = request.headers.get("x-payment");
|
||||||
|
*
|
||||||
|
* // verify and process the payment
|
||||||
|
* const result = await settlePayment({
|
||||||
|
* resourceUrl: "https://api.example.com/premium-content",
|
||||||
|
* method: "GET",
|
||||||
|
* paymentData,
|
||||||
|
* network: arbitrumSepolia, // or any other chain
|
||||||
|
* price: "$0.10", // or { amount: "100000", asset: { address: "0x...", decimals: 6 } }
|
||||||
|
* facilitator,
|
||||||
|
* routeConfig: {
|
||||||
|
* description: "Access to premium API content",
|
||||||
|
* mimeType: "application/json",
|
||||||
|
* maxTimeoutSeconds: 300,
|
||||||
|
* },
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* if (result.status === 200) {
|
||||||
|
* // Payment verified and settled successfully
|
||||||
|
* return Response.json({ data: "premium content" });
|
||||||
|
* } else {
|
||||||
|
* // Payment required
|
||||||
|
* return Response.json(result.responseBody, {
|
||||||
|
* status: result.status,
|
||||||
|
* headers: result.responseHeaders,
|
||||||
|
* });
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* ### Express middleware example
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* // Usage in Express middleware
|
||||||
|
* import express from "express";
|
||||||
|
* import { settlePayment, createFacilitator } from "@thirdweb-dev/nexus";
|
||||||
|
* import { arbitrumSepolia } from "thirdweb/chains";
|
||||||
|
*
|
||||||
|
* const facilitator = createFacilitator({
|
||||||
|
* walletSecret: <your-wallet-secret>,
|
||||||
|
* walletAddress: <your-wallet-address>,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* const app = express();
|
||||||
|
*
|
||||||
|
* async function paymentMiddleware(req, res, next) {
|
||||||
|
* // verify and process the payment
|
||||||
|
* const result = await settlePayment({
|
||||||
|
* resourceUrl: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
|
||||||
|
* method: req.method,
|
||||||
|
* paymentData: req.headers["x-payment"],
|
||||||
|
* network: arbitrumSepolia, // or any other chain
|
||||||
|
* price: "$0.05",
|
||||||
|
* waitUntil: "submitted",
|
||||||
|
* facilitator,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* if (result.status === 200) {
|
||||||
|
* // Set payment receipt headers and continue
|
||||||
|
* Object.entries(result.responseHeaders).forEach(([key, value]) => {
|
||||||
|
* res.setHeader(key, value);
|
||||||
|
* });
|
||||||
|
* next();
|
||||||
|
* } else {
|
||||||
|
* // Return payment required response
|
||||||
|
* res.status(result.status)
|
||||||
|
* .set(result.responseHeaders)
|
||||||
|
* .json(result.responseBody);
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* app.get("/api/premium", paymentMiddleware, (req, res) => {
|
||||||
|
* res.json({ message: "This is premium content!" });
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
* @beta
|
||||||
|
*/
|
||||||
|
export async function settlePayment(
|
||||||
|
args: SettlePaymentArgs,
|
||||||
|
): Promise<SettlePaymentResult> {
|
||||||
|
const { routeConfig = {}, facilitator } = args;
|
||||||
|
const { errorMessages } = routeConfig;
|
||||||
|
|
||||||
|
const decodePaymentResult = await decodePaymentRequest(args);
|
||||||
|
|
||||||
|
if (decodePaymentResult.status !== 200) {
|
||||||
|
return decodePaymentResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { selectedPaymentRequirements, decodedPayment, paymentRequirements } =
|
||||||
|
decodePaymentResult;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const settlement = await facilitator.settle(
|
||||||
|
decodedPayment,
|
||||||
|
selectedPaymentRequirements,
|
||||||
|
args.waitUntil,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (settlement.success) {
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
paymentReceipt: settlement,
|
||||||
|
responseHeaders: {
|
||||||
|
"Access-Control-Expose-Headers": "X-PAYMENT-RESPONSE",
|
||||||
|
"X-PAYMENT-RESPONSE": safeBase64Encode(stringify(settlement)),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const error = settlement.errorReason || "Settlement error";
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error,
|
||||||
|
errorMessage:
|
||||||
|
errorMessages?.settlementFailed || settlement.errorMessage,
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error: "Settlement error",
|
||||||
|
errorMessage:
|
||||||
|
errorMessages?.settlementFailed ||
|
||||||
|
(error instanceof Error ? error.message : undefined),
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import type { Money, PaymentMiddlewareConfig } from "x402/types";
|
||||||
|
import type z from "zod";
|
||||||
|
import type { ThirdwebX402Facilitator, WaitUntil } from "./facilitator.js";
|
||||||
|
import type {
|
||||||
|
FacilitatorNetwork,
|
||||||
|
FacilitatorSettleResponse,
|
||||||
|
FacilitatorSupportedAssetSchema,
|
||||||
|
RequestedPaymentPayload,
|
||||||
|
RequestedPaymentRequirements,
|
||||||
|
SupportedSignatureTypeSchema,
|
||||||
|
} from "./schemas.js";
|
||||||
|
|
||||||
|
export const x402Version = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration object for verifying or processing X402 payments.
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type PaymentArgs = {
|
||||||
|
/** The URL of the resource being protected by the payment */
|
||||||
|
resourceUrl: string;
|
||||||
|
/** The HTTP method used to access the resource */
|
||||||
|
method: "GET" | "POST" | ({} & string);
|
||||||
|
/** The payment data/proof provided by the client, typically from the X-PAYMENT header */
|
||||||
|
paymentData?: string | null;
|
||||||
|
/** The blockchain network where the payment should be processed */
|
||||||
|
network: FacilitatorNetwork;
|
||||||
|
/** The price for accessing the resource - either a USD amount (e.g., "$0.10") or a specific token amount */
|
||||||
|
price: Money | ERC20TokenAmount;
|
||||||
|
/** The payment facilitator instance used to verify and settle payments */
|
||||||
|
facilitator: ThirdwebX402Facilitator;
|
||||||
|
/** Optional configuration for the payment middleware route */
|
||||||
|
routeConfig?: PaymentMiddlewareConfig;
|
||||||
|
/** Optional recipient address to receive the payment if different from your facilitator address */
|
||||||
|
payTo?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SettlePaymentArgs = PaymentArgs & {
|
||||||
|
waitUntil?: WaitUntil;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PaymentRequiredResult = {
|
||||||
|
/** HTTP 402 - Payment Required, verification or processing failed or payment missing */
|
||||||
|
status: 402;
|
||||||
|
/** The error response body containing payment requirements */
|
||||||
|
responseBody: {
|
||||||
|
/** The X402 protocol version */
|
||||||
|
x402Version: number;
|
||||||
|
/** error code */
|
||||||
|
error: string;
|
||||||
|
/** Human-readable error message */
|
||||||
|
errorMessage?: string;
|
||||||
|
/** Array of acceptable payment methods and requirements */
|
||||||
|
accepts: RequestedPaymentRequirements[];
|
||||||
|
/** Optional payer address if verification partially succeeded */
|
||||||
|
payer?: string;
|
||||||
|
};
|
||||||
|
/** Response headers for the error response */
|
||||||
|
responseHeaders: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The result of a payment settlement operation.
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type SettlePaymentResult =
|
||||||
|
| {
|
||||||
|
/** HTTP 200 - Payment was successfully processed */
|
||||||
|
status: 200;
|
||||||
|
/** Response headers including payment receipt information */
|
||||||
|
responseHeaders: Record<string, string>;
|
||||||
|
/** The payment receipt from the payment facilitator */
|
||||||
|
paymentReceipt: FacilitatorSettleResponse;
|
||||||
|
}
|
||||||
|
| PaymentRequiredResult;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The result of a payment verification operation.
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
*/
|
||||||
|
export type VerifyPaymentResult =
|
||||||
|
| {
|
||||||
|
/** HTTP 200 - Payment was successfully verified */
|
||||||
|
status: 200;
|
||||||
|
decodedPayment: RequestedPaymentPayload;
|
||||||
|
selectedPaymentRequirements: RequestedPaymentRequirements;
|
||||||
|
}
|
||||||
|
| PaymentRequiredResult;
|
||||||
|
|
||||||
|
export type SupportedSignatureType = z.infer<
|
||||||
|
typeof SupportedSignatureTypeSchema
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type ERC20TokenAmount = {
|
||||||
|
amount: string;
|
||||||
|
asset: {
|
||||||
|
address: `0x${string}`;
|
||||||
|
decimals?: number;
|
||||||
|
eip712?: {
|
||||||
|
name: string;
|
||||||
|
version: string;
|
||||||
|
primaryType: SupportedSignatureType;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DefaultAsset = z.infer<typeof FacilitatorSupportedAssetSchema>;
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/**
|
||||||
|
* Stringify a JSON object and convert all bigint values to string
|
||||||
|
*
|
||||||
|
* If you are getting this error: "Exception: Do not know how to serialize a BigInt",
|
||||||
|
* you probably can use this function to parse the data.
|
||||||
|
* Because bigint is not an accepted value of the JSON format.
|
||||||
|
*
|
||||||
|
* @returns An object with all bigint values converted to string
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* import { stringify } from "thirdweb/utils";
|
||||||
|
* const obj = { tokenId: 0n };
|
||||||
|
* const str = stringify(obj); // "{"tokenId":"0"}"
|
||||||
|
* ```
|
||||||
|
* @utils
|
||||||
|
*/
|
||||||
|
export function stringify(
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: JSON.stringify signature
|
||||||
|
value: any,
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: JSON.stringify signature
|
||||||
|
replacer?: ((this: any, key: string, value: any) => any) | null,
|
||||||
|
space?: string | number,
|
||||||
|
) {
|
||||||
|
const res = JSON.stringify(
|
||||||
|
value,
|
||||||
|
(key, value_) => {
|
||||||
|
const value__ = typeof value_ === "bigint" ? value_.toString() : value_;
|
||||||
|
return typeof replacer === "function" ? replacer(key, value__) : value__;
|
||||||
|
},
|
||||||
|
space,
|
||||||
|
);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts a string representation of a number with decimal places to a BigInt representation.
|
||||||
|
* @param tokens - The string representation of the number, including the integer and fraction parts.
|
||||||
|
* @param decimals - The number of decimal places to include in the BigInt representation.
|
||||||
|
* @returns The BigInt representation of the number.
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* import { toUnits } from "thirdweb/utils";
|
||||||
|
* toUnits('1', 18)
|
||||||
|
* // 1000000000000000000n
|
||||||
|
* ```
|
||||||
|
* @utils
|
||||||
|
*/
|
||||||
|
export function toUnits(tokens: string, decimals: number): bigint {
|
||||||
|
if (tokens.includes("e")) {
|
||||||
|
tokens = Number(tokens).toFixed(decimals);
|
||||||
|
}
|
||||||
|
|
||||||
|
let [integerPart, fractionPart = ""] = tokens.split(".") as [string, string];
|
||||||
|
const prefix = integerPart.startsWith("-") ? "-" : "";
|
||||||
|
if (prefix) {
|
||||||
|
integerPart = integerPart.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
fractionPart = fractionPart.padEnd(decimals, "0"); // Ensure fraction part is at least 'decimals' long.
|
||||||
|
|
||||||
|
if (decimals === 0) {
|
||||||
|
// Check if there's any fraction part that would necessitate rounding up the integer part.
|
||||||
|
if (fractionPart[0] && Number.parseInt(fractionPart[0]) >= 5) {
|
||||||
|
integerPart = (BigInt(integerPart) + 1n).toString();
|
||||||
|
}
|
||||||
|
fractionPart = ""; // No fraction part is needed when decimals === 0.
|
||||||
|
} else {
|
||||||
|
// When decimals > 0, handle potential rounding based on the digit right after the specified decimal places.
|
||||||
|
if (fractionPart.length > decimals) {
|
||||||
|
const roundingDigit = fractionPart[decimals];
|
||||||
|
if (roundingDigit && Number.parseInt(roundingDigit, 10) >= 5) {
|
||||||
|
// If rounding is needed, add 1 to the last included digit of the fraction part.
|
||||||
|
const roundedFraction =
|
||||||
|
BigInt(fractionPart.substring(0, decimals)) + 1n;
|
||||||
|
fractionPart = roundedFraction.toString().padStart(decimals, "0");
|
||||||
|
|
||||||
|
if (fractionPart.length > decimals) {
|
||||||
|
// If rounding the fraction results in a length increase (e.g., .999 -> 1.000), increment the integer part.
|
||||||
|
integerPart = (BigInt(integerPart) + 1n).toString();
|
||||||
|
// Adjust the fraction part if it's longer than the specified decimals due to rounding up.
|
||||||
|
fractionPart = fractionPart.substring(fractionPart.length - decimals);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If no rounding is necessary, just truncate the fraction part to the specified number of decimals.
|
||||||
|
fractionPart = fractionPart.substring(0, decimals);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If the fraction part is shorter than the specified decimals, it's already handled by padEnd() above.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combine the integer and fraction parts into the final BigInt representation.
|
||||||
|
return BigInt(`${prefix}${integerPart}${fractionPart}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { decodePaymentRequest } from "./common.js";
|
||||||
|
import {
|
||||||
|
type PaymentArgs,
|
||||||
|
type VerifyPaymentResult,
|
||||||
|
x402Version,
|
||||||
|
} from "./types.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies X402 payments for protected resources. This function only verifies the payment,
|
||||||
|
* you should use `settlePayment` to settle the payment.
|
||||||
|
*
|
||||||
|
* @param args - Configuration object containing payment verification parameters
|
||||||
|
* @returns A promise that resolves to either a successful verification result (200) or payment required error (402)
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* // Usage in a Next.js API route
|
||||||
|
* import { verifyPayment, createFacilitator } from "@thirdweb-dev/nexus";
|
||||||
|
* import { arbitrumSepolia } from "thirdweb/chains";
|
||||||
|
*
|
||||||
|
* const facilitator = createFacilitator({
|
||||||
|
* walletSecret: <your-wallet-secret>,
|
||||||
|
* walletAddress: <your-wallet-address>,
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* export async function GET(request: Request) {
|
||||||
|
* const paymentData = request.headers.get("x-payment");
|
||||||
|
*
|
||||||
|
* const paymentArgs = {
|
||||||
|
* resourceUrl: "https://api.example.com/premium-content",
|
||||||
|
* method: "GET",
|
||||||
|
* paymentData,
|
||||||
|
* network: arbitrumSepolia, // or any other chain
|
||||||
|
* price: "$0.10", // or { amount: "100000", asset: { address: "0x...", decimals: 6 } }
|
||||||
|
* facilitator,
|
||||||
|
* routeConfig: {
|
||||||
|
* description: "Access to premium API content",
|
||||||
|
* mimeType: "application/json",
|
||||||
|
* maxTimeoutSeconds: 300,
|
||||||
|
* },
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* // verify the payment
|
||||||
|
* const result = await verifyPayment(paymentArgs);
|
||||||
|
*
|
||||||
|
* if (result.status === 200) {
|
||||||
|
* // Payment verified, but not settled yet
|
||||||
|
* // you can do the work that requires payment first
|
||||||
|
* const result = await doSomething();
|
||||||
|
* // then settle the payment
|
||||||
|
* const settleResult = await settlePayment(paymentArgs);
|
||||||
|
*
|
||||||
|
* // then return the result
|
||||||
|
* return Response.json(result);
|
||||||
|
* } else {
|
||||||
|
* // verification failed, return payment required
|
||||||
|
* return Response.json(result.responseBody, {
|
||||||
|
* status: result.status,
|
||||||
|
* headers: result.responseHeaders,
|
||||||
|
* });
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @public
|
||||||
|
* @beta
|
||||||
|
*/
|
||||||
|
export async function verifyPayment(
|
||||||
|
args: PaymentArgs,
|
||||||
|
): Promise<VerifyPaymentResult> {
|
||||||
|
const { routeConfig = {}, facilitator } = args;
|
||||||
|
const { errorMessages } = routeConfig;
|
||||||
|
|
||||||
|
const decodePaymentResult = await decodePaymentRequest(args);
|
||||||
|
|
||||||
|
if (decodePaymentResult.status !== 200) {
|
||||||
|
return decodePaymentResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { selectedPaymentRequirements, decodedPayment, paymentRequirements } =
|
||||||
|
decodePaymentResult;
|
||||||
|
|
||||||
|
// Verify payment
|
||||||
|
try {
|
||||||
|
const verification = await facilitator.verify(
|
||||||
|
decodedPayment,
|
||||||
|
selectedPaymentRequirements,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (verification.isValid) {
|
||||||
|
return {
|
||||||
|
status: 200,
|
||||||
|
decodedPayment,
|
||||||
|
selectedPaymentRequirements,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const error = verification.invalidReason || "Verification failed";
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error: error,
|
||||||
|
errorMessage:
|
||||||
|
errorMessages?.verificationFailed || verification.errorMessage,
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
status: 402,
|
||||||
|
responseHeaders: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
responseBody: {
|
||||||
|
x402Version,
|
||||||
|
error: "Verification error",
|
||||||
|
errorMessage:
|
||||||
|
errorMessages?.verificationFailed ||
|
||||||
|
(error instanceof Error ? error.message : undefined),
|
||||||
|
accepts: paymentRequirements,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
// This tsconfig file contains the shared config for the build (tsconfig.build.json) and type checking (tsconfig.json) config.
|
||||||
|
"compilerOptions": {
|
||||||
|
// Incremental builds
|
||||||
|
// NOTE: Enabling incremental builds speeds up `tsc`. Keep in mind though that it does not reliably bust the cache when the `tsconfig.json` file changes.
|
||||||
|
"allowJs": false,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"checkJs": false,
|
||||||
|
|
||||||
|
// Interop constraints
|
||||||
|
"esModuleInterop": false,
|
||||||
|
"exactOptionalPropertyTypes": false,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"importHelpers": true,
|
||||||
|
// Incremental builds
|
||||||
|
// NOTE: Enabling incremental builds speeds up `tsc`. Keep in mind though that it does not reliably bust the cache when the `tsconfig.json` file changes.
|
||||||
|
"incremental": false,
|
||||||
|
|
||||||
|
// jsx for "/react" portion
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"lib": [
|
||||||
|
"ES2022", // By using ES2022 we get access to the `.cause` property on `Error` instances.
|
||||||
|
"DOM" // We are adding `DOM` here to get the `fetch`, etc. types. This should be removed once these types are available via DefinitelyTyped.
|
||||||
|
],
|
||||||
|
"module": "NodeNext",
|
||||||
|
|
||||||
|
// Language and environment
|
||||||
|
"moduleResolution": "NodeNext",
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noImplicitOverride": true,
|
||||||
|
"noImplicitReturns": true,
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
|
||||||
|
// Skip type checking for node modules
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
// Type checking
|
||||||
|
"strict": true,
|
||||||
|
"target": "ES2021",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"useUnknownInCatchVariables": true,
|
||||||
|
"verbatimModuleSyntax": true
|
||||||
|
},
|
||||||
|
// This tsconfig file contains the shared config for the build (tsconfig.build.json) and type checking (tsconfig.json) config.
|
||||||
|
"include": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"rootDir": "./src",
|
||||||
|
"sourceMap": true
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"src/**/*.test.ts",
|
||||||
|
"src/**/*.test.tsx",
|
||||||
|
"src/**/*.test-d.ts",
|
||||||
|
"src/**/*.bench.ts",
|
||||||
|
"src/**/*.macro.ts"
|
||||||
|
],
|
||||||
|
"extends": "./tsconfig.base.json",
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
// This configuration is used for local development and type checking.
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"outDir": "./dist",
|
||||||
|
"paths": {
|
||||||
|
"~test/*": ["./test/src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"exclude": [],
|
||||||
|
"extends": "./tsconfig.base.json",
|
||||||
|
"include": ["src", "test"]
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
"path": "./dist/esm/exports/thirdweb.js"
|
"path": "./dist/esm/exports/thirdweb.js"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"limit": "375 kB",
|
"limit": "380 kB",
|
||||||
"name": "thirdweb (cjs)",
|
"name": "thirdweb (cjs)",
|
||||||
"path": "./dist/cjs/exports/thirdweb.js"
|
"path": "./dist/cjs/exports/thirdweb.js"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,89 @@
|
|||||||
# thirdweb
|
# thirdweb
|
||||||
|
|
||||||
|
## 5.111.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8358](https://github.com/thirdweb-dev/js/pull/8358) [`1d54cff`](https://github.com/thirdweb-dev/js/commit/1d54cff7b442b8667ddd54bd783502c367ffc83e) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Add support for extraMetadata in x402 payment requirements
|
||||||
|
|
||||||
|
- [#8356](https://github.com/thirdweb-dev/js/pull/8356) [`fd04eef`](https://github.com/thirdweb-dev/js/commit/fd04eefea9a2a99eee3740d6746040c9f81cd43f) Thanks [@kumaryash90](https://github.com/kumaryash90)! - Update implementations, fix deployment
|
||||||
|
|
||||||
|
## 5.111.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8354](https://github.com/thirdweb-dev/js/pull/8354) [`ccdce49`](https://github.com/thirdweb-dev/js/commit/ccdce496e09bc9420b0e15854328651c01f36279) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix hiddenWallets prop not applying to all wallets screen
|
||||||
|
|
||||||
|
## 5.111.0
|
||||||
|
|
||||||
|
### Minor Changes
|
||||||
|
|
||||||
|
- [#8335](https://github.com/thirdweb-dev/js/pull/8335) [`c83f1c6`](https://github.com/thirdweb-dev/js/commit/c83f1c6f7a38c8a9f424798e6e726e1d037ed042) Thanks [@MananTank](https://github.com/MananTank)! - Remove `Bridge.routes` and `useBridgeRoutes`
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8345](https://github.com/thirdweb-dev/js/pull/8345) [`219fc69`](https://github.com/thirdweb-dev/js/commit/219fc69d72b1ca861bf0228589039788008ea0c0) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Update x402 flows to use remote /accepts endpoint
|
||||||
|
|
||||||
|
## 5.110.6
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8334](https://github.com/thirdweb-dev/js/pull/8334) [`6c318f8`](https://github.com/thirdweb-dev/js/commit/6c318f83d63aa8acce46da666e43638e410f799c) Thanks [@kumaryash90](https://github.com/kumaryash90)! - Update implementations
|
||||||
|
|
||||||
|
- [#8306](https://github.com/thirdweb-dev/js/pull/8306) [`759b93b`](https://github.com/thirdweb-dev/js/commit/759b93beff7ab10a3a2fa3b9dd25ca628efb9267) Thanks [@alecananian](https://github.com/alecananian)! - Moved `@storybook/react` package to be a dev dependency
|
||||||
|
|
||||||
|
- [#8332](https://github.com/thirdweb-dev/js/pull/8332) [`8e357b3`](https://github.com/thirdweb-dev/js/commit/8e357b3cb39dcc7a8595a83224098a9c44585389) Thanks [@jnsdls](https://github.com/jnsdls)! - expose some useful erc20 extensions
|
||||||
|
|
||||||
|
## 5.110.5
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8327](https://github.com/thirdweb-dev/js/pull/8327) [`c08fb13`](https://github.com/thirdweb-dev/js/commit/c08fb1356e77be9eeb0569905fcb2ab76a516dc3) Thanks [@MananTank](https://github.com/MananTank)! - Fix Safe wallet connection issues with WalletConnect
|
||||||
|
|
||||||
|
- [#8331](https://github.com/thirdweb-dev/js/pull/8331) [`bcbb3f5`](https://github.com/thirdweb-dev/js/commit/bcbb3f540a8eab2b02f9261b779bd2aad3464598) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Loosen network schema
|
||||||
|
|
||||||
|
- [#8325](https://github.com/thirdweb-dev/js/pull/8325) [`e0c8312`](https://github.com/thirdweb-dev/js/commit/e0c83121c201eb2dbdfa6a6b1bbb637f5ad2a21d) Thanks [@Yash094](https://github.com/Yash094)! - Add Arc testnet to chains package
|
||||||
|
|
||||||
|
## 5.110.4
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8310](https://github.com/thirdweb-dev/js/pull/8310) [`23cb3bd`](https://github.com/thirdweb-dev/js/commit/23cb3bd98c5390e64f45da5a222042cdc76bd7f4) Thanks [@MananTank](https://github.com/MananTank)! - Minor UI adjustments in CheckoutWidget
|
||||||
|
|
||||||
|
- [#8317](https://github.com/thirdweb-dev/js/pull/8317) [`abf0bba`](https://github.com/thirdweb-dev/js/commit/abf0bbaf359c8de5b0ed0d481e3791c4b7cbf92b) Thanks [@0xFirekeeper](https://github.com/0xFirekeeper)! - updates default x402 transfer with authorization timeout
|
||||||
|
|
||||||
|
- [#8319](https://github.com/thirdweb-dev/js/pull/8319) [`e0abf2b`](https://github.com/thirdweb-dev/js/commit/e0abf2b2738661fda3c69551d78231cfac4b0767) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Update x402 types
|
||||||
|
|
||||||
|
## 5.110.3
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8314](https://github.com/thirdweb-dev/js/pull/8314) [`bf46520`](https://github.com/thirdweb-dev/js/commit/bf46520a6b183c4beb873de5e63853cd3a23e685) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Enhance compatiblity with third party x402 libs
|
||||||
|
|
||||||
|
## 5.110.2
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8304](https://github.com/thirdweb-dev/js/pull/8304) [`3e9eb49`](https://github.com/thirdweb-dev/js/commit/3e9eb49787e00c09c3286aeb4ad73826a2856e65) Thanks [@MananTank](https://github.com/MananTank)! - Fix Select Token UI stuck in loading state if wallet is connected to a chain that is not supported by thirdweb Bridge in BuyWidget, SwapWidget and BridgeWidget
|
||||||
|
|
||||||
|
- [#8311](https://github.com/thirdweb-dev/js/pull/8311) [`bfd3be7`](https://github.com/thirdweb-dev/js/commit/bfd3be764c461c420f1f8520fe4d5d2cc83e42f7) Thanks [@jnsdls](https://github.com/jnsdls)! - filter out null-ish values from `ERC721.getNFTs()` and `ERC1155.getNFTs()` arrays
|
||||||
|
|
||||||
|
- [#8313](https://github.com/thirdweb-dev/js/pull/8313) [`ae3a122`](https://github.com/thirdweb-dev/js/commit/ae3a122cf1628f0fc997dd240d4b23842ac30f66) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix network comparison when using diff libraries
|
||||||
|
|
||||||
|
- [#8301](https://github.com/thirdweb-dev/js/pull/8301) [`d5d5939`](https://github.com/thirdweb-dev/js/commit/d5d593956e12b2a15393ed32d1d742bc43575bdd) Thanks [@kumaryash90](https://github.com/kumaryash90)! - create2 factory for neura testnet
|
||||||
|
|
||||||
|
- [#8305](https://github.com/thirdweb-dev/js/pull/8305) [`f757e60`](https://github.com/thirdweb-dev/js/commit/f757e6084648b6b6e5879abeab30954753a1020d) Thanks [@MananTank](https://github.com/MananTank)! - Update theme colors and minor UI tweaks in React Components
|
||||||
|
|
||||||
|
## 5.110.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- [#8299](https://github.com/thirdweb-dev/js/pull/8299) [`85fe949`](https://github.com/thirdweb-dev/js/commit/85fe9491cd6d2270847e9941ddb7df76aefd8b31) Thanks [@alecananian](https://github.com/alecananian)! - [React Native] Fixed Send Funds screen not allowing decimal amounts
|
||||||
|
|
||||||
|
- [#8296](https://github.com/thirdweb-dev/js/pull/8296) [`e978809`](https://github.com/thirdweb-dev/js/commit/e9788096d665afef7c2a933cea5d6f522fc67273) Thanks [@MananTank](https://github.com/MananTank)! - Do not require connecting wallet in `BuyWidget` if `receiverAddress` is set
|
||||||
|
|
||||||
|
- [#8298](https://github.com/thirdweb-dev/js/pull/8298) [`899051f`](https://github.com/thirdweb-dev/js/commit/899051f788b0c2521a022846782892a8c1405a66) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Add EIP-5792 support for EIP1193.toProvider()
|
||||||
|
|
||||||
## 5.110.0
|
## 5.110.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -21,7 +21,6 @@
|
|||||||
"@radix-ui/react-focus-scope": "1.1.7",
|
"@radix-ui/react-focus-scope": "1.1.7",
|
||||||
"@radix-ui/react-icons": "1.3.2",
|
"@radix-ui/react-icons": "1.3.2",
|
||||||
"@radix-ui/react-tooltip": "1.2.7",
|
"@radix-ui/react-tooltip": "1.2.7",
|
||||||
"@storybook/react": "9.0.15",
|
|
||||||
"@tanstack/react-query": "5.81.5",
|
"@tanstack/react-query": "5.81.5",
|
||||||
"@thirdweb-dev/engine": "workspace:*",
|
"@thirdweb-dev/engine": "workspace:*",
|
||||||
"@thirdweb-dev/insight": "workspace:*",
|
"@thirdweb-dev/insight": "workspace:*",
|
||||||
@@ -40,7 +39,7 @@
|
|||||||
"toml": "3.0.0",
|
"toml": "3.0.0",
|
||||||
"uqr": "0.1.2",
|
"uqr": "0.1.2",
|
||||||
"viem": "2.37.9",
|
"viem": "2.37.9",
|
||||||
"x402": "0.6.1",
|
"x402": "0.7.0",
|
||||||
"zod": "3.25.75"
|
"zod": "3.25.75"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -57,6 +56,7 @@
|
|||||||
"@storybook/addon-docs": "9.0.15",
|
"@storybook/addon-docs": "9.0.15",
|
||||||
"@storybook/addon-links": "9.0.15",
|
"@storybook/addon-links": "9.0.15",
|
||||||
"@storybook/addon-onboarding": "9.0.15",
|
"@storybook/addon-onboarding": "9.0.15",
|
||||||
|
"@storybook/react": "9.0.15",
|
||||||
"@storybook/react-vite": "9.0.15",
|
"@storybook/react-vite": "9.0.15",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.3.0",
|
"@testing-library/react": "^16.3.0",
|
||||||
@@ -430,5 +430,5 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"typings": "./dist/types/exports/thirdweb.d.ts",
|
"typings": "./dist/types/exports/thirdweb.d.ts",
|
||||||
"version": "5.110.0"
|
"version": "5.111.2"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,8 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
// should invoke the return fn from subscribe instead
|
// should invoke the return fn from subscribe instead
|
||||||
},
|
},
|
||||||
request: async (request) => {
|
request: async (request) => {
|
||||||
if (request.method === "eth_sendTransaction") {
|
switch (request.method) {
|
||||||
|
case "eth_sendTransaction": {
|
||||||
const account = wallet.getAccount();
|
const account = wallet.getAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error("Account not connected");
|
throw new Error("Account not connected");
|
||||||
@@ -79,7 +80,7 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
});
|
});
|
||||||
return result.transactionHash;
|
return result.transactionHash;
|
||||||
}
|
}
|
||||||
if (request.method === "eth_estimateGas") {
|
case "eth_estimateGas": {
|
||||||
const account = wallet.getAccount();
|
const account = wallet.getAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error("Account not connected");
|
throw new Error("Account not connected");
|
||||||
@@ -93,7 +94,7 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (request.method === "personal_sign") {
|
case "personal_sign": {
|
||||||
const account = wallet.getAccount();
|
const account = wallet.getAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error("Account not connected");
|
throw new Error("Account not connected");
|
||||||
@@ -104,7 +105,7 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (request.method === "eth_signTypedData_v4") {
|
case "eth_signTypedData_v4": {
|
||||||
const account = wallet.getAccount();
|
const account = wallet.getAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
throw new Error("Account not connected");
|
throw new Error("Account not connected");
|
||||||
@@ -112,14 +113,14 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
const data = JSON.parse(request.params[1]);
|
const data = JSON.parse(request.params[1]);
|
||||||
return account.signTypedData(data);
|
return account.signTypedData(data);
|
||||||
}
|
}
|
||||||
if (request.method === "eth_accounts") {
|
case "eth_accounts": {
|
||||||
const account = wallet.getAccount();
|
const account = wallet.getAccount();
|
||||||
if (!account) {
|
if (!account) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
return [account.address];
|
return [account.address];
|
||||||
}
|
}
|
||||||
if (request.method === "eth_requestAccounts") {
|
case "eth_requestAccounts": {
|
||||||
const connectedAccount = wallet.getAccount();
|
const connectedAccount = wallet.getAccount();
|
||||||
if (connectedAccount) {
|
if (connectedAccount) {
|
||||||
return [connectedAccount.address];
|
return [connectedAccount.address];
|
||||||
@@ -141,10 +142,8 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
}
|
}
|
||||||
return [account.address];
|
return [account.address];
|
||||||
}
|
}
|
||||||
if (
|
case "wallet_switchEthereumChain":
|
||||||
request.method === "wallet_switchEthereumChain" ||
|
case "wallet_addEthereumChain": {
|
||||||
request.method === "wallet_addEthereumChain"
|
|
||||||
) {
|
|
||||||
const data = request.params[0];
|
const data = request.params[0];
|
||||||
const chainIdHex = data.chainId;
|
const chainIdHex = data.chainId;
|
||||||
if (!chainIdHex) {
|
if (!chainIdHex) {
|
||||||
@@ -157,7 +156,46 @@ export function toProvider(options: ToEip1193ProviderOptions): EIP1193Provider {
|
|||||||
const chain = getCachedChain(chainId);
|
const chain = getCachedChain(chainId);
|
||||||
return wallet.switchChain(chain);
|
return wallet.switchChain(chain);
|
||||||
}
|
}
|
||||||
|
case "wallet_getCapabilities": {
|
||||||
|
const account = wallet.getAccount();
|
||||||
|
if (!account) {
|
||||||
|
throw new Error("Account not connected");
|
||||||
|
}
|
||||||
|
if (!account.getCapabilities) {
|
||||||
|
throw new Error("Wallet does not support EIP-5792");
|
||||||
|
}
|
||||||
|
return account.getCapabilities({ chainId: chain.id });
|
||||||
|
}
|
||||||
|
case "wallet_sendCalls": {
|
||||||
|
const account = wallet.getAccount();
|
||||||
|
if (!account) {
|
||||||
|
throw new Error("Account not connected");
|
||||||
|
}
|
||||||
|
if (!account.sendCalls) {
|
||||||
|
throw new Error("Wallet does not support EIP-5792");
|
||||||
|
}
|
||||||
|
return account.sendCalls({
|
||||||
|
...request.params[0],
|
||||||
|
chain: chain,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
case "wallet_getCallsStatus": {
|
||||||
|
const account = wallet.getAccount();
|
||||||
|
if (!account) {
|
||||||
|
throw new Error("Account not connected");
|
||||||
|
}
|
||||||
|
if (!account.getCallsStatus) {
|
||||||
|
throw new Error("Wallet does not support EIP-5792");
|
||||||
|
}
|
||||||
|
return account.getCallsStatus({
|
||||||
|
id: request.params[0],
|
||||||
|
chain: chain,
|
||||||
|
client: client,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
default:
|
||||||
return rpcClient(request);
|
return rpcClient(request);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user