Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
781a626461 | ||
|
|
f630912b9b | ||
|
|
163ab8afe1 | ||
|
|
62cfbb7441 | ||
|
|
d7104f69f4 | ||
|
|
23545cb999 | ||
|
|
f9283f389b | ||
|
|
9fbb29dc25 | ||
|
|
71a1e58eaf | ||
|
|
68b48f4faa | ||
|
|
1c660d4712 | ||
|
|
30b5c30ba0 | ||
|
|
86461f9a07 | ||
|
|
2ebba6139a | ||
|
|
f3bacc16cb | ||
|
|
968913d55b | ||
|
|
bd70db4a5d | ||
|
|
d9a138a90a | ||
|
|
777aed1e5f | ||
|
|
fbed4be959 | ||
|
|
5a26217a43 | ||
|
|
938c1e2f60 | ||
|
|
af9a73d930 | ||
|
|
34c5d24043 | ||
|
|
e612f16a85 | ||
|
|
4a30b9c89a | ||
|
|
ef9cf3409b | ||
|
|
fd20a6cabb | ||
|
|
9095041ea7 | ||
|
|
2dbb9e2de4 | ||
|
|
00b8adf3a2 | ||
|
|
ae3dfa36c3 | ||
|
|
eb603f8908 | ||
|
|
e11b0da20e | ||
|
|
4c51fe6a8f | ||
|
|
64034c0ddb | ||
|
|
90c1e576ff | ||
|
|
27d5a81c49 | ||
|
|
dbadc23e04 | ||
|
|
21d5d0b6af | ||
|
|
b2239c91c9 | ||
|
|
ca701a48c2 | ||
|
|
94aae902a1 | ||
|
|
0c7149eb44 | ||
|
|
ce9220ea00 | ||
|
|
99c2af5e25 | ||
|
|
7495f46222 | ||
|
|
b8afa98de6 | ||
|
|
496615feae |
@@ -2,7 +2,7 @@ name: Auto Author Assign
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, ready_for_review, draft]
|
||||
types: [opened, reopened, ready_for_review]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
@@ -10,6 +10,7 @@ module.exports = [
|
||||
"/wallets",
|
||||
"/account-abstraction",
|
||||
"/payments",
|
||||
"/payments/x402",
|
||||
"/auth",
|
||||
"/in-app-wallets",
|
||||
"/transactions",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"use server";
|
||||
|
||||
import { createVaultClient, listEoas } from "@thirdweb-dev/vault-sdk";
|
||||
import { NEXT_PUBLIC_THIRDWEB_VAULT_URL } from "@/constants/public-envs";
|
||||
import type { ProjectWalletSummary } from "@/lib/server/project-wallet";
|
||||
|
||||
interface VaultWalletListItem {
|
||||
id: string;
|
||||
address: string;
|
||||
metadata?: {
|
||||
label?: string;
|
||||
projectId?: string;
|
||||
teamId?: string;
|
||||
type?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export async function listProjectServerWallets(params: {
|
||||
managementAccessToken: string;
|
||||
projectId: string;
|
||||
pageSize?: number;
|
||||
}): Promise<ProjectWalletSummary[]> {
|
||||
const { managementAccessToken, projectId, pageSize = 100 } = params;
|
||||
|
||||
if (!managementAccessToken || !NEXT_PUBLIC_THIRDWEB_VAULT_URL) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const vaultClient = await createVaultClient({
|
||||
baseUrl: NEXT_PUBLIC_THIRDWEB_VAULT_URL,
|
||||
});
|
||||
|
||||
const response = await listEoas({
|
||||
client: vaultClient,
|
||||
request: {
|
||||
auth: {
|
||||
accessToken: managementAccessToken,
|
||||
},
|
||||
options: {
|
||||
page: 0,
|
||||
// @ts-expect-error - Vault SDK expects snake_case pagination fields
|
||||
page_size: pageSize,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.success || !response.data?.items) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const items = response.data.items as VaultWalletListItem[];
|
||||
|
||||
return items
|
||||
.filter((item) => {
|
||||
return (
|
||||
item.metadata?.projectId === projectId &&
|
||||
(!item.metadata?.type || item.metadata.type === "server-wallet")
|
||||
);
|
||||
})
|
||||
.map<ProjectWalletSummary>((item) => ({
|
||||
id: item.id,
|
||||
address: item.address,
|
||||
label: item.metadata?.label ?? undefined,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Failed to list project server wallets", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
"use server";
|
||||
|
||||
import { configure, sendTokens } from "@thirdweb-dev/api";
|
||||
import { THIRDWEB_API_HOST } from "@/constants/urls";
|
||||
|
||||
configure({
|
||||
override: {
|
||||
baseUrl: THIRDWEB_API_HOST,
|
||||
},
|
||||
});
|
||||
|
||||
export async function sendProjectWalletTokens(options: {
|
||||
walletAddress: string;
|
||||
recipientAddress: string;
|
||||
chainId: number;
|
||||
quantityWei: string;
|
||||
publishableKey: string;
|
||||
teamId: string;
|
||||
tokenAddress?: string;
|
||||
secretKey: string;
|
||||
vaultAccessToken?: string;
|
||||
}) {
|
||||
const {
|
||||
walletAddress,
|
||||
recipientAddress,
|
||||
chainId,
|
||||
quantityWei,
|
||||
publishableKey,
|
||||
teamId,
|
||||
tokenAddress,
|
||||
secretKey,
|
||||
vaultAccessToken,
|
||||
} = options;
|
||||
|
||||
if (!secretKey) {
|
||||
return {
|
||||
error: "A project secret key is required to send funds.",
|
||||
ok: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
const response = await sendTokens({
|
||||
body: {
|
||||
chainId,
|
||||
from: walletAddress,
|
||||
recipients: [
|
||||
{
|
||||
address: recipientAddress,
|
||||
quantity: quantityWei,
|
||||
},
|
||||
],
|
||||
...(tokenAddress ? { tokenAddress } : {}),
|
||||
},
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-client-id": publishableKey,
|
||||
"x-secret-key": secretKey,
|
||||
"x-team-id": teamId,
|
||||
...(vaultAccessToken ? { "x-vault-access-token": vaultAccessToken } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (response.error || !response.data) {
|
||||
return {
|
||||
error: response.error || "Failed to submit transfer request.",
|
||||
ok: false,
|
||||
} as const;
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
transactionIds: response.data.result?.transactionIds ?? [],
|
||||
} as const;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import "server-only";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import { cookies, headers } from "next/headers";
|
||||
import Stripe from "stripe";
|
||||
import type { Team } from "@/api/team/get-team";
|
||||
import {
|
||||
@@ -88,6 +88,9 @@ export async function fetchClientSecret(team: Team) {
|
||||
throw new Error("No customer ID found");
|
||||
}
|
||||
|
||||
// try to get the gclid cookie
|
||||
const gclid = (await cookies()).get("gclid")?.value;
|
||||
|
||||
// Create Checkout Sessions from body params.
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
ui_mode: "embedded",
|
||||
@@ -117,6 +120,8 @@ export async function fetchClientSecret(team: Team) {
|
||||
missing_payment_method: "cancel",
|
||||
},
|
||||
},
|
||||
// if gclid exists, set it as a metadata field so we can attribute the conversion later
|
||||
metadata: gclid ? { gclid } : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ export function reportContractDeployed(properties: {
|
||||
publisher: string | undefined;
|
||||
contractName: string | undefined;
|
||||
deploymentType?: "asset";
|
||||
is_testnet: boolean | undefined;
|
||||
}) {
|
||||
posthog.capture("contract deployed", properties);
|
||||
}
|
||||
@@ -40,6 +41,7 @@ export function reportContractDeployed(properties: {
|
||||
export function reportContractDeployFailed(properties: {
|
||||
errorMessage: string;
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
publisher: string | undefined;
|
||||
contractName: string | undefined;
|
||||
}) {
|
||||
@@ -171,9 +173,7 @@ export function reportOnboardingCompleted() {
|
||||
*
|
||||
*/
|
||||
export function reportFaucetUsed(properties: { chainId: number }) {
|
||||
posthog.capture("faucet used", {
|
||||
chainId: properties.chainId,
|
||||
});
|
||||
posthog.capture("faucet used", properties);
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
@@ -197,12 +197,7 @@ export function reportChainConfigurationAdded(properties: {
|
||||
decimals: number;
|
||||
};
|
||||
}) {
|
||||
posthog.capture("chain configuration added", {
|
||||
chainId: properties.chainId,
|
||||
chainName: properties.chainName,
|
||||
nativeCurrency: properties.nativeCurrency,
|
||||
rpcURLs: properties.rpcURLs,
|
||||
});
|
||||
posthog.capture("chain configuration added", properties);
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
@@ -227,12 +222,9 @@ export function reportAssetBuySuccessful(properties: {
|
||||
chainId: number;
|
||||
contractType: AssetContractType | undefined;
|
||||
assetType: "nft" | "coin";
|
||||
is_testnet: boolean | undefined;
|
||||
}) {
|
||||
posthog.capture("asset buy successful", {
|
||||
assetType: properties.assetType,
|
||||
chainId: properties.chainId,
|
||||
contractType: properties.contractType,
|
||||
});
|
||||
posthog.capture("asset buy successful", properties);
|
||||
}
|
||||
|
||||
type TokenSwapParams = {
|
||||
@@ -349,16 +341,12 @@ export function reportTokenSwapCancelled(properties: TokenSwapParams) {
|
||||
*/
|
||||
export function reportAssetBuyFailed(properties: {
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
contractType: AssetContractType | undefined;
|
||||
assetType: "nft" | "coin";
|
||||
error: string;
|
||||
}) {
|
||||
posthog.capture("asset buy failed", {
|
||||
assetType: properties.assetType,
|
||||
chainId: properties.chainId,
|
||||
contractType: properties.contractType,
|
||||
error: properties.error,
|
||||
});
|
||||
posthog.capture("asset buy failed", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -371,14 +359,11 @@ export function reportAssetBuyFailed(properties: {
|
||||
*/
|
||||
export function reportAssetBuyCancelled(properties: {
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
contractType: AssetContractType | undefined;
|
||||
assetType: "nft" | "coin";
|
||||
}) {
|
||||
posthog.capture("asset buy cancelled", {
|
||||
assetType: properties.assetType,
|
||||
chainId: properties.chainId,
|
||||
contractType: properties.contractType,
|
||||
});
|
||||
posthog.capture("asset buy cancelled", properties);
|
||||
}
|
||||
|
||||
// Assets Landing Page ----------------------------
|
||||
@@ -423,10 +408,7 @@ export function reportAssetCreationStepConfigured(
|
||||
step: "coin-info" | "token-distribution" | "launch-coin";
|
||||
},
|
||||
) {
|
||||
posthog.capture("asset creation step configured", {
|
||||
assetType: properties.assetType,
|
||||
step: properties.step,
|
||||
});
|
||||
posthog.capture("asset creation step configured", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -440,11 +422,10 @@ export function reportAssetCreationStepConfigured(
|
||||
export function reportAssetCreationSuccessful(properties: {
|
||||
assetType: "nft" | "coin";
|
||||
contractType: AssetContractType;
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
}) {
|
||||
posthog.capture("asset creation successful", {
|
||||
assetType: properties.assetType,
|
||||
contractType: properties.contractType,
|
||||
});
|
||||
posthog.capture("asset creation successful", properties);
|
||||
}
|
||||
|
||||
type CoinCreationStep =
|
||||
@@ -466,7 +447,12 @@ type CoinCreationStep =
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportAssetCreationFailed(
|
||||
properties: { contractType: AssetContractType; error: string } & (
|
||||
properties: {
|
||||
contractType: AssetContractType;
|
||||
error: string;
|
||||
is_testnet: boolean | undefined;
|
||||
chainId: number;
|
||||
} & (
|
||||
| {
|
||||
assetType: "nft";
|
||||
step:
|
||||
@@ -481,12 +467,7 @@ export function reportAssetCreationFailed(
|
||||
}
|
||||
),
|
||||
) {
|
||||
posthog.capture("asset creation failed", {
|
||||
assetType: properties.assetType,
|
||||
contractType: properties.contractType,
|
||||
error: properties.error,
|
||||
step: properties.step,
|
||||
});
|
||||
posthog.capture("asset creation failed", properties);
|
||||
}
|
||||
|
||||
type UpsellParams = {
|
||||
@@ -582,6 +563,7 @@ export function reportPaymentLinkBuyFailed(properties: {
|
||||
export function reportAssetPageview(properties: {
|
||||
assetType: "nft" | "coin";
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
}) {
|
||||
posthog.capture("asset pageview", properties);
|
||||
}
|
||||
@@ -593,7 +575,10 @@ export function reportAssetPageview(properties: {
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportChainPageview(properties: { chainId: number }) {
|
||||
export function reportChainPageview(properties: {
|
||||
chainId: number;
|
||||
is_testnet: boolean | undefined;
|
||||
}) {
|
||||
posthog.capture("chain pageview", properties);
|
||||
}
|
||||
|
||||
@@ -686,10 +671,7 @@ export function reportProductFeedback(properties: {
|
||||
feedback: string;
|
||||
source: "desktop" | "mobile";
|
||||
}) {
|
||||
posthog.capture("product feedback submitted", {
|
||||
feedback: properties.feedback,
|
||||
source: properties.source,
|
||||
});
|
||||
posthog.capture("product feedback submitted", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -448,6 +448,7 @@ type ActiveStatus = {
|
||||
pay: boolean;
|
||||
inAppWallet: boolean;
|
||||
ecosystemWallet: boolean;
|
||||
engineCloud: boolean;
|
||||
};
|
||||
|
||||
export const isProjectActive = unstable_cache(
|
||||
@@ -479,6 +480,7 @@ export const isProjectActive = unstable_cache(
|
||||
pay: false,
|
||||
rpc: false,
|
||||
sdk: false,
|
||||
engineCloud: false,
|
||||
storage: false,
|
||||
} as ActiveStatus;
|
||||
}
|
||||
@@ -488,7 +490,7 @@ export const isProjectActive = unstable_cache(
|
||||
},
|
||||
["isProjectActive"],
|
||||
{
|
||||
revalidate: 60 * 60, // 1 hour
|
||||
revalidate: 30, // 30 seconds
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ export function BuyAndSwapEmbed(props: {
|
||||
tokenAddress: string | undefined;
|
||||
buyAmount: string | undefined;
|
||||
pageType: PageType;
|
||||
isTestnet: boolean | undefined;
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
const [tab, setTab] = useState<"buy" | "swap">("swap");
|
||||
@@ -116,6 +117,7 @@ export function BuyAndSwapEmbed(props: {
|
||||
chainId: props.chain.id,
|
||||
error: errorMessage,
|
||||
contractType: undefined,
|
||||
is_testnet: props.isTestnet,
|
||||
});
|
||||
}
|
||||
}}
|
||||
@@ -141,6 +143,7 @@ export function BuyAndSwapEmbed(props: {
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: undefined,
|
||||
is_testnet: props.isTestnet,
|
||||
});
|
||||
}
|
||||
}}
|
||||
@@ -166,6 +169,7 @@ export function BuyAndSwapEmbed(props: {
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: undefined,
|
||||
is_testnet: props.isTestnet,
|
||||
});
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -46,7 +46,7 @@ export function AdvancedSearchInput(props: {
|
||||
value={searchType}
|
||||
onValueChange={(value) => setSearchType(value as SearchType)}
|
||||
>
|
||||
<SelectTrigger className="w-[140px] bg-card">
|
||||
<SelectTrigger className="w-[140px] bg-background rounded-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -61,7 +61,7 @@ export function AdvancedSearchInput(props: {
|
||||
<div className="flex flex-1">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
className="bg-card pl-9 border-r-0 rounded-r-none"
|
||||
className="bg-background pl-9 border-r-0 rounded-r-none rounded-l-full"
|
||||
placeholder={`Search by ${searchType}...`}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
@@ -86,7 +86,7 @@ export function AdvancedSearchInput(props: {
|
||||
onClick={handleSearch}
|
||||
variant="outline"
|
||||
disabled={!query.trim() || props.isLoading}
|
||||
className="rounded-l-none gap-2 bg-card disabled:opacity-100"
|
||||
className="rounded-l-none rounded-r-full gap-2 bg-background disabled:opacity-100"
|
||||
>
|
||||
{props.isLoading && <Spinner className="size-4" />}
|
||||
Search
|
||||
|
||||
+22
-9
@@ -2,7 +2,7 @@
|
||||
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { format } from "date-fns";
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||
import { ArrowLeftIcon, ArrowRightIcon, UserIcon } from "lucide-react";
|
||||
import Papa from "papaparse";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
@@ -264,11 +264,24 @@ export function InAppWalletUsersPageContent(
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Top section */}
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col md:flex-row lg:items-center justify-end gap-3">
|
||||
<div className="w-full max-w-lg">
|
||||
<div className="overflow-hidden rounded-xl border border-border bg-card">
|
||||
<div className="flex flex-col lg:flex-row lg:justify-between p-4 lg:px-6 py-5 lg:items-center gap-5">
|
||||
<div>
|
||||
<div className="flex mb-3">
|
||||
<div className="p-2 rounded-full bg-background border border-border">
|
||||
<UserIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<h2 className="font-semibold text-2xl tracking-tight">
|
||||
User Wallets
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
View and manage your project's users
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-start lg:items-end gap-2.5 border-t lg:border-t-0 pt-5 lg:pt-0 border-dashed">
|
||||
<div className="w-full lg:w-auto lg:min-w-[320px]">
|
||||
<AdvancedSearchInput
|
||||
onSearch={handleSearch}
|
||||
onClear={handleClearSearch}
|
||||
@@ -277,7 +290,7 @@ export function InAppWalletUsersPageContent(
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="gap-2 bg-card"
|
||||
className="gap-2 bg-background rounded-full"
|
||||
disabled={wallets.length === 0 || isPending}
|
||||
onClick={downloadCSV}
|
||||
variant="outline"
|
||||
@@ -298,11 +311,11 @@ export function InAppWalletUsersPageContent(
|
||||
data={wallets}
|
||||
isFetched={walletsQuery.isFetched}
|
||||
isPending={walletsQuery.isPending}
|
||||
tableContainerClassName="rounded-b-none"
|
||||
tableContainerClassName="rounded-none border-x-0 border-b-0"
|
||||
title="in-app wallets"
|
||||
/>
|
||||
|
||||
<div className="flex justify-center gap-3 rounded-b-lg border border-t-0 bg-card p-6">
|
||||
<div className="flex justify-center gap-3 border-t bg-card p-6">
|
||||
<Button
|
||||
className="gap-2 bg-background"
|
||||
disabled={activePage === 1 || walletsQuery.isPending}
|
||||
|
||||
@@ -5,6 +5,7 @@ import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLocalStorage } from "@/hooks/useLocalStorage";
|
||||
|
||||
// biome-ignore lint/correctness/noUnusedVariables: banner is toggled on-demand via API content changes
|
||||
function AnnouncementBannerUI(props: {
|
||||
href: string;
|
||||
label: string;
|
||||
|
||||
@@ -64,7 +64,7 @@ const CreateProjectDialog = (props: CreateProjectDialogProps) => {
|
||||
<CreateProjectDialogUI
|
||||
createProject={async (params) => {
|
||||
const res = await createProjectClient(props.teamId, params);
|
||||
await createVaultAccountAndAccessToken({
|
||||
const vaultTokens = await createVaultAccountAndAccessToken({
|
||||
project: res.project,
|
||||
projectSecretKey: res.secret,
|
||||
}).catch((error) => {
|
||||
@@ -74,6 +74,13 @@ const CreateProjectDialog = (props: CreateProjectDialogProps) => {
|
||||
);
|
||||
throw error;
|
||||
});
|
||||
|
||||
const managementAccessToken = vaultTokens.managementToken?.accessToken;
|
||||
|
||||
if (!managementAccessToken) {
|
||||
throw new Error("Missing management access token for project wallet");
|
||||
}
|
||||
|
||||
return {
|
||||
project: res.project,
|
||||
secret: res.secret,
|
||||
|
||||
@@ -379,12 +379,27 @@ export function useEngineTransactions(params: {
|
||||
page?: number;
|
||||
status?: EngineStatus;
|
||||
};
|
||||
id?: string;
|
||||
}) {
|
||||
const { instanceUrl, autoUpdate, authToken } = params;
|
||||
const { instanceUrl, autoUpdate, authToken, id } = params;
|
||||
|
||||
return useQuery({
|
||||
placeholderData: keepPreviousData,
|
||||
queryFn: async () => {
|
||||
if (id) {
|
||||
const res = await fetch(`${instanceUrl}transaction/status/${id}`, {
|
||||
headers: getEngineRequestHeaders(authToken),
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
const transaction = (json.result as Transaction) || {};
|
||||
return {
|
||||
transactions: [transaction],
|
||||
totalCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const url = new URL(`${instanceUrl}transaction/get-all`);
|
||||
if (params.queryParams) {
|
||||
for (const key in params.queryParams) {
|
||||
@@ -402,7 +417,6 @@ export function useEngineTransactions(params: {
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
return (json.result as TransactionResponse) || {};
|
||||
},
|
||||
queryKey: engineKeys.transactions(instanceUrl, params),
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
const PROJECT_WALLET_LABEL_SUFFIX = " Wallet";
|
||||
const PROJECT_WALLET_LABEL_MAX_LENGTH = 32;
|
||||
|
||||
/**
|
||||
* Builds the default label for a project's primary server wallet.
|
||||
* Ensures a stable naming convention so the wallet can be identified across flows.
|
||||
*/
|
||||
export function getProjectWalletLabel(projectName: string | undefined) {
|
||||
const baseName = projectName?.trim() || "Project";
|
||||
const maxBaseLength = Math.max(
|
||||
1,
|
||||
PROJECT_WALLET_LABEL_MAX_LENGTH - PROJECT_WALLET_LABEL_SUFFIX.length,
|
||||
);
|
||||
|
||||
const normalizedBase =
|
||||
baseName.length > maxBaseLength
|
||||
? baseName.slice(0, maxBaseLength).trimEnd()
|
||||
: baseName;
|
||||
|
||||
return `${normalizedBase}${PROJECT_WALLET_LABEL_SUFFIX}`;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import "server-only";
|
||||
|
||||
import { createVaultClient, listEoas } from "@thirdweb-dev/vault-sdk";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { NEXT_PUBLIC_THIRDWEB_VAULT_URL } from "@/constants/public-envs";
|
||||
import { getProjectWalletLabel } from "@/lib/project-wallet";
|
||||
|
||||
export type ProjectWalletSummary = {
|
||||
id: string;
|
||||
address: string;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
type VaultWalletListItem = {
|
||||
id: string;
|
||||
address: string;
|
||||
metadata?: {
|
||||
label?: string;
|
||||
projectId?: string;
|
||||
teamId?: string;
|
||||
type?: string;
|
||||
};
|
||||
};
|
||||
|
||||
export async function getProjectWallet(
|
||||
project: Project,
|
||||
): Promise<ProjectWalletSummary | undefined> {
|
||||
const engineCloudService = project.services.find(
|
||||
(service) => service.name === "engineCloud",
|
||||
);
|
||||
|
||||
const managementAccessToken =
|
||||
engineCloudService?.managementAccessToken || undefined;
|
||||
const projectWalletAddress = (
|
||||
engineCloudService as { projectWalletAddress?: string } | undefined
|
||||
)?.projectWalletAddress;
|
||||
|
||||
if (
|
||||
!managementAccessToken ||
|
||||
!NEXT_PUBLIC_THIRDWEB_VAULT_URL ||
|
||||
!projectWalletAddress
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const vaultClient = await createVaultClient({
|
||||
baseUrl: NEXT_PUBLIC_THIRDWEB_VAULT_URL,
|
||||
});
|
||||
|
||||
const response = await listEoas({
|
||||
client: vaultClient,
|
||||
request: {
|
||||
auth: {
|
||||
accessToken: managementAccessToken,
|
||||
},
|
||||
options: {
|
||||
page: 0,
|
||||
// @ts-expect-error - SDK expects snake_case for pagination arguments
|
||||
page_size: 100,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.success || !response.data) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const items = response.data.items as VaultWalletListItem[] | undefined;
|
||||
|
||||
if (!items?.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const defaultLabel = getProjectWalletLabel(project.name);
|
||||
|
||||
const serverWallets = items.filter(
|
||||
(item) => item.metadata?.projectId === project.id,
|
||||
);
|
||||
|
||||
const defaultWallet = serverWallets.find(
|
||||
(item) =>
|
||||
item.address.toLowerCase() === projectWalletAddress.toLowerCase(),
|
||||
);
|
||||
|
||||
if (!defaultWallet) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
id: defaultWallet.id,
|
||||
address: defaultWallet.address,
|
||||
label: defaultWallet.metadata?.label ?? defaultLabel,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to load project wallet", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+1
@@ -8,6 +8,7 @@ export function BuyFundsSection(props: { chain: ChainMetadata }) {
|
||||
return (
|
||||
<GridPatternEmbedContainer>
|
||||
<BuyAndSwapEmbed
|
||||
isTestnet={props.chain.testnet}
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
chain={defineDashboardChain(props.chain.chainId, props.chain)}
|
||||
buyAmount={undefined}
|
||||
|
||||
+2
-1
@@ -2,10 +2,11 @@
|
||||
import { reportChainPageview } from "@/analytics/report";
|
||||
import { useEffectOnce } from "@/hooks/useEffectOnce";
|
||||
|
||||
export function ChainPageView(props: { chainId: number }) {
|
||||
export function ChainPageView(props: { chainId: number; is_testnet: boolean }) {
|
||||
useEffectOnce(() => {
|
||||
reportChainPageview({
|
||||
chainId: props.chainId,
|
||||
is_testnet: props.is_testnet,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ export default async function ChainPageLayout(props: {
|
||||
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<ChainPageView chainId={chain.chainId} />
|
||||
<ChainPageView chainId={chain.chainId} is_testnet={chain.testnet} />
|
||||
<div className="border-border border-b bg-card">
|
||||
<TeamHeader />
|
||||
</div>
|
||||
|
||||
+2
@@ -5,11 +5,13 @@ import { useEffectOnce } from "@/hooks/useEffectOnce";
|
||||
export function AssetPageView(props: {
|
||||
assetType: "nft" | "coin";
|
||||
chainId: number;
|
||||
is_testnet: boolean;
|
||||
}) {
|
||||
useEffectOnce(() => {
|
||||
reportAssetPageview({
|
||||
assetType: props.assetType,
|
||||
chainId: props.chainId,
|
||||
is_testnet: props.is_testnet,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+3
@@ -122,6 +122,7 @@ export function TokenDropClaim(props: {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC20",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
toast.error("Failed to approve spending", {
|
||||
@@ -160,6 +161,7 @@ export function TokenDropClaim(props: {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC20",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
toast.error("Failed to buy tokens", {
|
||||
@@ -172,6 +174,7 @@ export function TokenDropClaim(props: {
|
||||
assetType: "coin",
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC20",
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
setStepsUI({
|
||||
|
||||
+6
-1
@@ -76,7 +76,11 @@ export async function ERC20PublicPage(props: {
|
||||
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<AssetPageView assetType="coin" chainId={props.chainMetadata.chainId} />
|
||||
<AssetPageView
|
||||
assetType="coin"
|
||||
chainId={props.chainMetadata.chainId}
|
||||
is_testnet={props.chainMetadata.testnet}
|
||||
/>
|
||||
<PageHeader containerClassName="max-w-7xl" />
|
||||
|
||||
<div className="border-b border-dashed">
|
||||
@@ -199,6 +203,7 @@ function BuyEmbed(props: {
|
||||
tokenAddress={props.clientContract.address}
|
||||
buyAmount={undefined}
|
||||
pageType="asset"
|
||||
isTestnet={props.chainMetadata.testnet}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
+5
-1
@@ -18,7 +18,11 @@ export function NFTPublicPageLayout(props: {
|
||||
}) {
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<AssetPageView assetType="nft" chainId={props.chainMetadata.chainId} />
|
||||
<AssetPageView
|
||||
assetType="nft"
|
||||
chainId={props.chainMetadata.chainId}
|
||||
is_testnet={props.chainMetadata.testnet}
|
||||
/>
|
||||
<PageHeader containerClassName="max-w-8xl" />
|
||||
<div className="border-b">
|
||||
<div className="container max-w-8xl">
|
||||
|
||||
+4
@@ -120,6 +120,7 @@ export function BuyEditionDrop(props: BuyEditionDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC1155",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
console.error(errorMessage);
|
||||
@@ -147,6 +148,7 @@ export function BuyEditionDrop(props: BuyEditionDropProps) {
|
||||
assetType: "nft",
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC1155",
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
props.onSuccess?.();
|
||||
@@ -163,6 +165,7 @@ export function BuyEditionDrop(props: BuyEditionDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC1155",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
return;
|
||||
@@ -180,6 +183,7 @@ export function BuyEditionDrop(props: BuyEditionDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC1155",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+4
@@ -77,6 +77,7 @@ export function BuyNFTDrop(props: BuyNFTDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC721",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
return;
|
||||
@@ -103,6 +104,7 @@ export function BuyNFTDrop(props: BuyNFTDropProps) {
|
||||
assetType: "nft",
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC721",
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
props.onSuccess?.();
|
||||
@@ -115,6 +117,7 @@ export function BuyNFTDrop(props: BuyNFTDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC721",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
|
||||
return;
|
||||
@@ -131,6 +134,7 @@ export function BuyNFTDrop(props: BuyNFTDropProps) {
|
||||
chainId: props.contract.chain.id,
|
||||
contractType: "DropERC721",
|
||||
error: errorMessage,
|
||||
is_testnet: props.chainMetadata.testnet,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
+17
-5
@@ -190,25 +190,37 @@ export async function generateContractLayoutMetadata(params: {
|
||||
.replace("Testnet", "")
|
||||
.trim();
|
||||
|
||||
const title = `${contractDisplayName} | ${cleanedChainName} Smart Contract`;
|
||||
let title = `${contractDisplayName} | ${cleanedChainName} Smart Contract`;
|
||||
let description = "";
|
||||
|
||||
if (isERC721 || isERC1155) {
|
||||
description = `View tokens, source code, transactions, balances, and analytics for the ${contractDisplayName} smart contract on ${cleanedChainName}.`;
|
||||
} else if (isERC20) {
|
||||
description = `View ERC20 tokens, transactions, balances, source code, and analytics for the ${contractDisplayName} smart contract on ${cleanedChainName}`;
|
||||
title = `${contractMetadata.name} (${contractMetadata.symbol}) on ${cleanedChainName} | Buy, Swap, Bridge & Price`;
|
||||
description = `Buy, swap & bridge ${contractMetadata.name} (${contractMetadata.symbol}) on ${cleanedChainName} with thirdweb Bridge. View contract address, holders, analytics, transactions and live price.`;
|
||||
} else {
|
||||
description = `View tokens, transactions, balances, source code, and analytics for the ${contractDisplayName} smart contract on ${cleanedChainName}`;
|
||||
description = `View tokens, transactions, balances, source code, and analytics for the ${contractMetadata.name} smart contract on ${cleanedChainName}`;
|
||||
}
|
||||
|
||||
return {
|
||||
description: description,
|
||||
title: title,
|
||||
openGraph: {
|
||||
description: description,
|
||||
title: title,
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
const fallbackTitle = `${shortenIfAddress(params.contractAddress)} | ${params.chainIdOrSlug}`;
|
||||
const fallbackDescription = `View tokens, transactions, balances, source code, and analytics for the smart contract on Chain ID ${params.chainIdOrSlug}`;
|
||||
|
||||
return {
|
||||
description: `View tokens, transactions, balances, source code, and analytics for the smart contract on Chain ID ${params.chainIdOrSlug}`,
|
||||
title: `${shortenIfAddress(params.contractAddress)} | ${params.chainIdOrSlug}`,
|
||||
description: fallbackDescription,
|
||||
title: fallbackTitle,
|
||||
openGraph: {
|
||||
description: fallbackDescription,
|
||||
title: fallbackTitle,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -50,6 +50,7 @@ import {
|
||||
} from "@/constants/addresses";
|
||||
import { LAST_USED_PROJECT_ID, LAST_USED_TEAM_ID } from "@/constants/cookie";
|
||||
import { ZERO_FEE_CHAINS } from "@/constants/fee-config";
|
||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||
import {
|
||||
useCustomFactoryAbi,
|
||||
useFunctionParamsFromABI,
|
||||
@@ -206,6 +207,8 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
|
||||
const activeAccount = useActiveAccount();
|
||||
const walletChain = useActiveWalletChain();
|
||||
const walletChainMetadata = useV5DashboardChain(walletChain?.id);
|
||||
|
||||
const { onError } = useTxNotifications(
|
||||
"Successfully deployed contract",
|
||||
"Failed to deploy contract",
|
||||
@@ -656,6 +659,7 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
chainId: walletChain.id,
|
||||
contractName: metadata.name,
|
||||
publisher: rewriteTwPublisher(metadata.publisher),
|
||||
is_testnet: walletChainMetadata?.testnet,
|
||||
});
|
||||
|
||||
deployStatusModal.nextStep();
|
||||
@@ -694,6 +698,7 @@ export const CustomContractForm: React.FC<CustomContractFormProps> = ({
|
||||
contractName: metadata.name,
|
||||
errorMessage: parsedError,
|
||||
publisher: rewriteTwPublisher(metadata.publisher),
|
||||
is_testnet: walletChain.testnet,
|
||||
});
|
||||
|
||||
deployStatusModal.close();
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { BringToFrontIcon } from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import { unstable_cache } from "next/cache";
|
||||
import Link from "next/link";
|
||||
import { Bridge } from "thirdweb";
|
||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||
import { PageHeader } from "./components/header";
|
||||
@@ -35,13 +34,10 @@ export default async function Page() {
|
||||
<h1 className="text-4xl font-bold tracking-tighter mb-1">
|
||||
Discover and swap any tokens on any chain, instantly
|
||||
</h1>
|
||||
<Link
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
href="https://thirdweb.com/monetize/bridge"
|
||||
target="_blank"
|
||||
>
|
||||
Powered by thirdweb bridge
|
||||
</Link>
|
||||
|
||||
<p className="text-muted-foreground">
|
||||
85+ chains, 3200+ tokens and 9+ million routes supported
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<TokenPage chains={chains} />
|
||||
|
||||
+11
-1
@@ -55,7 +55,7 @@ export function CreateProjectFormOnboarding(props: {
|
||||
<CreateProjectForm
|
||||
createProject={async (params) => {
|
||||
const res = await createProjectClient(props.teamId, params);
|
||||
await createVaultAccountAndAccessToken({
|
||||
const vaultTokens = await createVaultAccountAndAccessToken({
|
||||
project: res.project,
|
||||
projectSecretKey: res.secret,
|
||||
}).catch((error) => {
|
||||
@@ -65,6 +65,16 @@ export function CreateProjectFormOnboarding(props: {
|
||||
);
|
||||
throw error;
|
||||
});
|
||||
|
||||
const managementAccessToken =
|
||||
vaultTokens.managementToken?.accessToken;
|
||||
|
||||
if (!managementAccessToken) {
|
||||
throw new Error(
|
||||
"Missing management access token for project wallet",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
project: res.project,
|
||||
secret: res.secret,
|
||||
|
||||
+29
-22
@@ -25,6 +25,34 @@ import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { ThirdwebMiniLogo } from "../../../../../../../components/ThirdwebMiniLogo";
|
||||
import { searchParams } from "../search-params";
|
||||
|
||||
function getStatusBadge(invoice: Stripe.Invoice) {
|
||||
switch (invoice.status) {
|
||||
case "paid":
|
||||
return <Badge variant="success">Paid</Badge>;
|
||||
case "open":
|
||||
// we treat "uncollectible" as unpaid
|
||||
case "uncollectible": {
|
||||
// if the invoice has a due date, use that, otherwise use the effective at date (which is the date the invoice was created)
|
||||
const effectiveDueDate = invoice.due_date || invoice.effective_at;
|
||||
|
||||
// if the invoice due date is in the past, we want to display it as past due
|
||||
if (effectiveDueDate && effectiveDueDate * 1000 < Date.now()) {
|
||||
return <Badge variant="destructive">Past Due</Badge>;
|
||||
}
|
||||
return <Badge variant="outline">Open</Badge>;
|
||||
}
|
||||
case "void":
|
||||
return <Badge variant="secondary">Void</Badge>;
|
||||
|
||||
default:
|
||||
return <Badge variant="outline">Unknown</Badge>;
|
||||
}
|
||||
}
|
||||
|
||||
function isInvoicePayable(invoice: Stripe.Invoice) {
|
||||
return invoice.status === "open" || invoice.status === "uncollectible";
|
||||
}
|
||||
|
||||
export function BillingHistory(props: {
|
||||
teamSlug: string;
|
||||
invoices: Stripe.Invoice[];
|
||||
@@ -57,27 +85,6 @@ export function BillingHistory(props: {
|
||||
});
|
||||
};
|
||||
|
||||
const getStatusBadge = (invoice: Stripe.Invoice) => {
|
||||
switch (invoice.status) {
|
||||
case "paid":
|
||||
return <Badge variant="success">Paid</Badge>;
|
||||
case "open":
|
||||
// we treate "uncollectible" as unpaid
|
||||
case "uncollectible": {
|
||||
// if the invoice due date is in the past, we want to display it as past due
|
||||
if (invoice.due_date && invoice.due_date * 1000 < Date.now()) {
|
||||
return <Badge variant="destructive">Past Due</Badge>;
|
||||
}
|
||||
return <Badge variant="outline">Open</Badge>;
|
||||
}
|
||||
case "void":
|
||||
return <Badge variant="secondary">Void</Badge>;
|
||||
|
||||
default:
|
||||
return <Badge variant="outline">Unknown</Badge>;
|
||||
}
|
||||
};
|
||||
|
||||
if (props.invoices.length === 0) {
|
||||
if (props.status === "open") {
|
||||
return (
|
||||
@@ -126,7 +133,7 @@ export function BillingHistory(props: {
|
||||
<TableCell>{getStatusBadge(invoice)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end space-x-2">
|
||||
{invoice.status === "open" && (
|
||||
{isInvoicePayable(invoice) && (
|
||||
<>
|
||||
{/* always show the crypto payment button */}
|
||||
<ToolTipLabel
|
||||
|
||||
+1
-1
@@ -552,7 +552,7 @@ export function AccountAbstractionSettingsPage(
|
||||
you build your own rules.{" "}
|
||||
<UnderlineLink
|
||||
className="text-primary-500"
|
||||
href="https://portal.thirdweb.com/wallets/smart-wallet/sponsorship-rules#setting-up-a-server-verifier"
|
||||
href="https://portal.thirdweb.com/transactions/policies#server-verifier"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
|
||||
+3
-3
@@ -28,11 +28,11 @@ export function QuickStartSection(props: {
|
||||
icon={ArrowRightLeftIcon}
|
||||
setupTime={5}
|
||||
id="swap_tokens"
|
||||
features={["Swap any token", "Cross-chain swaps"]}
|
||||
features={["Swap any token", "Cross-chain swap"]}
|
||||
description="Swap tokens cross-chain with dedicated swapping endpoints."
|
||||
link={{
|
||||
href: `https://portal.thirdweb.com/payments/swap`,
|
||||
label: "Setup Swaps",
|
||||
href: `https://portal.thirdweb.com/bridge/swap`,
|
||||
label: "Setup Swap",
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
+8
-58
@@ -69,70 +69,20 @@ export default async function Page(props: {
|
||||
},
|
||||
},
|
||||
links: [
|
||||
// TODO - add docs when bridge docs are added in portal
|
||||
// {
|
||||
// type: "docs",
|
||||
// href: "https://portal.thirdweb.com/payments",
|
||||
// },
|
||||
{
|
||||
type: "docs",
|
||||
href: "https://portal.thirdweb.com/bridge",
|
||||
},
|
||||
{
|
||||
type: "playground",
|
||||
href: "https://playground.thirdweb.com/bridge/swap-widget",
|
||||
},
|
||||
{
|
||||
type: "api",
|
||||
href: "https://api.thirdweb.com/reference#tag/bridge",
|
||||
},
|
||||
],
|
||||
}}
|
||||
footer={{
|
||||
center: {
|
||||
links: [
|
||||
{
|
||||
href: "https://playground.thirdweb.com/payments/ui-components",
|
||||
label: "UI Component",
|
||||
},
|
||||
{
|
||||
href: "https://playground.thirdweb.com/connect/payments/fund-wallet",
|
||||
label: "Buy Crypto",
|
||||
},
|
||||
{
|
||||
href: "https://playground.thirdweb.com/connect/payments/commerce",
|
||||
label: "Checkout",
|
||||
},
|
||||
{
|
||||
href: "https://playground.thirdweb.com/connect/payments/transactions",
|
||||
label: "Transactions",
|
||||
},
|
||||
],
|
||||
title: "Demos",
|
||||
},
|
||||
left: {
|
||||
links: [
|
||||
{
|
||||
href: "https://portal.thirdweb.com/payments",
|
||||
label: "Overview",
|
||||
},
|
||||
{
|
||||
href: "https://portal.thirdweb.com/typescript/v5/convertCryptoToFiat",
|
||||
label: "TypeScript",
|
||||
},
|
||||
{
|
||||
href: "https://portal.thirdweb.com/react/v5/pay/fund-wallets",
|
||||
label: "React",
|
||||
},
|
||||
{
|
||||
href: "https://portal.thirdweb.com/dotnet/universal-bridge/quickstart",
|
||||
label: ".NET",
|
||||
},
|
||||
],
|
||||
title: "Documentation",
|
||||
},
|
||||
right: {
|
||||
links: [
|
||||
{
|
||||
href: "https://www.youtube.com/watch?v=aBu175-VsNY",
|
||||
label: "Implement cross-chain payments in any app",
|
||||
},
|
||||
],
|
||||
title: "Tutorials",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-12">
|
||||
<ResponsiveSearchParamsProvider value={searchParams}>
|
||||
|
||||
+1
@@ -31,5 +31,6 @@ export const Default: Story = {
|
||||
],
|
||||
},
|
||||
teamSlug: "bar",
|
||||
managementAccessToken: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
+93
-1
@@ -7,6 +7,7 @@ import {
|
||||
import Link from "next/link";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { AlertDialogFooter } from "@/components/ui/alert-dialog";
|
||||
import { CodeServer } from "@/components/ui/code/code.server";
|
||||
import { UnderlineLink } from "@/components/ui/UnderlineLink";
|
||||
import { DotNetIcon } from "@/icons/brand-icons/DotNetIcon";
|
||||
@@ -18,13 +19,34 @@ import { UnrealIcon } from "@/icons/brand-icons/UnrealIcon";
|
||||
import { ContractIcon } from "@/icons/ContractIcon";
|
||||
import { InsightIcon } from "@/icons/InsightIcon";
|
||||
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 CreateServerWallet from "../../transactions/server-wallets/components/create-server-wallet.client";
|
||||
import { ClientIDSection } from "./ClientIDSection";
|
||||
import { IntegrateAPIKeyCodeTabs } from "./IntegrateAPIKeyCodeTabs";
|
||||
import { ProjectWalletControls } from "./ProjectWalletControls.client";
|
||||
import { SecretKeySection } from "./SecretKeySection";
|
||||
|
||||
export function ProjectFTUX(props: { project: Project; teamSlug: string }) {
|
||||
export async function ProjectFTUX(props: {
|
||||
project: Project;
|
||||
teamSlug: string;
|
||||
wallet?: ProjectWalletSummary | undefined;
|
||||
managementAccessToken: string | undefined;
|
||||
}) {
|
||||
const projectWallet = props.wallet ?? (await getProjectWallet(props.project));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-10">
|
||||
<ProjectWalletSection
|
||||
project={props.project}
|
||||
teamSlug={props.teamSlug}
|
||||
wallet={projectWallet}
|
||||
managementAccessToken={props.managementAccessToken}
|
||||
/>
|
||||
<IntegrateAPIKeySection
|
||||
project={props.project}
|
||||
teamSlug={props.teamSlug}
|
||||
@@ -39,6 +61,76 @@ export function ProjectFTUX(props: { project: Project; teamSlug: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
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">
|
||||
Default managed server wallet for this project. 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>
|
||||
</>
|
||||
) : (
|
||||
<Alert variant="info">
|
||||
<CircleAlertIcon className="size-5" />
|
||||
<AlertTitle>No default project wallet set</AlertTitle>
|
||||
<AlertDescription>
|
||||
Set a default project wallet to use for dashboard and API
|
||||
integrations.
|
||||
</AlertDescription>
|
||||
<AlertDialogFooter className="flex justify-start sm:justify-start pt-4">
|
||||
<CreateServerWallet
|
||||
managementAccessToken={props.managementAccessToken}
|
||||
project={props.project}
|
||||
teamSlug={props.teamSlug}
|
||||
setAsProjectWallet={true}
|
||||
/>
|
||||
</AlertDialogFooter>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// Integrate API key section ------------------------------------------------------------
|
||||
|
||||
function IntegrateAPIKeySection({
|
||||
|
||||
+725
@@ -0,0 +1,725 @@
|
||||
"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 { Label } from "@/components/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Spinner } from "@/components/ui/Spinner";
|
||||
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("Default 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>
|
||||
) : (
|
||||
<RadioGroup
|
||||
className="space-y-3"
|
||||
onValueChange={(value) => setSelectedWalletId(value)}
|
||||
value={selectedWalletId}
|
||||
>
|
||||
{serverWallets.map((wallet) => {
|
||||
const isCurrent =
|
||||
wallet.address.toLowerCase() === currentWalletAddressLower;
|
||||
const isSelected = wallet.id === selectedWalletId;
|
||||
|
||||
return (
|
||||
<Label
|
||||
key={wallet.id}
|
||||
htmlFor={`project-wallet-${wallet.id}`}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 transition",
|
||||
isSelected && "border-primary ring-2 ring-primary/20",
|
||||
)}
|
||||
>
|
||||
<RadioGroupItem
|
||||
id={`project-wallet-${wallet.id}`}
|
||||
value={wallet.id}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-foreground">
|
||||
{wallet.label ?? "Unnamed server wallet"}
|
||||
</span>
|
||||
{isCurrent && (
|
||||
<Badge variant="success" className="text-xs">
|
||||
current
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground break-all">
|
||||
{wallet.address}
|
||||
</span>
|
||||
</div>
|
||||
</Label>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
)}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
+13
@@ -1,3 +1,4 @@
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
@@ -110,6 +111,7 @@ export function TransactionsTable(props: {
|
||||
const [autoUpdate, setAutoUpdate] = useState(true);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState<EngineStatus | undefined>(undefined);
|
||||
const [filterId, setFilterId] = useState<string | undefined>(undefined);
|
||||
const autoUpdateId = useId();
|
||||
const pageSize = 10;
|
||||
const transactionsQuery = useEngineTransactions({
|
||||
@@ -121,6 +123,7 @@ export function TransactionsTable(props: {
|
||||
page: page,
|
||||
status,
|
||||
},
|
||||
id: filterId,
|
||||
});
|
||||
|
||||
const transactions = transactionsQuery.data?.transactions ?? [];
|
||||
@@ -160,6 +163,16 @@ export function TransactionsTable(props: {
|
||||
onCheckedChange={(v) => setAutoUpdate(!!v)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
className="max-w-[250px]"
|
||||
onChange={(e) => {
|
||||
const value = e.target.value.trim();
|
||||
setFilterId(value || undefined);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Filter by Queue ID"
|
||||
value={filterId || ""}
|
||||
/>
|
||||
<StatusSelector
|
||||
setStatus={(v) => {
|
||||
setStatus(v);
|
||||
|
||||
@@ -29,6 +29,7 @@ import { ResponsiveTimeFilters } from "@/components/analytics/responsive-time-fi
|
||||
import { ProjectAvatar } from "@/components/blocks/avatar/project-avatar";
|
||||
import { ProjectPage } from "@/components/blocks/project-page/project-page";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { getProjectWallet } from "@/lib/server/project-wallet";
|
||||
import { getFiltersFromSearchParams } from "@/lib/time";
|
||||
import type {
|
||||
InAppWalletStats,
|
||||
@@ -38,7 +39,10 @@ import type {
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { PieChartCard } from "../../../components/Analytics/PieChartCard";
|
||||
import { EngineCloudChartCardAsync } from "./components/EngineCloudChartCard";
|
||||
import { ProjectFTUX } from "./components/ProjectFTUX/ProjectFTUX";
|
||||
import {
|
||||
ProjectFTUX,
|
||||
ProjectWalletSection,
|
||||
} from "./components/ProjectFTUX/ProjectFTUX";
|
||||
import { RpcMethodBarChartCardAsync } from "./components/RpcMethodBarChartCard";
|
||||
import { TransactionsChartCardAsync } from "./components/Transactions";
|
||||
import { ProjectHighlightsCard } from "./overview/highlights-card";
|
||||
@@ -64,6 +68,9 @@ type PageProps = {
|
||||
searchParams: Promise<PageSearchParams>;
|
||||
};
|
||||
|
||||
// Revalidate this page data every 30 seconds
|
||||
export const revalidate = 30;
|
||||
|
||||
export default async function ProjectOverviewPage(props: PageProps) {
|
||||
const [params, searchParams] = await Promise.all([
|
||||
props.params,
|
||||
@@ -104,6 +111,11 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
||||
teamId: project.teamId,
|
||||
});
|
||||
|
||||
const projectWallet = await getProjectWallet(project);
|
||||
const managementAccessToken =
|
||||
project.services?.find((service) => service.name === "engineCloud")
|
||||
?.managementAccessToken ?? undefined;
|
||||
|
||||
return (
|
||||
<ResponsiveSearchParamsProvider value={searchParams}>
|
||||
<ProjectPage
|
||||
@@ -125,6 +137,12 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
||||
>
|
||||
{isActive ? (
|
||||
<div className="flex flex-col gap-4 md:gap-6">
|
||||
<ProjectWalletSection
|
||||
project={project}
|
||||
teamSlug={params.team_slug}
|
||||
wallet={projectWallet}
|
||||
managementAccessToken={managementAccessToken}
|
||||
/>
|
||||
<ResponsiveTimeFilters defaultRange={defaultRange} />
|
||||
<ProjectAnalytics
|
||||
authToken={authToken}
|
||||
@@ -137,7 +155,12 @@ export default async function ProjectOverviewPage(props: PageProps) {
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<ProjectFTUX project={project} teamSlug={params.team_slug} />
|
||||
<ProjectFTUX
|
||||
project={project}
|
||||
teamSlug={params.team_slug}
|
||||
wallet={projectWallet}
|
||||
managementAccessToken={managementAccessToken}
|
||||
/>
|
||||
)}
|
||||
</ProjectPage>
|
||||
</ResponsiveSearchParamsProvider>
|
||||
|
||||
+2
@@ -15,6 +15,7 @@ export function QuickStartSection(props: {
|
||||
projectSlug: string;
|
||||
clientId: string;
|
||||
teamId: string;
|
||||
projectWalletAddress?: string;
|
||||
}) {
|
||||
return (
|
||||
<section>
|
||||
@@ -43,6 +44,7 @@ export function QuickStartSection(props: {
|
||||
action={
|
||||
<CreatePaymentLinkButton
|
||||
clientId={props.clientId}
|
||||
projectWalletAddress={props.projectWalletAddress}
|
||||
teamId={props.teamId}
|
||||
>
|
||||
<Button
|
||||
|
||||
+42
-9
@@ -45,7 +45,11 @@ const formSchema = z.object({
|
||||
});
|
||||
|
||||
export function CreatePaymentLinkButton(
|
||||
props: PropsWithChildren<{ clientId: string; teamId: string }>,
|
||||
props: PropsWithChildren<{
|
||||
clientId: string;
|
||||
teamId: string;
|
||||
projectWalletAddress?: string;
|
||||
}>,
|
||||
) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
@@ -55,6 +59,7 @@ export function CreatePaymentLinkButton(
|
||||
<DialogContent className="p-0 !max-w-lg">
|
||||
<CreatePaymentLinkDialogContent
|
||||
clientId={props.clientId}
|
||||
projectWalletAddress={props.projectWalletAddress}
|
||||
setOpen={setOpen}
|
||||
teamId={props.teamId}
|
||||
/>
|
||||
@@ -67,6 +72,7 @@ function CreatePaymentLinkDialogContent(props: {
|
||||
clientId: string;
|
||||
teamId: string;
|
||||
setOpen: (open: boolean) => void;
|
||||
projectWalletAddress?: string;
|
||||
}) {
|
||||
const client = getClientThirdwebClient();
|
||||
|
||||
@@ -182,14 +188,41 @@ function CreatePaymentLinkDialogContent(props: {
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Recipient Address</FormLabel>
|
||||
<Input
|
||||
className="w-full bg-card"
|
||||
{...field}
|
||||
onChange={field.onChange}
|
||||
value={field.value}
|
||||
placeholder="Address or ENS"
|
||||
required
|
||||
/>
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
className="w-full bg-card sm:flex-1"
|
||||
{...field}
|
||||
onChange={field.onChange}
|
||||
value={field.value}
|
||||
placeholder="Address or ENS"
|
||||
required
|
||||
/>
|
||||
{props.projectWalletAddress && (
|
||||
<Button
|
||||
className="sm:w-auto"
|
||||
onClick={() => {
|
||||
if (!props.projectWalletAddress) {
|
||||
return;
|
||||
}
|
||||
|
||||
form.setValue(
|
||||
"recipient",
|
||||
props.projectWalletAddress,
|
||||
{
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
shouldValidate: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
Use Project Wallet
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
|
||||
+16
-3
@@ -40,7 +40,11 @@ import { ErrorState } from "../../components/ErrorState";
|
||||
import { formatTokenAmount } from "../../components/format";
|
||||
import { CreatePaymentLinkButton } from "./CreatePaymentLinkButton.client";
|
||||
|
||||
export function PaymentLinksTable(props: { clientId: string; teamId: string }) {
|
||||
export function PaymentLinksTable(props: {
|
||||
clientId: string;
|
||||
teamId: string;
|
||||
projectWalletAddress?: string;
|
||||
}) {
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-4">
|
||||
@@ -49,12 +53,20 @@ export function PaymentLinksTable(props: { clientId: string; teamId: string }) {
|
||||
The payments you have created in this project
|
||||
</p>
|
||||
</div>
|
||||
<PaymentLinksTableInner clientId={props.clientId} teamId={props.teamId} />
|
||||
<PaymentLinksTableInner
|
||||
clientId={props.clientId}
|
||||
projectWalletAddress={props.projectWalletAddress}
|
||||
teamId={props.teamId}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function PaymentLinksTableInner(props: { clientId: string; teamId: string }) {
|
||||
function PaymentLinksTableInner(props: {
|
||||
clientId: string;
|
||||
teamId: string;
|
||||
projectWalletAddress?: string;
|
||||
}) {
|
||||
const paymentLinksQuery = useQuery({
|
||||
queryFn: async () => {
|
||||
return getPaymentLinks({
|
||||
@@ -120,6 +132,7 @@ function PaymentLinksTableInner(props: { clientId: string; teamId: string }) {
|
||||
<CreatePaymentLinkButton
|
||||
key="create-payment-link"
|
||||
clientId={props.clientId}
|
||||
projectWalletAddress={props.projectWalletAddress}
|
||||
teamId={props.teamId}
|
||||
>
|
||||
<Button className="gap-2 rounded-full" variant="default" size="sm">
|
||||
|
||||
+6
@@ -6,6 +6,7 @@ import { getProject } from "@/api/project/projects";
|
||||
import { ProjectPage } from "@/components/blocks/project-page/project-page";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { PayIcon } from "@/icons/PayIcon";
|
||||
import { getProjectWallet } from "@/lib/server/project-wallet";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { AdvancedSection } from "./components/AdvancedSection.client";
|
||||
import { QuickStartSection } from "./components/QuickstartSection.client";
|
||||
@@ -29,6 +30,8 @@ export default async function Page(props: {
|
||||
redirect(`/team/${params.team_slug}`);
|
||||
}
|
||||
|
||||
const projectWallet = await getProjectWallet(project);
|
||||
|
||||
const client = getClientThirdwebClient({
|
||||
jwt: authToken,
|
||||
teamId: project.teamId,
|
||||
@@ -51,6 +54,7 @@ export default async function Page(props: {
|
||||
component: (
|
||||
<CreatePaymentLinkButton
|
||||
clientId={project.publishableKey}
|
||||
projectWalletAddress={projectWallet?.address}
|
||||
teamId={project.teamId}
|
||||
>
|
||||
<Button className="gap-1.5 rounded-full" size="sm">
|
||||
@@ -141,12 +145,14 @@ export default async function Page(props: {
|
||||
<div className="flex flex-col gap-12">
|
||||
<PaymentLinksTable
|
||||
clientId={project.publishableKey}
|
||||
projectWalletAddress={projectWallet?.address}
|
||||
teamId={project.teamId}
|
||||
/>
|
||||
<QuickStartSection
|
||||
projectSlug={params.project_slug}
|
||||
teamSlug={params.team_slug}
|
||||
clientId={project.publishableKey}
|
||||
projectWalletAddress={projectWallet?.address}
|
||||
teamId={project.teamId}
|
||||
/>
|
||||
|
||||
|
||||
+33
-1
@@ -7,6 +7,7 @@ import { toast } from "sonner";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { type Fee, updateFee } from "@/api/universal-bridge/developer";
|
||||
import { SettingsCard } from "@/components/blocks/SettingsCard";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -25,6 +26,7 @@ interface PayConfigProps {
|
||||
teamId: string;
|
||||
teamSlug: string;
|
||||
fees: Fee;
|
||||
projectWalletAddress?: string;
|
||||
}
|
||||
|
||||
export const PayConfig: React.FC<PayConfigProps> = (props) => {
|
||||
@@ -103,7 +105,37 @@ export const PayConfig: React.FC<PayConfigProps> = (props) => {
|
||||
<FormItem>
|
||||
<FormLabel>Recipient address</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} placeholder="0x..." />
|
||||
<div className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
{...field}
|
||||
className="sm:flex-1"
|
||||
placeholder="0x..."
|
||||
/>
|
||||
{props.projectWalletAddress && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!props.projectWalletAddress) {
|
||||
return;
|
||||
}
|
||||
|
||||
form.setValue(
|
||||
"payoutAddress",
|
||||
props.projectWalletAddress,
|
||||
{
|
||||
shouldDirty: true,
|
||||
shouldTouch: true,
|
||||
shouldValidate: true,
|
||||
},
|
||||
);
|
||||
}}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
Use Project Wallet
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
|
||||
+4
@@ -3,6 +3,7 @@ import { getAuthToken } from "@/api/auth-token";
|
||||
import { getProject } from "@/api/project/projects";
|
||||
import { getTeamBySlug } from "@/api/team/get-team";
|
||||
import { getFees } from "@/api/universal-bridge/developer";
|
||||
import { getProjectWallet } from "@/lib/server/project-wallet";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { ProjectSettingsBreadcrumb } from "../_components/project-settings-breadcrumb";
|
||||
import { PayConfig } from "./PayConfig";
|
||||
@@ -31,6 +32,8 @@ export default async function Page(props: {
|
||||
redirect(`/team/${team_slug}`);
|
||||
}
|
||||
|
||||
const projectWallet = await getProjectWallet(project);
|
||||
|
||||
let fees = await getFees({
|
||||
clientId: project.publishableKey,
|
||||
teamId: team.id,
|
||||
@@ -64,6 +67,7 @@ export default async function Page(props: {
|
||||
fees={fees}
|
||||
project={project}
|
||||
teamId={team.id}
|
||||
projectWalletAddress={projectWallet?.address}
|
||||
teamSlug={team_slug}
|
||||
/>
|
||||
</div>
|
||||
|
||||
+4
@@ -74,6 +74,10 @@ export type CreateNFTCollectionFunctions = {
|
||||
count: number;
|
||||
};
|
||||
gasless: boolean;
|
||||
onNotEnoughFunds: (data: {
|
||||
requiredAmount: string;
|
||||
balance: string;
|
||||
}) => void;
|
||||
}) => Promise<void>;
|
||||
lazyMintNFTs: (params: {
|
||||
values: CreateNFTCollectionAllValues;
|
||||
|
||||
+98
-3
@@ -1,6 +1,14 @@
|
||||
"use client";
|
||||
import { useRef } from "react";
|
||||
import { encode, getContract, type ThirdwebClient } from "thirdweb";
|
||||
import {
|
||||
encode,
|
||||
estimateGasCost,
|
||||
getContract,
|
||||
getGasPrice,
|
||||
type PreparedTransaction,
|
||||
type ThirdwebClient,
|
||||
toEther,
|
||||
} from "thirdweb";
|
||||
import { deployERC721Contract, deployERC1155Contract } from "thirdweb/deploys";
|
||||
import { multicall } from "thirdweb/extensions/common";
|
||||
import {
|
||||
@@ -14,7 +22,8 @@ import {
|
||||
} from "thirdweb/extensions/erc1155";
|
||||
import { grantRole } from "thirdweb/extensions/permissions";
|
||||
import { useActiveAccount } from "thirdweb/react";
|
||||
import { maxUint256 } from "thirdweb/utils";
|
||||
import { maxUint256, resolvePromisedValue } from "thirdweb/utils";
|
||||
import { getWalletBalance } from "thirdweb/wallets";
|
||||
import { create7702MinimalAccount } from "thirdweb/wallets/smart";
|
||||
import { revalidatePathAction } from "@/actions/revalidate";
|
||||
import { reportContractDeployed } from "@/analytics/report";
|
||||
@@ -39,6 +48,10 @@ export function CreateNFTPage(props: {
|
||||
const contractAddressRef = useRef<string | undefined>(undefined);
|
||||
const getChain = useGetV5DashboardChain();
|
||||
const sendAndConfirmTx = useSendAndConfirmTx();
|
||||
const sendAndConfirmTxNoPayModal = useSendAndConfirmTx({
|
||||
payModal: false,
|
||||
});
|
||||
|
||||
function getAccount(params: { gasless: boolean }) {
|
||||
if (!activeAccount) {
|
||||
throw new Error("Wallet is not connected");
|
||||
@@ -130,6 +143,7 @@ export function CreateNFTPage(props: {
|
||||
contractName: contractType,
|
||||
deploymentType: "asset",
|
||||
publisher: "deployer.thirdweb.eth",
|
||||
is_testnet: chain.testnet,
|
||||
});
|
||||
|
||||
contractAddressRef.current = contractAddress;
|
||||
@@ -218,6 +232,10 @@ export function CreateNFTPage(props: {
|
||||
count: number;
|
||||
};
|
||||
gasless: boolean;
|
||||
onNotEnoughFunds: (data: {
|
||||
requiredAmount: string;
|
||||
balance: string;
|
||||
}) => void;
|
||||
}) {
|
||||
const { values, batch } = params;
|
||||
const contract = getDeployedContract({
|
||||
@@ -277,7 +295,46 @@ export function CreateNFTPage(props: {
|
||||
data: encodedTransactions,
|
||||
});
|
||||
|
||||
await sendAndConfirmTx.mutateAsync(tx);
|
||||
// if there are more than one batches, on the first batch, we check if the user has enough funds to cover the cost of all the batches ->
|
||||
// calculate the cost of one batch, multiply by the number of batches to get the total cost
|
||||
// if the user does not have enough funds, call the onNotEnoughFunds callback
|
||||
|
||||
const totalBatches = Math.ceil(values.nfts.length / batch.count);
|
||||
|
||||
if (batch.startIndex === 0 && totalBatches > 1 && !params.gasless) {
|
||||
if (!activeAccount) {
|
||||
throw new Error("Wallet is not connected");
|
||||
}
|
||||
|
||||
const costPerBatch = await getTotalTransactionCost({
|
||||
tx: tx,
|
||||
from: activeAccount.address,
|
||||
});
|
||||
|
||||
const totalCost = costPerBatch * BigInt(totalBatches);
|
||||
|
||||
const walletBalance = await getWalletBalance({
|
||||
address: activeAccount.address,
|
||||
chain: contract.chain,
|
||||
client: contract.client,
|
||||
});
|
||||
|
||||
if (walletBalance.value < totalCost) {
|
||||
params.onNotEnoughFunds({
|
||||
balance: toEther(walletBalance.value),
|
||||
requiredAmount: toEther(totalCost),
|
||||
});
|
||||
throw new Error(
|
||||
`Not enough funds: Required ${toEther(totalCost)}, Balance ${toEther(walletBalance.value)}`,
|
||||
);
|
||||
}
|
||||
|
||||
await sendAndConfirmTxNoPayModal.mutateAsync(tx);
|
||||
} else if (totalBatches > 1) {
|
||||
await sendAndConfirmTxNoPayModal.mutateAsync(tx);
|
||||
} else {
|
||||
await sendAndConfirmTx.mutateAsync(tx);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSetAdmins(params: {
|
||||
@@ -390,3 +447,41 @@ function transformSocialUrls(
|
||||
{} as Record<string, string>,
|
||||
);
|
||||
}
|
||||
|
||||
async function getTransactionGasCost(tx: PreparedTransaction, from?: string) {
|
||||
try {
|
||||
const gasCost = await estimateGasCost({
|
||||
from,
|
||||
transaction: tx,
|
||||
});
|
||||
|
||||
const bufferCost = gasCost.wei / 10n;
|
||||
|
||||
// Note: get tx.value AFTER estimateGasCost
|
||||
// add 10% extra gas cost to the estimate to ensure user buys enough to cover the tx cost
|
||||
return gasCost.wei + bufferCost;
|
||||
} catch {
|
||||
if (from) {
|
||||
// try again without passing from
|
||||
return await getTransactionGasCost(tx);
|
||||
}
|
||||
// fallback if both fail, use the tx value + 1M * gas price
|
||||
const gasPrice = await getGasPrice({
|
||||
chain: tx.chain,
|
||||
client: tx.client,
|
||||
});
|
||||
|
||||
return 1_000_000n * gasPrice;
|
||||
}
|
||||
}
|
||||
|
||||
async function getTotalTransactionCost(params: {
|
||||
tx: PreparedTransaction;
|
||||
from?: string;
|
||||
}) {
|
||||
const [txValue, txGasCost] = await Promise.all([
|
||||
resolvePromisedValue(params.tx.value),
|
||||
getTransactionGasCost(params.tx, params.from),
|
||||
]);
|
||||
return (txValue || 0n) + txGasCost;
|
||||
}
|
||||
|
||||
+180
-32
@@ -1,14 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ArrowRightIcon,
|
||||
ArrowUpFromLineIcon,
|
||||
ImageOffIcon,
|
||||
RefreshCcwIcon,
|
||||
ShoppingBagIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import {
|
||||
BuyWidget,
|
||||
TokenProvider,
|
||||
TokenSymbol,
|
||||
useActiveAccount,
|
||||
@@ -37,6 +42,7 @@ import {
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||
import { ChainOverview } from "../../_common/chain-overview";
|
||||
import { StepCard } from "../../_common/step-card";
|
||||
import { StorageErrorPlanUpsell } from "../../_common/storage-error-upsell";
|
||||
@@ -71,6 +77,10 @@ export function LaunchNFT(props: {
|
||||
const walletRequiresApproval = activeWallet?.id !== "inApp";
|
||||
const account = useActiveAccount();
|
||||
const contractAddressRef = useRef<string | null>(null);
|
||||
const { theme } = useTheme();
|
||||
const chainMeta = useV5DashboardChain(
|
||||
Number(formValues.collectionInfo.chain),
|
||||
);
|
||||
|
||||
function updateStatus(
|
||||
index: number,
|
||||
@@ -161,6 +171,18 @@ export function LaunchNFT(props: {
|
||||
const [isGasless, setIsGasless] = useState(canEnableGasless);
|
||||
const showGaslessSection = false; // activeWallet?.id === "inApp";
|
||||
|
||||
const [notEnoughFunds, setNotEnoughFunds] = useState<
|
||||
| false
|
||||
| {
|
||||
values: {
|
||||
requiredAmount: string;
|
||||
balance: string;
|
||||
};
|
||||
isBuySuccess: boolean;
|
||||
showBuyWidget: boolean;
|
||||
}
|
||||
>(false);
|
||||
|
||||
const contractLink = contractAddressRef.current
|
||||
? `/team/${props.teamSlug}/${props.projectSlug}/contract/${formValues.collectionInfo.chain}/${contractAddressRef.current}`
|
||||
: null;
|
||||
@@ -204,6 +226,16 @@ export function LaunchNFT(props: {
|
||||
},
|
||||
gasless: isGasless,
|
||||
values: formValues,
|
||||
onNotEnoughFunds: (data) => {
|
||||
setNotEnoughFunds({
|
||||
values: {
|
||||
balance: data.balance,
|
||||
requiredAmount: data.requiredAmount,
|
||||
},
|
||||
isBuySuccess: false,
|
||||
showBuyWidget: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
batchesProcessedRef.current += 1;
|
||||
@@ -216,6 +248,16 @@ export function LaunchNFT(props: {
|
||||
},
|
||||
gasless: isGasless,
|
||||
values: formValues,
|
||||
onNotEnoughFunds: (data) => {
|
||||
setNotEnoughFunds({
|
||||
values: {
|
||||
balance: data.balance,
|
||||
requiredAmount: data.requiredAmount,
|
||||
},
|
||||
isBuySuccess: false,
|
||||
showBuyWidget: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -274,6 +316,8 @@ export function LaunchNFT(props: {
|
||||
contractType: ercType === "erc721" ? "DropERC721" : "DropERC1155",
|
||||
error: errorMessage,
|
||||
step: currentStep.id,
|
||||
is_testnet: chainMeta.testnet,
|
||||
chainId: Number(formValues.collectionInfo.chain),
|
||||
});
|
||||
|
||||
throw error;
|
||||
@@ -283,6 +327,8 @@ export function LaunchNFT(props: {
|
||||
reportAssetCreationSuccessful({
|
||||
assetType: "nft",
|
||||
contractType: ercType === "erc721" ? "DropERC721" : "DropERC1155",
|
||||
chainId: Number(formValues.collectionInfo.chain),
|
||||
is_testnet: chainMeta?.testnet ?? false,
|
||||
});
|
||||
|
||||
props.onLaunchSuccess();
|
||||
@@ -357,41 +403,143 @@ export function LaunchNFT(props: {
|
||||
className="gap-0 overflow-hidden p-0 md:max-w-[480px]"
|
||||
dialogCloseClassName="hidden"
|
||||
>
|
||||
<div className="flex flex-col gap-6 p-6">
|
||||
<DialogHeader className="space-y-0.5">
|
||||
<DialogTitle className="font-semibold text-xl tracking-tight">
|
||||
Status
|
||||
</DialogTitle>
|
||||
{walletRequiresApproval && (
|
||||
<DialogDescription>
|
||||
Each step will prompt a signature request in your wallet
|
||||
</DialogDescription>
|
||||
)}
|
||||
</DialogHeader>
|
||||
{/** biome-ignore lint/complexity/useOptionalChain: can't change it to optional chain */}
|
||||
{notEnoughFunds && notEnoughFunds.showBuyWidget ? (
|
||||
<div className="bg-card">
|
||||
<div className="border-b py-2 px-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setNotEnoughFunds({
|
||||
...notEnoughFunds,
|
||||
showBuyWidget: false,
|
||||
})
|
||||
}
|
||||
className="gap-2 px-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
<BuyWidget
|
||||
client={props.client}
|
||||
chain={chain}
|
||||
amount={String(
|
||||
Number(notEnoughFunds.values.requiredAmount) -
|
||||
Number(notEnoughFunds.values.balance),
|
||||
)}
|
||||
buttonLabel={`Buy ${chainMeta?.nativeCurrency?.symbol || "ETH"}`}
|
||||
theme={getSDKTheme(theme === "dark" ? "dark" : "light")}
|
||||
className="!border-none !w-full !rounded-none"
|
||||
onSuccess={() => {
|
||||
setNotEnoughFunds({
|
||||
...notEnoughFunds,
|
||||
isBuySuccess: true,
|
||||
showBuyWidget: false,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-6 p-6 mb-2">
|
||||
<DialogHeader className="space-y-0.5">
|
||||
<DialogTitle className="font-semibold text-xl tracking-tight">
|
||||
Status
|
||||
</DialogTitle>
|
||||
{walletRequiresApproval && (
|
||||
<DialogDescription>
|
||||
Each step will prompt a signature request in your wallet
|
||||
</DialogDescription>
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
<MultiStepStatus
|
||||
onRetry={handleRetry}
|
||||
renderError={(step, errorMessage) => {
|
||||
if (
|
||||
props.teamPlan === "free" &&
|
||||
errorMessage.toLowerCase().includes("storage limit")
|
||||
) {
|
||||
return (
|
||||
<StorageErrorPlanUpsell
|
||||
onRetry={() => handleRetry(step)}
|
||||
teamSlug={props.teamSlug}
|
||||
trackingCampaign="create-nft"
|
||||
/>
|
||||
);
|
||||
}
|
||||
<MultiStepStatus
|
||||
onRetry={handleRetry}
|
||||
renderError={(step, errorMessage) => {
|
||||
if (
|
||||
props.teamPlan === "free" &&
|
||||
errorMessage.toLowerCase().includes("storage limit")
|
||||
) {
|
||||
return (
|
||||
<StorageErrorPlanUpsell
|
||||
onRetry={() => handleRetry(step)}
|
||||
teamSlug={props.teamSlug}
|
||||
trackingCampaign="create-nft"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}}
|
||||
steps={steps}
|
||||
/>
|
||||
</div>
|
||||
if (notEnoughFunds) {
|
||||
return (
|
||||
<div>
|
||||
{notEnoughFunds.isBuySuccess ? (
|
||||
<p className="text-success-text text-sm mt-1.5 mb-2">
|
||||
Funds bought successfully
|
||||
</p>
|
||||
) : (
|
||||
<div className="mt-2 mb-2 space-y-1">
|
||||
<p className="text-destructive-text text-sm">
|
||||
Not enough funds
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Required Funds:{" "}
|
||||
{notEnoughFunds.values.requiredAmount}{" "}
|
||||
{chainMeta?.nativeCurrency?.symbol || "ETH"}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Balance: {notEnoughFunds.values.balance}{" "}
|
||||
{chainMeta?.nativeCurrency?.symbol || "ETH"}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-2 flex justify-end gap-4 border-border border-t bg-card p-6">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={() => {
|
||||
handleRetry(step);
|
||||
setNotEnoughFunds(false);
|
||||
}}
|
||||
size="sm"
|
||||
variant={
|
||||
notEnoughFunds.isBuySuccess
|
||||
? "default"
|
||||
: "outline"
|
||||
}
|
||||
className="gap-2"
|
||||
>
|
||||
<RefreshCcwIcon className="size-3.5" />
|
||||
Retry
|
||||
</Button>
|
||||
|
||||
{!notEnoughFunds.isBuySuccess && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
setNotEnoughFunds({
|
||||
...notEnoughFunds,
|
||||
showBuyWidget: true,
|
||||
});
|
||||
}}
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
>
|
||||
<ShoppingBagIcon className="size-3.5" />
|
||||
Buy Funds
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}}
|
||||
steps={steps}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-4 border-border border-t bg-card p-6">
|
||||
{!isComplete ? (
|
||||
<Button
|
||||
onClick={() => {
|
||||
|
||||
+6
-1
@@ -178,12 +178,14 @@ export function CreateTokenAssetPage(props: {
|
||||
teamId: props.teamId,
|
||||
});
|
||||
|
||||
const chainMetadata = getChain(Number(params.values.chain));
|
||||
reportContractDeployed({
|
||||
address: contractAddress,
|
||||
chainId: Number(params.values.chain),
|
||||
contractName: "DropERC20",
|
||||
contractName: "ERC20Asset",
|
||||
deploymentType: "asset",
|
||||
publisher: account.address,
|
||||
is_testnet: chainMetadata.testnet,
|
||||
});
|
||||
|
||||
contractAddressRef.current = contractAddress;
|
||||
@@ -299,12 +301,15 @@ export function CreateTokenAssetPage(props: {
|
||||
teamId: props.teamId,
|
||||
});
|
||||
|
||||
const chainMetadata = getChain(Number(values.chain));
|
||||
|
||||
reportContractDeployed({
|
||||
address: contractAddress,
|
||||
chainId: Number(values.chain),
|
||||
contractName: "DropERC20",
|
||||
deploymentType: "asset",
|
||||
publisher: "deployer.thirdweb.eth",
|
||||
is_testnet: chainMetadata.testnet,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
+4
@@ -230,6 +230,8 @@ export function LaunchTokenStatus(props: {
|
||||
: "ERC20Asset",
|
||||
error: errorMessage,
|
||||
step: currentStep.id,
|
||||
is_testnet: chainMetadata?.testnet,
|
||||
chainId: Number(formValues.chain),
|
||||
});
|
||||
|
||||
updateStatus(i, {
|
||||
@@ -247,6 +249,8 @@ export function LaunchTokenStatus(props: {
|
||||
formValues.saleMode === "drop-erc20:token-drop"
|
||||
? "DropERC20"
|
||||
: "ERC20Asset",
|
||||
chainId: Number(formValues.chain),
|
||||
is_testnet: chainMetadata?.testnet,
|
||||
});
|
||||
|
||||
if (contractAddressRef.current) {
|
||||
|
||||
+48
-18
@@ -13,6 +13,7 @@ import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyAddressButton } from "@/components/ui/CopyAddressButton";
|
||||
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
@@ -49,6 +50,8 @@ export function TransactionsTableUI(props: {
|
||||
getData: (params: {
|
||||
page: number;
|
||||
status: TransactionStatus | undefined;
|
||||
id: string | undefined;
|
||||
from: string | undefined;
|
||||
}) => Promise<TransactionsResponse>;
|
||||
project: Project;
|
||||
teamSlug: string;
|
||||
@@ -60,13 +63,15 @@ export function TransactionsTableUI(props: {
|
||||
const [status, setStatus] = useState<TransactionStatus | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [id, setId] = useState<string | undefined>(undefined);
|
||||
const [from, setFrom] = useState<string | undefined>(undefined);
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const pageSize = 10;
|
||||
const transactionsQuery = useQuery({
|
||||
placeholderData: keepPreviousData,
|
||||
queryFn: () => props.getData({ page, status }),
|
||||
queryKey: ["transactions", props.project.id, page, status],
|
||||
queryFn: () => props.getData({ page, status, id, from }),
|
||||
queryKey: ["transactions", props.project.id, page, status, id, from],
|
||||
refetchInterval: autoUpdate ? 4_000 : false,
|
||||
});
|
||||
|
||||
@@ -84,18 +89,18 @@ export function TransactionsTableUI(props: {
|
||||
|
||||
return (
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-card">
|
||||
<div className="flex flex-col gap-4 rounded-lg rounded-b-none px-6 py-6 lg:flex-row lg:justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-2xl tracking-tight">
|
||||
Transaction History
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Transactions sent from server wallets
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 rounded-lg rounded-b-none px-6 py-6">
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-2xl tracking-tight">
|
||||
Transaction History
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Transactions sent from server wallets
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-5 border-border border-t pt-4 lg:border-none lg:pt-0">
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<div className="flex shrink-0 items-center gap-2 border-border border-t pt-4 lg:border-none lg:pt-0">
|
||||
<Label htmlFor={autoUpdateId}>Auto Update</Label>
|
||||
<Switch
|
||||
checked={autoUpdate}
|
||||
@@ -103,14 +108,39 @@ export function TransactionsTableUI(props: {
|
||||
onCheckedChange={(v) => setAutoUpdate(!!v)}
|
||||
/>
|
||||
</div>
|
||||
<StatusSelector
|
||||
setStatus={(v) => {
|
||||
setStatus(v);
|
||||
// reset page
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-end gap-3">
|
||||
<Input
|
||||
className="max-w-[250px]"
|
||||
onChange={(e) => {
|
||||
const value = e.target.value.trim();
|
||||
setId(value || undefined);
|
||||
setPage(1);
|
||||
}}
|
||||
status={status}
|
||||
placeholder="Filter by Queue ID"
|
||||
value={id || ""}
|
||||
/>
|
||||
<Input
|
||||
className="max-w-[250px]"
|
||||
onChange={(e) => {
|
||||
const value = e.target.value.trim();
|
||||
setFrom(value || undefined);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder="Filter by wallet address"
|
||||
value={from || ""}
|
||||
/>
|
||||
<div>
|
||||
<StatusSelector
|
||||
setStatus={(v) => {
|
||||
setStatus(v);
|
||||
// reset page
|
||||
setPage(1);
|
||||
}}
|
||||
status={status}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+9
-1
@@ -16,11 +16,13 @@ export function TransactionsTable(props: {
|
||||
return (
|
||||
<TransactionsTableUI
|
||||
client={props.client}
|
||||
getData={async ({ page, status }) => {
|
||||
getData={async ({ page, status, id, from }) => {
|
||||
return await getTransactions({
|
||||
page,
|
||||
project: props.project,
|
||||
status,
|
||||
id,
|
||||
from,
|
||||
});
|
||||
}}
|
||||
project={props.project}
|
||||
@@ -34,10 +36,14 @@ async function getTransactions({
|
||||
project,
|
||||
page,
|
||||
status,
|
||||
id,
|
||||
from,
|
||||
}: {
|
||||
project: Project;
|
||||
page: number;
|
||||
status: TransactionStatus | undefined;
|
||||
id: string | undefined;
|
||||
from: string | undefined;
|
||||
}) {
|
||||
const transactions = await engineCloudProxy<{ result: TransactionsResponse }>(
|
||||
{
|
||||
@@ -52,6 +58,8 @@ async function getTransactions({
|
||||
limit: "20",
|
||||
page: page.toString(),
|
||||
status: status ?? undefined,
|
||||
id: id ?? undefined,
|
||||
from: from ?? undefined,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
+104
-2
@@ -3,14 +3,17 @@
|
||||
import { encrypt } from "@thirdweb-dev/service-utils";
|
||||
import {
|
||||
createAccessToken,
|
||||
createEoa,
|
||||
createServiceAccount,
|
||||
createVaultClient,
|
||||
rotateServiceAccount,
|
||||
type VaultClient,
|
||||
} from "@thirdweb-dev/vault-sdk";
|
||||
import { engineCloudProxy } from "@/actions/proxies";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { NEXT_PUBLIC_THIRDWEB_VAULT_URL } from "@/constants/public-envs";
|
||||
import { updateProjectClient } from "@/hooks/useApi";
|
||||
import { getProjectWalletLabel } from "@/lib/project-wallet";
|
||||
|
||||
const SERVER_WALLET_ACCESS_TOKEN_PURPOSE =
|
||||
"Access Token for All Server Wallets";
|
||||
@@ -126,6 +129,92 @@ export async function createVaultAccountAndAccessToken(props: {
|
||||
}
|
||||
}
|
||||
|
||||
export async function createProjectServerWallet(props: {
|
||||
project: Project;
|
||||
managementAccessToken: string;
|
||||
label?: string;
|
||||
setAsProjectWallet?: boolean;
|
||||
}) {
|
||||
const vaultClient = await initVaultClient();
|
||||
|
||||
const walletLabel = props.label?.trim()
|
||||
? props.label.trim()
|
||||
: getProjectWalletLabel(props.project.name);
|
||||
|
||||
const eoa = await createEoa({
|
||||
client: vaultClient,
|
||||
request: {
|
||||
auth: {
|
||||
accessToken: props.managementAccessToken,
|
||||
},
|
||||
options: {
|
||||
metadata: {
|
||||
label: walletLabel,
|
||||
projectId: props.project.id,
|
||||
teamId: props.project.teamId,
|
||||
type: "server-wallet",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!eoa.success) {
|
||||
throw new Error(eoa.error?.message || "Failed to create server wallet");
|
||||
}
|
||||
|
||||
engineCloudProxy({
|
||||
body: JSON.stringify({
|
||||
signerAddress: eoa.data.address,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-client-id": props.project.publishableKey,
|
||||
"x-team-id": props.project.teamId,
|
||||
},
|
||||
method: "POST",
|
||||
pathname: "/cache/smart-account",
|
||||
}).catch((err) => {
|
||||
console.warn("failed to cache server wallet", err);
|
||||
});
|
||||
|
||||
if (props.setAsProjectWallet) {
|
||||
await updateDefaultProjectWallet({
|
||||
project: props.project,
|
||||
projectWalletAddress: eoa.data.address,
|
||||
});
|
||||
}
|
||||
|
||||
return eoa.data;
|
||||
}
|
||||
|
||||
export async function updateDefaultProjectWallet(props: {
|
||||
project: Project;
|
||||
projectWalletAddress: string;
|
||||
}) {
|
||||
const services = props.project.services.filter(
|
||||
(service) => service.name !== "engineCloud",
|
||||
);
|
||||
const engineCloudService = props.project.services.find(
|
||||
(service) => service.name === "engineCloud",
|
||||
);
|
||||
if (engineCloudService) {
|
||||
const engineCloudServiceWithProjectWallet = {
|
||||
...engineCloudService,
|
||||
projectWalletAddress: props.projectWalletAddress,
|
||||
};
|
||||
|
||||
await updateProjectClient(
|
||||
{
|
||||
projectId: props.project.id,
|
||||
teamId: props.project.teamId,
|
||||
},
|
||||
{
|
||||
services: [...services, engineCloudServiceWithProjectWallet],
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function createAndEncryptVaultAccessTokens(props: {
|
||||
project: Project;
|
||||
vaultClient: VaultClient;
|
||||
@@ -157,6 +246,13 @@ async function createAndEncryptVaultAccessTokens(props: {
|
||||
const managementToken = managementTokenResult.data;
|
||||
const walletToken = walletTokenResult.data;
|
||||
|
||||
// create a default project server wallet
|
||||
const defaultProjectServerWallet = await createProjectServerWallet({
|
||||
project,
|
||||
managementAccessToken: managementToken.accessToken,
|
||||
label: getProjectWalletLabel(project.name),
|
||||
});
|
||||
|
||||
if (projectSecretKey) {
|
||||
// verify that the project secret key is valid
|
||||
const projectSecretKeyHash = await hashSecretKey(projectSecretKey);
|
||||
@@ -182,7 +278,9 @@ async function createAndEncryptVaultAccessTokens(props: {
|
||||
},
|
||||
{
|
||||
services: [
|
||||
...props.project.services,
|
||||
...props.project.services.filter(
|
||||
(service) => service.name !== "engineCloud",
|
||||
),
|
||||
{
|
||||
name: "engineCloud",
|
||||
actions: [],
|
||||
@@ -191,6 +289,7 @@ async function createAndEncryptVaultAccessTokens(props: {
|
||||
encryptedAdminKey,
|
||||
encryptedWalletAccessToken,
|
||||
rotationCode: rotationCode,
|
||||
projectWalletAddress: defaultProjectServerWallet.address,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -204,7 +303,9 @@ async function createAndEncryptVaultAccessTokens(props: {
|
||||
},
|
||||
{
|
||||
services: [
|
||||
...props.project.services,
|
||||
...props.project.services.filter(
|
||||
(service) => service.name !== "engineCloud",
|
||||
),
|
||||
{
|
||||
name: "engineCloud",
|
||||
actions: [],
|
||||
@@ -213,6 +314,7 @@ async function createAndEncryptVaultAccessTokens(props: {
|
||||
encryptedAdminKey: null,
|
||||
encryptedWalletAccessToken: null,
|
||||
rotationCode: rotationCode,
|
||||
projectWalletAddress: defaultProjectServerWallet.address,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
+9
-42
@@ -1,10 +1,8 @@
|
||||
"use client";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { createEoa } from "@thirdweb-dev/vault-sdk";
|
||||
import { PlusIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { engineCloudProxy } from "@/actions/proxies";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -17,12 +15,13 @@ import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Spinner } from "@/components/ui/Spinner";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
import { initVaultClient } from "../../lib/vault.client";
|
||||
import { createProjectServerWallet } from "../../lib/vault.client";
|
||||
|
||||
export default function CreateServerWallet(props: {
|
||||
project: Project;
|
||||
teamSlug: string;
|
||||
managementAccessToken: string | undefined;
|
||||
setAsProjectWallet?: boolean;
|
||||
}) {
|
||||
const router = useDashboardRouter();
|
||||
const [label, setLabel] = useState("");
|
||||
@@ -36,49 +35,17 @@ export default function CreateServerWallet(props: {
|
||||
managementAccessToken: string;
|
||||
label: string;
|
||||
}) => {
|
||||
const vaultClient = await initVaultClient();
|
||||
|
||||
const eoa = await createEoa({
|
||||
client: vaultClient,
|
||||
request: {
|
||||
auth: {
|
||||
accessToken: managementAccessToken,
|
||||
},
|
||||
options: {
|
||||
metadata: {
|
||||
label,
|
||||
projectId: props.project.id,
|
||||
teamId: props.project.teamId,
|
||||
type: "server-wallet",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!eoa.success) {
|
||||
throw new Error("Failed to create eoa");
|
||||
}
|
||||
|
||||
// no need to await this, it's not blocking
|
||||
engineCloudProxy({
|
||||
body: JSON.stringify({
|
||||
signerAddress: eoa.data.address,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-client-id": props.project.publishableKey,
|
||||
"x-team-id": props.project.teamId,
|
||||
},
|
||||
method: "POST",
|
||||
pathname: "/cache/smart-account",
|
||||
}).catch((err) => {
|
||||
console.warn("failed to cache server wallet", err);
|
||||
const wallet = await createProjectServerWallet({
|
||||
label,
|
||||
managementAccessToken,
|
||||
project: props.project,
|
||||
setAsProjectWallet: props.setAsProjectWallet,
|
||||
});
|
||||
|
||||
router.refresh();
|
||||
setModalOpen(false);
|
||||
|
||||
return eoa;
|
||||
setLabel("");
|
||||
return wallet;
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(error.message);
|
||||
|
||||
+72
-32
@@ -1,8 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||
import {
|
||||
CheckIcon,
|
||||
MoreVerticalIcon,
|
||||
RefreshCcwIcon,
|
||||
SendIcon,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { useWalletBalance } from "thirdweb/react";
|
||||
import {
|
||||
@@ -20,6 +22,7 @@ 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 {
|
||||
DropdownMenu,
|
||||
@@ -50,7 +53,9 @@ import {
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||
import { WalletProductIcon } from "@/icons/WalletProductIcon";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { updateDefaultProjectWallet } from "../../lib/vault.client";
|
||||
import CreateServerWallet from "../components/create-server-wallet.client";
|
||||
import type { Wallet } from "./types";
|
||||
|
||||
@@ -96,15 +101,22 @@ export function ServerWalletsTableUI({
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-start lg:items-end gap-5 border-t lg:border-t-0 pt-5 lg:pt-0 border-dashed">
|
||||
<SingleNetworkSelector
|
||||
chainId={selectedChainId}
|
||||
onChange={setSelectedChainId}
|
||||
client={client}
|
||||
disableChainId
|
||||
className="w-fit min-w-[180px] rounded-full bg-background hover:bg-accent/50"
|
||||
placeholder="Select network"
|
||||
popoverContentClassName="!w-[320px] rounded-xl overflow-hidden"
|
||||
/>
|
||||
<div className="flex flex-row gap-2.5">
|
||||
<CreateServerWallet
|
||||
managementAccessToken={managementAccessToken}
|
||||
project={project}
|
||||
teamSlug={teamSlug}
|
||||
/>
|
||||
<SingleNetworkSelector
|
||||
chainId={selectedChainId}
|
||||
onChange={setSelectedChainId}
|
||||
client={client}
|
||||
disableChainId
|
||||
className="w-fit min-w-[180px] rounded-full bg-background hover:bg-accent/50"
|
||||
placeholder="Select network"
|
||||
popoverContentClassName="!w-[320px] rounded-xl overflow-hidden"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2.5">
|
||||
<Label
|
||||
@@ -187,25 +199,10 @@ export function ServerWalletsTableUI({
|
||||
<XIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="text-muted-foreground">No server wallets found</p>
|
||||
<CreateServerWallet
|
||||
managementAccessToken={managementAccessToken}
|
||||
project={project}
|
||||
teamSlug={teamSlug}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</TableContainer>
|
||||
|
||||
{wallets.length > 0 && (
|
||||
<div className="flex justify-end items-center p-4 py-5 lg:px-6 border-t">
|
||||
<CreateServerWallet
|
||||
managementAccessToken={managementAccessToken}
|
||||
project={project}
|
||||
teamSlug={teamSlug}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{totalPages > 1 && (
|
||||
<div className="flex flex-col items-center border-t p-6">
|
||||
<div className="mb-4 text-muted-foreground text-sm">
|
||||
@@ -295,18 +292,34 @@ function ServerWalletTableRow(props: {
|
||||
queryKey: ["smart-account-address", wallet.address, chainId],
|
||||
});
|
||||
|
||||
// Get the default project wallet address
|
||||
const engineCloudService = project.services.find(
|
||||
(service) => service.name === "engineCloud",
|
||||
);
|
||||
const defaultWalletAddress = engineCloudService?.projectWalletAddress;
|
||||
const isDefaultWallet =
|
||||
defaultWalletAddress &&
|
||||
wallet.address.toLowerCase() === defaultWalletAddress.toLowerCase();
|
||||
|
||||
return (
|
||||
<TableRow key={wallet.id}>
|
||||
{/* Label */}
|
||||
<TableCell>
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm text-foreground",
|
||||
!wallet.metadata.label && "text-muted-foreground",
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn(
|
||||
"text-sm text-foreground",
|
||||
!wallet.metadata.label && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{wallet.metadata.label || "N/A"}
|
||||
</span>
|
||||
{isDefaultWallet && (
|
||||
<Badge variant="success" className="text-xs">
|
||||
default
|
||||
</Badge>
|
||||
)}
|
||||
>
|
||||
{wallet.metadata.label || "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
|
||||
{/* Address */}
|
||||
@@ -399,6 +412,25 @@ function WalletActionsDropdown(props: {
|
||||
chainId: number;
|
||||
}) {
|
||||
const [showFundModal, setShowFundModal] = useState(false);
|
||||
const router = useDashboardRouter();
|
||||
|
||||
const setAsDefaultMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
await updateDefaultProjectWallet({
|
||||
project: props.project,
|
||||
projectWalletAddress: props.wallet.address,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("Wallet set as default project wallet");
|
||||
router.refresh();
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(
|
||||
error instanceof Error ? error.message : "Failed to set default wallet",
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -428,6 +460,14 @@ function WalletActionsDropdown(props: {
|
||||
Fund wallet
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => setAsDefaultMutation.mutate()}
|
||||
disabled={setAsDefaultMutation.isPending}
|
||||
className="flex items-center gap-2 h-9 rounded-lg"
|
||||
>
|
||||
<CheckIcon className="size-4 text-muted-foreground" />
|
||||
Set as default
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
|
||||
+69
-7
@@ -1,3 +1,4 @@
|
||||
import { createVaultClient, listEoas } from "@thirdweb-dev/vault-sdk";
|
||||
import { redirect } from "next/navigation";
|
||||
import { ResponsiveSearchParamsProvider } from "responsive-rsc";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
@@ -6,10 +7,13 @@ import type { DurationId } from "@/components/analytics/date-range-selector";
|
||||
import { ResponsiveTimeFilters } from "@/components/analytics/responsive-time-filters";
|
||||
import { ProjectPage } from "@/components/blocks/project-page/project-page";
|
||||
import { InAppWalletUsersPageContent } from "@/components/in-app-wallet-users-content/in-app-wallet-users-content";
|
||||
import { NEXT_PUBLIC_THIRDWEB_VAULT_URL } from "@/constants/public-envs";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { WalletProductIcon } from "@/icons/WalletProductIcon";
|
||||
import { getFiltersFromSearchParams } from "@/lib/time";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import type { Wallet } from "../transactions/server-wallets/wallet-table/types";
|
||||
import { ServerWalletsTable } from "../transactions/server-wallets/wallet-table/wallet-table";
|
||||
import { InAppWalletAnalytics } from "./analytics/chart";
|
||||
import { InAppWalletsSummary } from "./analytics/chart/Summary";
|
||||
|
||||
@@ -20,6 +24,7 @@ export default async function Page(props: {
|
||||
to?: string;
|
||||
type?: string;
|
||||
interval?: string;
|
||||
page?: string;
|
||||
}>;
|
||||
}) {
|
||||
const [searchParams, params] = await Promise.all([
|
||||
@@ -40,12 +45,47 @@ export default async function Page(props: {
|
||||
to: searchParams.to,
|
||||
});
|
||||
|
||||
const project = await getProject(params.team_slug, params.project_slug);
|
||||
const [vaultClient, project] = await Promise.all([
|
||||
createVaultClient({
|
||||
baseUrl: NEXT_PUBLIC_THIRDWEB_VAULT_URL,
|
||||
}).catch(() => undefined),
|
||||
getProject(params.team_slug, params.project_slug),
|
||||
]);
|
||||
|
||||
if (!project) {
|
||||
redirect(`/team/${params.team_slug}`);
|
||||
}
|
||||
|
||||
const projectEngineCloudService = project.services.find(
|
||||
(service) => service.name === "engineCloud",
|
||||
);
|
||||
|
||||
const managementAccessToken =
|
||||
projectEngineCloudService?.managementAccessToken;
|
||||
|
||||
// Fetch server wallets with pagination (5 per page)
|
||||
const pageSize = 5;
|
||||
const currentPage = Number.parseInt(searchParams.page ?? "1");
|
||||
|
||||
const eoas =
|
||||
vaultClient && managementAccessToken
|
||||
? await listEoas({
|
||||
client: vaultClient,
|
||||
request: {
|
||||
auth: {
|
||||
accessToken: managementAccessToken,
|
||||
},
|
||||
options: {
|
||||
page: currentPage - 1,
|
||||
// @ts-expect-error - TODO: fix this
|
||||
page_size: pageSize,
|
||||
},
|
||||
},
|
||||
})
|
||||
: { data: { items: [], totalRecords: 0 }, error: null, success: true };
|
||||
|
||||
const serverWallets = eoas.data?.items as Wallet[] | undefined;
|
||||
|
||||
const client = getClientThirdwebClient({
|
||||
jwt: authToken,
|
||||
teamId: project.teamId,
|
||||
@@ -103,12 +143,34 @@ export default async function Page(props: {
|
||||
authToken={authToken}
|
||||
/>
|
||||
|
||||
<InAppWalletUsersPageContent
|
||||
authToken={authToken}
|
||||
client={client}
|
||||
projectClientId={project.publishableKey}
|
||||
teamId={project.teamId}
|
||||
/>
|
||||
{/* Server Wallets Section */}
|
||||
<div className="flex flex-col gap-4">
|
||||
{eoas.error ? null : (
|
||||
<ServerWalletsTable
|
||||
client={client}
|
||||
currentPage={currentPage}
|
||||
managementAccessToken={managementAccessToken ?? undefined}
|
||||
project={project}
|
||||
teamSlug={params.team_slug}
|
||||
totalPages={Math.ceil(eoas.data.totalRecords / pageSize)}
|
||||
totalRecords={eoas.data.totalRecords}
|
||||
wallets={serverWallets ?? []}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* User Wallets Section */}
|
||||
<div className="flex flex-col gap-4">
|
||||
<h2 className="font-semibold text-2xl tracking-tight">
|
||||
User wallets
|
||||
</h2>
|
||||
<InAppWalletUsersPageContent
|
||||
authToken={authToken}
|
||||
client={client}
|
||||
projectClientId={project.publishableKey}
|
||||
teamId={project.teamId}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ProjectPage>
|
||||
</ResponsiveSearchParamsProvider>
|
||||
|
||||
+2
@@ -30,11 +30,13 @@ function unclaimedFeesStub(token0Amount: bigint, token1Amount: bigint) {
|
||||
address: "0x1234567890123456789012345678901234567890",
|
||||
amount: token0Amount,
|
||||
symbol: "FOO",
|
||||
decimals: 18,
|
||||
},
|
||||
token1: {
|
||||
address: "0x0987654321098765432109876543210987654321",
|
||||
amount: token1Amount,
|
||||
symbol: "BAR",
|
||||
decimals: 18,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+7
-1
@@ -29,11 +29,13 @@ export function ClaimRewardsPage(props: {
|
||||
address: string;
|
||||
amount: bigint;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
token1: {
|
||||
address: string;
|
||||
amount: bigint;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
};
|
||||
chainSlug: string;
|
||||
@@ -98,11 +100,13 @@ export function ClaimRewardsPageUI(props: {
|
||||
address: string;
|
||||
amount: bigint;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
token1: {
|
||||
address: string;
|
||||
amount: bigint;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
};
|
||||
recipient: string;
|
||||
@@ -275,6 +279,7 @@ function TokenReward(props: {
|
||||
address: string;
|
||||
amount: bigint;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
client: ThirdwebClient;
|
||||
chain: Chain;
|
||||
@@ -303,7 +308,8 @@ function TokenReward(props: {
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
<p className="font-bold text-sm">
|
||||
{toTokens(props.token.amount, 18)} {props.token.symbol}
|
||||
{toTokens(props.token.amount, props.token.decimals)}{" "}
|
||||
{props.token.symbol}
|
||||
</p>
|
||||
<Link
|
||||
target="_blank"
|
||||
|
||||
+2
@@ -31,6 +31,7 @@ export default async function Page(props: {
|
||||
const chain = info.clientContract.chain;
|
||||
const assetContractServer = info.serverContract;
|
||||
const serverClient = assetContractServer.client;
|
||||
const chainMetadata = info.chainMetadata;
|
||||
|
||||
const { address: entrypointContractAddress } =
|
||||
await getDeployedEntrypointERC20({
|
||||
@@ -56,6 +57,7 @@ export default async function Page(props: {
|
||||
|
||||
// Note: must use server contract/client here
|
||||
const unclaimedFees = await getUnclaimedFees({
|
||||
chainMetadata,
|
||||
positionManager: getContract({
|
||||
address: reward.positionManager,
|
||||
chain,
|
||||
|
||||
+47
-17
@@ -1,11 +1,14 @@
|
||||
import type { ThirdwebContract } from "thirdweb";
|
||||
import { getContract, readContract } from "thirdweb";
|
||||
import { getAddress, getContract, readContract, ZERO_ADDRESS } from "thirdweb";
|
||||
import type { ChainMetadata } from "thirdweb/chains";
|
||||
import { symbol } from "thirdweb/extensions/common";
|
||||
import { decimals } from "thirdweb/extensions/erc20";
|
||||
|
||||
const maxUint128 = 2n ** 128n - 1n;
|
||||
|
||||
export async function getUnclaimedFees(params: {
|
||||
positionManager: ThirdwebContract;
|
||||
chainMetadata: ChainMetadata;
|
||||
reward: {
|
||||
tokenId: bigint;
|
||||
recipient: string;
|
||||
@@ -56,33 +59,60 @@ export async function getUnclaimedFees(params: {
|
||||
const token0Address = positionsResult[2];
|
||||
const token1Address = positionsResult[3];
|
||||
|
||||
const [token0Symbol, token1Symbol] = await Promise.all([
|
||||
symbol({
|
||||
contract: getContract({
|
||||
address: token0Address,
|
||||
chain,
|
||||
client,
|
||||
}),
|
||||
}),
|
||||
symbol({
|
||||
contract: getContract({
|
||||
address: token1Address,
|
||||
chain,
|
||||
client,
|
||||
}),
|
||||
}),
|
||||
]);
|
||||
const token0Contract = getContract({
|
||||
address: token0Address,
|
||||
chain,
|
||||
client,
|
||||
});
|
||||
|
||||
const token1Contract = getContract({
|
||||
address: token1Address,
|
||||
chain,
|
||||
client,
|
||||
});
|
||||
|
||||
const isToken0Native = getAddress(token0Address) === getAddress(ZERO_ADDRESS);
|
||||
const isToken1Native = getAddress(token1Address) === getAddress(ZERO_ADDRESS);
|
||||
|
||||
const nativeSymbol = params.chainMetadata.nativeCurrency.symbol;
|
||||
const nativeDecimals = params.chainMetadata.nativeCurrency.decimals;
|
||||
|
||||
const [token0Symbol, token1Symbol, token0Decimals, token1Decimals] =
|
||||
await Promise.all([
|
||||
isToken0Native
|
||||
? nativeSymbol
|
||||
: symbol({
|
||||
contract: token0Contract,
|
||||
}),
|
||||
isToken1Native
|
||||
? nativeSymbol
|
||||
: symbol({
|
||||
contract: token1Contract,
|
||||
}),
|
||||
isToken0Native
|
||||
? nativeDecimals
|
||||
: decimals({
|
||||
contract: token0Contract,
|
||||
}),
|
||||
isToken1Native
|
||||
? nativeDecimals
|
||||
: decimals({
|
||||
contract: token1Contract,
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
token0: {
|
||||
address: token0Address,
|
||||
amount: collectResult[0],
|
||||
symbol: token0Symbol,
|
||||
decimals: token0Decimals,
|
||||
},
|
||||
token1: {
|
||||
address: token1Address,
|
||||
amount: collectResult[1],
|
||||
symbol: token1Symbol,
|
||||
decimals: token1Decimals,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export function UniversalBridgeEmbed({
|
||||
buyAmount={amount}
|
||||
tokenAddress={token?.address}
|
||||
pageType="bridge"
|
||||
isTestnet={chain.testnet}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import { bridgeAppThirdwebClient } from "./constants";
|
||||
|
||||
const title = "thirdweb Bridge: Buy, Bridge & Swap Crypto on 85+ Chains";
|
||||
const description =
|
||||
"Bridge, swap, and on-ramp across 9M+ token routes on 85+ chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing and near-instant fast finality";
|
||||
"Bridge and swap 3,200+ tokens across 85+ chains (Ethereum, Base, Optimism, Arbitrum, BNB & more). Best-price routing with near-instant finality";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
description,
|
||||
@@ -105,8 +105,7 @@ export default async function BridgePage({
|
||||
href="https://portal.thirdweb.com/bridge"
|
||||
linkType="integrate-bridge"
|
||||
>
|
||||
Integrate Bridge in your apps in minutes, and start generating
|
||||
revenue
|
||||
Accept Payments in Any Token Right Inside Your App
|
||||
</PillLink>
|
||||
|
||||
<PillLink
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ShieldCheckIcon } from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { Bridge, defineChain, toTokens } from "thirdweb";
|
||||
import { getChainMetadata } from "thirdweb/chains";
|
||||
import { shortenAddress } from "thirdweb/utils";
|
||||
@@ -80,131 +81,137 @@ export default async function PayPage({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex z-10 flex-col lg:flex-row h-full w-full">
|
||||
<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">
|
||||
<div>
|
||||
<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"
|
||||
/>
|
||||
<ThemeProvider
|
||||
forcedTheme={theme === "light" ? "light" : "dark"}
|
||||
attribute="class"
|
||||
disableTransitionOnChange
|
||||
enableSystem={false}
|
||||
>
|
||||
<div className="flex z-10 flex-col lg:flex-row h-full w-full">
|
||||
<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">
|
||||
<div>
|
||||
<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>
|
||||
)}
|
||||
<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">
|
||||
{paymentLink.amount && (
|
||||
<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="hidden lg:block my-4 w-full">
|
||||
{paymentLink.amount && (
|
||||
<div className="flex flex-col gap-1 w-full my-4">
|
||||
<span className="text-muted-foreground text-xs">Seller</span>
|
||||
<span className="text-muted-foreground text-xs">Details</span>
|
||||
<div className="font-medium flex-row flex justify-between items-center w-full">
|
||||
{recipientEnsOrAddress.ensName ??
|
||||
shortenAddress(recipientEnsOrAddress.address)}
|
||||
<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>
|
||||
))}
|
||||
</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
|
||||
amount={paymentLink.amount ? BigInt(paymentLink.amount) : undefined}
|
||||
chainId={Number(paymentLink.destinationToken.chainId)}
|
||||
clientId={undefined} // Payment links don't need to use the same client ID to be executed
|
||||
image={paymentLink.imageUrl}
|
||||
name={paymentLink.title}
|
||||
paymentLinkId={id}
|
||||
purchaseData={paymentLink.purchaseData}
|
||||
recipientAddress={paymentLink.receiver}
|
||||
redirectUri={redirectUri}
|
||||
theme={theme}
|
||||
token={token}
|
||||
/>
|
||||
</main>
|
||||
</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
|
||||
amount={paymentLink.amount ? BigInt(paymentLink.amount) : undefined}
|
||||
chainId={Number(paymentLink.destinationToken.chainId)}
|
||||
clientId={undefined} // Payment links don't need to use the same client ID to be executed
|
||||
image={paymentLink.imageUrl}
|
||||
name={paymentLink.title}
|
||||
paymentLinkId={id}
|
||||
purchaseData={paymentLink.purchaseData}
|
||||
recipientAddress={paymentLink.receiver}
|
||||
redirectUri={redirectUri}
|
||||
token={token}
|
||||
/>
|
||||
</main>
|
||||
</div>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client";
|
||||
import { payAppThirdwebClient } from "app/pay/constants";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect } from "react";
|
||||
import { createThirdwebClient, NATIVE_TOKEN_ADDRESS, toTokens } from "thirdweb";
|
||||
import { AutoConnect, CheckoutWidget } from "thirdweb/react";
|
||||
import { checksumAddress } from "thirdweb/utils";
|
||||
@@ -11,6 +10,7 @@ import {
|
||||
reportPaymentLinkBuySuccessful,
|
||||
} from "@/analytics/report";
|
||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||
|
||||
export function PayPageWidget({
|
||||
chainId,
|
||||
@@ -21,7 +21,6 @@ export function PayPageWidget({
|
||||
name,
|
||||
image,
|
||||
redirectUri,
|
||||
theme,
|
||||
purchaseData,
|
||||
clientId,
|
||||
}: {
|
||||
@@ -34,17 +33,10 @@ export function PayPageWidget({
|
||||
image?: string;
|
||||
redirectUri?: string;
|
||||
clientId: string | undefined;
|
||||
theme?: "light" | "dark";
|
||||
purchaseData: Record<string, unknown> | undefined;
|
||||
}) {
|
||||
const { theme: browserTheme, setTheme } = useTheme();
|
||||
const { theme } = useTheme();
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
useEffect(() => {
|
||||
if (theme) {
|
||||
setTheme(theme);
|
||||
}
|
||||
}, [theme, setTheme]);
|
||||
const chain = useV5DashboardChain(chainId);
|
||||
|
||||
return (
|
||||
@@ -55,6 +47,7 @@ export function PayPageWidget({
|
||||
}
|
||||
/>
|
||||
<CheckoutWidget
|
||||
theme={getSDKTheme(theme === "light" ? "light" : "dark")}
|
||||
connectOptions={{
|
||||
wallets: [
|
||||
createWallet("io.metamask"),
|
||||
@@ -87,7 +80,6 @@ export function PayPageWidget({
|
||||
paymentLinkId={paymentLinkId}
|
||||
purchaseData={purchaseData}
|
||||
seller={checksumAddress(recipientAddress)}
|
||||
theme={theme ?? (browserTheme === "light" ? "light" : "dark")}
|
||||
tokenAddress={
|
||||
token.address === NATIVE_TOKEN_ADDRESS
|
||||
? undefined
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import "@workspace/ui/global.css";
|
||||
import { Inter } from "next/font/google";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { PayProviders } from "./components/client/Providers.client";
|
||||
|
||||
@@ -24,16 +23,9 @@ export default async function PayLayout({
|
||||
)}
|
||||
>
|
||||
<PayProviders>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="dark"
|
||||
disableTransitionOnChange
|
||||
enableSystem={false}
|
||||
>
|
||||
<div className="relative mx-auto flex h-full w-full items-center justify-center overflow-x-hidden overflow-y-scroll">
|
||||
{children}
|
||||
</div>
|
||||
</ThemeProvider>
|
||||
<div className="relative mx-auto flex h-full w-full items-center justify-center overflow-x-hidden overflow-y-scroll">
|
||||
{children}
|
||||
</div>
|
||||
</PayProviders>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { createThirdwebClient, defineChain, getContract } from "thirdweb";
|
||||
import { getCurrencyMetadata } from "thirdweb/extensions/erc20";
|
||||
import { checksumAddress } from "thirdweb/utils";
|
||||
@@ -33,7 +34,16 @@ export default async function PayPage({
|
||||
!params.tokenAddress &&
|
||||
!params.amount
|
||||
) {
|
||||
return <PaymentLinkForm />;
|
||||
return (
|
||||
<ThemeProvider
|
||||
forcedTheme={params.theme === "light" ? "light" : "dark"}
|
||||
attribute="class"
|
||||
disableTransitionOnChange
|
||||
enableSystem={false}
|
||||
>
|
||||
<PaymentLinkForm />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// Validate query parameters
|
||||
@@ -84,17 +94,23 @@ export default async function PayPage({
|
||||
};
|
||||
|
||||
return (
|
||||
<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}
|
||||
theme={params.theme}
|
||||
token={token}
|
||||
/>
|
||||
<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}
|
||||
/>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,20 @@ import { defineDashboardChain } from "@/lib/defineDashboardChain";
|
||||
import { isLoginRequired } from "@/utils/auth";
|
||||
import { LAST_VISITED_TEAM_PAGE_PATH } from "./app/(app)/team/components/last-visited-page/consts";
|
||||
|
||||
type CookiesToSet = Record<
|
||||
string,
|
||||
| [string]
|
||||
| [
|
||||
string,
|
||||
{
|
||||
httpOnly: boolean;
|
||||
sameSite?: "lax" | "strict" | "none";
|
||||
secure: boolean;
|
||||
maxAge: number;
|
||||
},
|
||||
]
|
||||
>;
|
||||
|
||||
// ignore assets, api - only intercept page routes
|
||||
export const config = {
|
||||
matcher: [
|
||||
@@ -24,12 +38,12 @@ export const config = {
|
||||
};
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
const { pathname, searchParams } = request.nextUrl;
|
||||
|
||||
// nebula subdomain handling
|
||||
const paths = pathname.slice(1).split("/");
|
||||
|
||||
let cookiesToSet: Record<string, string> | undefined;
|
||||
let cookiesToSet: CookiesToSet = {};
|
||||
|
||||
const activeAccount = request.cookies.get(COOKIE_ACTIVE_ACCOUNT)?.value;
|
||||
const authCookie = activeAccount
|
||||
@@ -56,12 +70,27 @@ export async function middleware(request: NextRequest) {
|
||||
cookiesToSet = {};
|
||||
}
|
||||
|
||||
cookiesToSet[key] = value;
|
||||
cookiesToSet[key] = [value];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handle gclid (if it exists in search params)
|
||||
const gclid = searchParams.get("gclid");
|
||||
if (gclid) {
|
||||
cookiesToSet.gclid = [
|
||||
gclid,
|
||||
{
|
||||
// TODO: define conversion window, for now 7d should do fine
|
||||
maxAge: 7 * 24 * 60 * 60,
|
||||
httpOnly: false,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// logged in paths
|
||||
if (isLoginRequired(pathname)) {
|
||||
// check if the user is logged in (has a valid auth cookie)
|
||||
@@ -146,7 +175,7 @@ export async function middleware(request: NextRequest) {
|
||||
if (cookiesToSet) {
|
||||
const defaultResponse = NextResponse.next();
|
||||
for (const entry of Object.entries(cookiesToSet)) {
|
||||
defaultResponse.cookies.set(entry[0], entry[1]);
|
||||
defaultResponse.cookies.set(entry[0], entry[1][0], entry[1][1]);
|
||||
}
|
||||
|
||||
return defaultResponse;
|
||||
@@ -162,7 +191,7 @@ function isPossibleAddressOrENSName(address: string) {
|
||||
function rewrite(
|
||||
request: NextRequest,
|
||||
relativePath: string,
|
||||
cookiesToSet: Record<string, string> | undefined,
|
||||
cookiesToSet: CookiesToSet,
|
||||
) {
|
||||
const url = request.nextUrl.clone();
|
||||
url.pathname = relativePath;
|
||||
@@ -170,7 +199,7 @@ function rewrite(
|
||||
|
||||
if (cookiesToSet) {
|
||||
for (const entry of Object.entries(cookiesToSet)) {
|
||||
res.cookies.set(entry[0], entry[1]);
|
||||
res.cookies.set(entry[0], entry[1][0], entry[1][1]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +213,7 @@ function redirect(
|
||||
| {
|
||||
searchParams?: string;
|
||||
permanent?: boolean;
|
||||
cookiesToSet?: Record<string, string> | undefined;
|
||||
cookiesToSet?: CookiesToSet;
|
||||
}
|
||||
| undefined,
|
||||
) {
|
||||
@@ -196,7 +225,7 @@ function redirect(
|
||||
|
||||
if (options?.cookiesToSet) {
|
||||
for (const entry of Object.entries(options.cookiesToSet)) {
|
||||
res.cookies.set(entry[0], entry[1]);
|
||||
res.cookies.set(entry[0], entry[1][0], entry[1][1]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,15 @@ const baseNextConfig: NextConfig = {
|
||||
},
|
||||
productionBrowserSourceMaps: false,
|
||||
reactStrictMode: true,
|
||||
async redirects() {
|
||||
return [
|
||||
{
|
||||
source: "/:path*",
|
||||
destination: "https://thirdweb.com/ai",
|
||||
permanent: true,
|
||||
},
|
||||
];
|
||||
},
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -76,7 +76,7 @@ export function ChatContainer() {
|
||||
return (
|
||||
<Reasoning
|
||||
key={`${message.id}-reasoning-${i}`}
|
||||
className="w-full"
|
||||
className="w-full max-w-md"
|
||||
isStreaming={status === "streaming"}
|
||||
>
|
||||
<ReasoningTrigger />
|
||||
|
||||
@@ -1,10 +1,90 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
import { createThirdwebClient, defineChain } from "thirdweb";
|
||||
import { toUnits } from "thirdweb/utils";
|
||||
import { facilitator, settlePayment } from "thirdweb/x402";
|
||||
import { token } from "../../payments/x402/components/constants";
|
||||
|
||||
// Allow streaming responses up to 5 minutes
|
||||
export const maxDuration = 300;
|
||||
|
||||
export async function GET(_req: Request) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Payment successful. You have accessed the protected route.",
|
||||
export async function GET(request: NextRequest) {
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY as string,
|
||||
});
|
||||
|
||||
const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_WALLET as string;
|
||||
// const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_SMART_WALLET as string;
|
||||
const ENGINE_VAULT_ACCESS_TOKEN = process.env
|
||||
.ENGINE_VAULT_ACCESS_TOKEN as string;
|
||||
const API_URL = `https://${process.env.NEXT_PUBLIC_API_URL || "api.thirdweb.com"}`;
|
||||
|
||||
const twFacilitator = facilitator({
|
||||
baseUrl: `${API_URL}/v1/payments/x402`,
|
||||
client,
|
||||
serverWalletAddress: BACKEND_WALLET_ADDRESS,
|
||||
vaultAccessToken: ENGINE_VAULT_ACCESS_TOKEN,
|
||||
});
|
||||
|
||||
const paymentData = request.headers.get("X-PAYMENT");
|
||||
const queryParams = request.nextUrl.searchParams;
|
||||
|
||||
const chainId = queryParams.get("chainId");
|
||||
|
||||
if (!chainId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing required parameters" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const amount = queryParams.get("amount") || "0.01";
|
||||
const tokenAddress = queryParams.get("tokenAddress") || token.address;
|
||||
const decimals = queryParams.get("decimals") || token.decimals.toString();
|
||||
const waitUntil =
|
||||
(queryParams.get("waitUntil") as "simulated" | "submitted" | "confirmed") ||
|
||||
"simulated";
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl: "https://playground-web.thirdweb.com/api/paywall",
|
||||
method: "GET",
|
||||
paymentData,
|
||||
network: defineChain(Number(chainId)),
|
||||
price: {
|
||||
amount: toUnits(amount, parseInt(decimals)).toString(),
|
||||
asset: {
|
||||
address: tokenAddress as `0x${string}`,
|
||||
decimals: decimals ? parseInt(decimals) : token.decimals,
|
||||
},
|
||||
},
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
},
|
||||
waitUntil,
|
||||
facilitator: twFacilitator,
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// payment successful, execute the request
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: "Payment successful. You have accessed the protected route.",
|
||||
payment: {
|
||||
amount,
|
||||
tokenAddress,
|
||||
},
|
||||
receipt: result.paymentReceipt,
|
||||
},
|
||||
{
|
||||
status: 200,
|
||||
headers: result.responseHeaders,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// otherwise, request payment
|
||||
return NextResponse.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ const defaultOptions: BridgeComponentsPlaygroundOptions = {
|
||||
sellerAddress: "0x0000000000000000000000000000000000000000",
|
||||
title: "",
|
||||
transactionData: "",
|
||||
receiverAddress: undefined,
|
||||
currency: "USD",
|
||||
showThirdwebBranding: true,
|
||||
},
|
||||
|
||||
@@ -118,8 +118,12 @@ tokenId: 2n,
|
||||
tokenAddress: options.payOptions.buyTokenAddress
|
||||
? quotes(options.payOptions.buyTokenAddress)
|
||||
: undefined,
|
||||
seller: options.payOptions.sellerAddress
|
||||
? quotes(options.payOptions.sellerAddress)
|
||||
seller:
|
||||
widget === "checkout"
|
||||
? quotes(options.payOptions.sellerAddress)
|
||||
: undefined,
|
||||
receiverAddress: options.payOptions.receiverAddress
|
||||
? quotes(options.payOptions.receiverAddress)
|
||||
: undefined,
|
||||
buttonLabel: options.payOptions.buttonLabel
|
||||
? quotes(options.payOptions.buttonLabel)
|
||||
|
||||
@@ -140,6 +140,7 @@ export function LeftSection(props: {
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Token</Label>
|
||||
<TokenSelector
|
||||
disableAddress
|
||||
chainId={selectedChain}
|
||||
client={THIRDWEB_CLIENT}
|
||||
enabled={true}
|
||||
@@ -154,10 +155,10 @@ export function LeftSection(props: {
|
||||
)}
|
||||
|
||||
{/* Mode-specific form fields */}
|
||||
<div className="my-2">
|
||||
<div className="">
|
||||
{/* Buy Mode - Amount and Payment Methods */}
|
||||
{props.widget === "buy" && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={buyTokenAmountId}>Amount</Label>
|
||||
<Input
|
||||
@@ -177,6 +178,30 @@ export function LeftSection(props: {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{props.widget === "buy" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="receiver-address">Receiver Address</Label>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Receive the tokens in a different wallet address
|
||||
</p>
|
||||
<Input
|
||||
className="bg-card"
|
||||
id="receiver-address"
|
||||
onChange={(e) => {
|
||||
setOptions((v) => ({
|
||||
...v,
|
||||
payOptions: {
|
||||
...v.payOptions,
|
||||
receiverAddress: e.target.value as Address,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
placeholder="0x..."
|
||||
value={payOptions.receiverAddress || ""}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Payment Methods */}
|
||||
<div className="flex flex-col gap-3">
|
||||
<Label>Payment Methods</Label>
|
||||
@@ -206,6 +231,7 @@ export function LeftSection(props: {
|
||||
/>
|
||||
<Label htmlFor={cryptoPaymentId}>Crypto</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
checked={payOptions.paymentMethods.includes("card")}
|
||||
@@ -257,7 +283,6 @@ export function LeftSection(props: {
|
||||
value={payOptions.sellerAddress || ""}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={paymentAmountId}>Price</Label>
|
||||
<Input
|
||||
|
||||
@@ -67,6 +67,12 @@ export function RightSection(props: {
|
||||
tokenAddress={props.options.payOptions.buyTokenAddress}
|
||||
currency={props.options.payOptions.currency}
|
||||
showThirdwebBranding={props.options.payOptions.showThirdwebBranding}
|
||||
receiverAddress={props.options.payOptions.receiverAddress}
|
||||
key={JSON.stringify({
|
||||
amount: props.options.payOptions.buyTokenAmount,
|
||||
chain: props.options.payOptions.buyTokenChain,
|
||||
tokenAddress: props.options.payOptions.buyTokenAddress,
|
||||
})}
|
||||
{...(props.options.payOptions.buttonLabel && {
|
||||
buttonLabel: props.options.payOptions.buttonLabel,
|
||||
})}
|
||||
@@ -89,7 +95,6 @@ export function RightSection(props: {
|
||||
}
|
||||
name={props.options.payOptions.title || "Your Product Name"}
|
||||
paymentMethods={props.options.payOptions.paymentMethods}
|
||||
presetOptions={[1, 2, 3]}
|
||||
seller={props.options.payOptions.sellerAddress}
|
||||
theme={themeObj}
|
||||
tokenAddress={props.options.payOptions.buyTokenAddress}
|
||||
|
||||
@@ -48,6 +48,7 @@ export type BridgeComponentsPlaygroundOptions = {
|
||||
|
||||
// direct_payment mode options
|
||||
sellerAddress: Address;
|
||||
receiverAddress: Address | undefined;
|
||||
|
||||
// transaction mode options
|
||||
transactionData?: string; // Simplified for demo; could be more complex in real implementation
|
||||
|
||||
@@ -17,6 +17,7 @@ const defaultOptions: BridgeComponentsPlaygroundOptions = {
|
||||
paymentMethods: ["crypto", "card"],
|
||||
sellerAddress: "0x0000000000000000000000000000000000000000",
|
||||
title: "",
|
||||
receiverAddress: undefined,
|
||||
transactionData: "",
|
||||
currency: "USD",
|
||||
showThirdwebBranding: true,
|
||||
|
||||
@@ -20,6 +20,7 @@ const defaultOptions: BridgeComponentsPlaygroundOptions = {
|
||||
transactionData: "",
|
||||
currency: "USD",
|
||||
showThirdwebBranding: true,
|
||||
receiverAddress: undefined,
|
||||
},
|
||||
theme: {
|
||||
darkColorOverrides: {},
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { useId, useState } from "react";
|
||||
import { defineChain } from "thirdweb/chains";
|
||||
import { BridgeNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { TokenSelector } from "@/components/ui/TokenSelector";
|
||||
import { THIRDWEB_CLIENT } from "@/lib/client";
|
||||
import type { TokenMetadata } from "@/lib/types";
|
||||
import type { X402PlaygroundOptions } from "./types";
|
||||
|
||||
export function X402LeftSection(props: {
|
||||
options: X402PlaygroundOptions;
|
||||
setOptions: React.Dispatch<React.SetStateAction<X402PlaygroundOptions>>;
|
||||
}) {
|
||||
const { options, setOptions } = props;
|
||||
|
||||
// Local state for chain and token selection
|
||||
const [selectedChain, setSelectedChain] = useState<number | undefined>(() => {
|
||||
return options.chain?.id;
|
||||
});
|
||||
|
||||
const [selectedToken, setSelectedToken] = useState<
|
||||
{ chainId: number; address: string } | undefined
|
||||
>(() => {
|
||||
if (options.tokenAddress && options.chain?.id) {
|
||||
return {
|
||||
address: options.tokenAddress,
|
||||
chainId: options.chain.id,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const chainId = useId();
|
||||
const tokenId = useId();
|
||||
const amountId = useId();
|
||||
const waitUntilId = useId();
|
||||
|
||||
const handleChainChange = (chainId: number) => {
|
||||
setSelectedChain(chainId);
|
||||
// Clear token selection when chain changes
|
||||
setSelectedToken(undefined);
|
||||
|
||||
setOptions((v) => ({
|
||||
...v,
|
||||
chain: defineChain(chainId),
|
||||
tokenAddress: "0x0000000000000000000000000000000000000000" as const,
|
||||
tokenSymbol: "",
|
||||
tokenDecimals: 18,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleTokenChange = (token: TokenMetadata) => {
|
||||
setSelectedToken({
|
||||
address: token.address,
|
||||
chainId: selectedChain!,
|
||||
});
|
||||
|
||||
setOptions((v) => ({
|
||||
...v,
|
||||
tokenAddress: token.address as `0x${string}`,
|
||||
tokenSymbol: token.symbol ?? "",
|
||||
tokenDecimals: token.decimals ?? 18,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setOptions((v) => ({
|
||||
...v,
|
||||
amount: e.target.value,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleWaitUntilChange = (
|
||||
value: "simulated" | "submitted" | "confirmed",
|
||||
) => {
|
||||
setOptions((v) => ({
|
||||
...v,
|
||||
waitUntil: value,
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="mb-4 text-xl font-semibold">Configuration</h2>
|
||||
<div className="space-y-4">
|
||||
{/* Chain selection */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={chainId}>Chain</Label>
|
||||
<BridgeNetworkSelector
|
||||
chainId={selectedChain}
|
||||
onChange={handleChainChange}
|
||||
placeholder="Select a chain"
|
||||
className="bg-card"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Token selection - only show if chain is selected */}
|
||||
{selectedChain && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={tokenId}>Token</Label>
|
||||
<TokenSelector
|
||||
chainId={selectedChain}
|
||||
client={THIRDWEB_CLIENT}
|
||||
enabled={true}
|
||||
onChange={handleTokenChange}
|
||||
placeholder="Select a token"
|
||||
selectedToken={selectedToken}
|
||||
className="bg-card"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Amount input */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={amountId}>Amount</Label>
|
||||
<Input
|
||||
id={amountId}
|
||||
type="text"
|
||||
placeholder="0.01"
|
||||
value={options.amount}
|
||||
onChange={handleAmountChange}
|
||||
className="bg-card"
|
||||
/>
|
||||
{options.tokenSymbol && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Amount in {options.tokenSymbol}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Wait Until selection */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor={waitUntilId}>Wait Until</Label>
|
||||
<Select
|
||||
value={options.waitUntil}
|
||||
onValueChange={handleWaitUntilChange}
|
||||
>
|
||||
<SelectTrigger className="bg-card">
|
||||
<SelectValue placeholder="Select wait condition" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="simulated">Simulated</SelectItem>
|
||||
<SelectItem value="submitted">Submitted</SelectItem>
|
||||
<SelectItem value="confirmed">Confirmed</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
When to consider the payment settled: simulated (fastest),
|
||||
submitted (medium), or confirmed (most secure)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useActiveAccount } from "thirdweb/react";
|
||||
import { chain, token } from "./constants";
|
||||
import type { X402PlaygroundOptions } from "./types";
|
||||
import { X402LeftSection } from "./X402LeftSection";
|
||||
import { X402RightSection } from "./X402RightSection";
|
||||
|
||||
const defaultOptions: X402PlaygroundOptions = {
|
||||
chain: chain,
|
||||
tokenAddress: token.address as `0x${string}`,
|
||||
tokenSymbol: token.symbol,
|
||||
tokenDecimals: token.decimals,
|
||||
amount: "0.01",
|
||||
payTo: "0x0000000000000000000000000000000000000000",
|
||||
waitUntil: "simulated",
|
||||
};
|
||||
|
||||
export function X402Playground() {
|
||||
const [options, setOptions] = useState<X402PlaygroundOptions>(defaultOptions);
|
||||
const activeAccount = useActiveAccount();
|
||||
|
||||
// Update payTo address when wallet connects, but only if it's still the default
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
activeAccount?.address &&
|
||||
options.payTo === "0x0000000000000000000000000000000000000000"
|
||||
) {
|
||||
setOptions((prev) => ({
|
||||
...prev,
|
||||
payTo: activeAccount.address as `0x${string}`,
|
||||
}));
|
||||
}
|
||||
}, [activeAccount?.address, options.payTo]);
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-col-reverse gap-6 xl:min-h-[900px] xl:flex-row xl:gap-6">
|
||||
<div className="grow border-b pb-10 xl:mb-0 xl:border-r xl:border-b-0 xl:pr-6">
|
||||
<X402LeftSection options={options} setOptions={setOptions} />
|
||||
</div>
|
||||
<X402RightSection options={options} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { CodeClient } from "@workspace/ui/components/code/code.client";
|
||||
import { CodeIcon, LockIcon } from "lucide-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
ConnectButton,
|
||||
useActiveAccount,
|
||||
useActiveWallet,
|
||||
} from "thirdweb/react";
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { THIRDWEB_CLIENT } from "@/lib/client";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { X402PlaygroundOptions } from "./types";
|
||||
|
||||
type Tab = "ui" | "client-code" | "server-code";
|
||||
|
||||
export function X402RightSection(props: { options: X402PlaygroundOptions }) {
|
||||
const pathname = usePathname();
|
||||
const [previewTab, _setPreviewTab] = useState<Tab>(() => {
|
||||
return "ui";
|
||||
});
|
||||
|
||||
function setPreviewTab(tab: "ui" | "client-code" | "server-code") {
|
||||
_setPreviewTab(tab);
|
||||
window.history.replaceState({}, "", `${pathname}?tab=${tab}`);
|
||||
}
|
||||
|
||||
const activeWallet = useActiveWallet();
|
||||
const activeAccount = useActiveAccount();
|
||||
|
||||
const paidApiCall = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!activeWallet) {
|
||||
throw new Error("No active wallet");
|
||||
}
|
||||
const fetchWithPay = wrapFetchWithPayment(
|
||||
fetch,
|
||||
THIRDWEB_CLIENT,
|
||||
activeWallet,
|
||||
BigInt(1 * 10 ** 18),
|
||||
);
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("chainId", props.options.chain.id.toString());
|
||||
searchParams.set("payTo", props.options.payTo);
|
||||
searchParams.set("amount", props.options.amount);
|
||||
searchParams.set("tokenAddress", props.options.tokenAddress);
|
||||
searchParams.set("decimals", props.options.tokenDecimals.toString());
|
||||
searchParams.set("waitUntil", props.options.waitUntil);
|
||||
|
||||
const url =
|
||||
"/api/paywall" +
|
||||
(searchParams.size > 0 ? "?" + searchParams.toString() : "");
|
||||
const response = await fetchWithPay(url.toString());
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
|
||||
const handlePayClick = async () => {
|
||||
paidApiCall.mutate();
|
||||
};
|
||||
|
||||
const clientCode = `import { createThirdwebClient } from "thirdweb";
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
import { useActiveWallet } from "thirdweb/react";
|
||||
|
||||
const client = createThirdwebClient({ clientId: "your-client-id" });
|
||||
|
||||
export default function Page() {
|
||||
const wallet = useActiveWallet();
|
||||
|
||||
const onClick = async () => {
|
||||
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
|
||||
const response = await fetchWithPay('/api/paid-endpoint');
|
||||
}
|
||||
|
||||
return (
|
||||
<Button onClick={onClick}>Pay Now</Button>
|
||||
);
|
||||
}`;
|
||||
|
||||
const serverCode = `// Usage in a Next.js API route
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { defineChain } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0xYourServerWalletAddress",
|
||||
waitUtil: "${props.options.waitUntil}",
|
||||
});
|
||||
|
||||
export async function POST(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: "POST",
|
||||
paymentData,
|
||||
payTo: "${props.options.payTo}",
|
||||
network: defineChain(${props.options.chain.id}),
|
||||
price: {
|
||||
amount: "${Number(props.options.amount) * 10 ** props.options.tokenDecimals}",
|
||||
asset: {
|
||||
address: "${props.options.tokenAddress}",
|
||||
},
|
||||
},
|
||||
facilitator: thirdwebFacilitator,
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
}`;
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 flex-col gap-4 xl:sticky xl:top-0 xl:w-[764px]">
|
||||
<TabButtons
|
||||
tabs={[
|
||||
{
|
||||
isActive: previewTab === "ui",
|
||||
name: "UI",
|
||||
onClick: () => setPreviewTab("ui"),
|
||||
},
|
||||
{
|
||||
isActive: previewTab === "client-code",
|
||||
name: "Client Code",
|
||||
onClick: () => setPreviewTab("client-code"),
|
||||
},
|
||||
{
|
||||
isActive: previewTab === "server-code",
|
||||
name: "Server Code",
|
||||
onClick: () => setPreviewTab("server-code"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex min-h-[200px] grow justify-center rounded-lg",
|
||||
previewTab === "ui" && "items-center",
|
||||
)}
|
||||
>
|
||||
<BackgroundPattern />
|
||||
|
||||
{previewTab === "ui" && (
|
||||
<div className="flex flex-col gap-4 w-full p-4 md:p-12 max-w-lg mx-auto">
|
||||
<ConnectButton
|
||||
client={THIRDWEB_CLIENT}
|
||||
chain={props.options.chain}
|
||||
detailsButton={{
|
||||
displayBalanceToken:
|
||||
props.options.tokenAddress !==
|
||||
"0x0000000000000000000000000000000000000000"
|
||||
? {
|
||||
[props.options.chain.id]: props.options.tokenAddress,
|
||||
}
|
||||
: undefined,
|
||||
}}
|
||||
supportedTokens={
|
||||
props.options.tokenAddress !==
|
||||
"0x0000000000000000000000000000000000000000"
|
||||
? {
|
||||
[props.options.chain.id]: [
|
||||
{
|
||||
address: props.options.tokenAddress,
|
||||
symbol: props.options.tokenSymbol,
|
||||
name: props.options.tokenSymbol,
|
||||
},
|
||||
],
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<LockIcon className="w-5 h-5 text-muted-foreground" />
|
||||
<span className="text-lg font-medium">Paid API Call</span>
|
||||
<Badge variant="success">
|
||||
<span className="text-xl font-bold">
|
||||
{props.options.amount}{" "}
|
||||
{props.options.tokenSymbol || "tokens"}
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handlePayClick}
|
||||
className="w-full mb-4"
|
||||
size="lg"
|
||||
disabled={paidApiCall.isPending || !activeAccount}
|
||||
>
|
||||
Access Premium Content
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Pay for access with {props.options.tokenSymbol || "tokens"} on{" "}
|
||||
{props.options.chain.name || `chain ${props.options.chain.id}`}
|
||||
</p>
|
||||
</Card>
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<CodeIcon className="w-5 h-5 text-muted-foreground" />
|
||||
<span className="text-lg font-medium">API Call Response</span>
|
||||
</div>
|
||||
{paidApiCall.isPending && (
|
||||
<div className="text-center">Loading...</div>
|
||||
)}
|
||||
{paidApiCall.isError && (
|
||||
<div className="text-center">
|
||||
Error: {paidApiCall.error.message}
|
||||
</div>
|
||||
)}
|
||||
{paidApiCall.data && (
|
||||
<CodeClient
|
||||
code={JSON.stringify(paidApiCall.data, null, 2)}
|
||||
lang="json"
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{previewTab === "client-code" && (
|
||||
<div className="w-full">
|
||||
<CodeClient
|
||||
className="h-full rounded-none border-none"
|
||||
code={clientCode}
|
||||
lang="tsx"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{previewTab === "server-code" && (
|
||||
<div className="w-full">
|
||||
<CodeClient
|
||||
className="h-full rounded-none border-none"
|
||||
code={serverCode}
|
||||
lang="typescript"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BackgroundPattern() {
|
||||
const color = "hsl(var(--foreground)/15%)";
|
||||
return (
|
||||
<div
|
||||
className="absolute inset-0 z-[-1]"
|
||||
style={{
|
||||
backgroundImage: `radial-gradient(${color} 1px, transparent 1px)`,
|
||||
backgroundSize: "24px 24px",
|
||||
maskImage:
|
||||
"radial-gradient(ellipse 100% 100% at 50% 50%, black 30%, transparent 60%)",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabButtons(props: {
|
||||
tabs: Array<{
|
||||
name: string;
|
||||
isActive: boolean;
|
||||
onClick: () => void;
|
||||
}>;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-start gap-1 rounded-lg border bg-card p-2 shadow-md md:inline-flex">
|
||||
{props.tabs.map((tab) => (
|
||||
<Button
|
||||
className={cn(
|
||||
"gap-2 px-4 text-base",
|
||||
tab.isActive
|
||||
? "bg-accent text-foreground"
|
||||
: "bg-transparent text-muted-foreground",
|
||||
)}
|
||||
key={tab.name}
|
||||
onClick={tab.onClick}
|
||||
variant="ghost"
|
||||
>
|
||||
{tab.name}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
// const chain = arbitrumSepolia;
|
||||
import { base } from "thirdweb/chains";
|
||||
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
import { getDefaultToken } from "thirdweb/react";
|
||||
|
||||
export const chain = arbitrumSepolia;
|
||||
export const token = getDefaultToken(chain, "USDC")!;
|
||||
export const chain = base;
|
||||
export const token = {
|
||||
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
||||
name: "USD Coin",
|
||||
symbol: "USDC",
|
||||
decimals: 6,
|
||||
};
|
||||
// export const chain = base;
|
||||
// export const token = {
|
||||
// address: "0x0578d8A44db98B23BF096A382e016e29a5Ce0ffe",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Chain } from "thirdweb/chains";
|
||||
import type { Address } from "thirdweb/utils";
|
||||
|
||||
export type X402PlaygroundOptions = {
|
||||
chain: Chain;
|
||||
tokenAddress: Address;
|
||||
tokenSymbol: string;
|
||||
tokenDecimals: number;
|
||||
amount: string;
|
||||
payTo: Address;
|
||||
waitUntil: "simulated" | "submitted" | "confirmed";
|
||||
};
|
||||
@@ -1,120 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { Badge } from "@workspace/ui/components/badge";
|
||||
import { CodeClient } from "@workspace/ui/components/code/code.client";
|
||||
import { CodeIcon, LockIcon } from "lucide-react";
|
||||
import {
|
||||
ConnectButton,
|
||||
useActiveAccount,
|
||||
useActiveWallet,
|
||||
} from "thirdweb/react";
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { THIRDWEB_CLIENT } from "../../../../lib/client";
|
||||
import { chain, token } from "./constants";
|
||||
|
||||
export function X402ClientPreview() {
|
||||
const activeWallet = useActiveWallet();
|
||||
const activeAccount = useActiveAccount();
|
||||
const paidApiCall = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!activeWallet) {
|
||||
throw new Error("No active wallet");
|
||||
}
|
||||
const fetchWithPay = wrapFetchWithPayment(
|
||||
fetch,
|
||||
THIRDWEB_CLIENT,
|
||||
activeWallet,
|
||||
BigInt(1 * 10 ** 18),
|
||||
);
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("chainId", chain.id.toString());
|
||||
searchParams.set("payTo", activeWallet.getAccount()?.address || "");
|
||||
// TODO (402): dynamic from playground config
|
||||
// if (token) {
|
||||
// searchParams.set("amount", "0.01");
|
||||
// searchParams.set("tokenAddress", token.address);
|
||||
// searchParams.set("decimals", token.decimals.toString());
|
||||
// }
|
||||
const url =
|
||||
"/api/paywall" +
|
||||
(searchParams.size > 0 ? "?" + searchParams.toString() : "");
|
||||
const response = await fetchWithPay(url.toString());
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
|
||||
const handlePayClick = async () => {
|
||||
paidApiCall.mutate();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 w-full p-4 md:p-12 max-w-lg mx-auto">
|
||||
<ConnectButton
|
||||
client={THIRDWEB_CLIENT}
|
||||
chain={chain}
|
||||
detailsButton={{
|
||||
displayBalanceToken: {
|
||||
[chain.id]: token.address,
|
||||
},
|
||||
}}
|
||||
supportedTokens={{
|
||||
[chain.id]: [token],
|
||||
}}
|
||||
/>
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<LockIcon className="w-5 h-5 text-muted-foreground" />
|
||||
<span className="text-lg font-medium">Paid API Call</span>
|
||||
<Badge variant="success">
|
||||
<span className="text-xl font-bold">0.1 {token.symbol}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handlePayClick}
|
||||
className="w-full mb-4"
|
||||
size="lg"
|
||||
disabled={paidApiCall.isPending || !activeAccount}
|
||||
>
|
||||
Access Premium Content
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Pay for access with {token.symbol} on{" "}
|
||||
{chain.name || `chain ${chain.id}`}
|
||||
</p>
|
||||
{chain.testnet && token.symbol.toLowerCase() === "usdc" && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{" "}
|
||||
<a
|
||||
className="underline"
|
||||
href={"https://faucet.circle.com/"}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Click here to get testnet {token.symbol} on {chain.name}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<CodeIcon className="w-5 h-5 text-muted-foreground" />
|
||||
<span className="text-lg font-medium">API Call Response</span>
|
||||
</div>
|
||||
{paidApiCall.isPending && <div className="text-center">Loading...</div>}
|
||||
{paidApiCall.isError && (
|
||||
<div className="text-center">Error: {paidApiCall.error.message}</div>
|
||||
)}
|
||||
{paidApiCall.data && (
|
||||
<CodeClient
|
||||
code={JSON.stringify(paidApiCall.data, null, 2)}
|
||||
lang="json"
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import { CodeServer } from "@workspace/ui/components/code/code.server";
|
||||
import { CircleDollarSignIcon, Code2Icon } from "lucide-react";
|
||||
import { CodeExample, TabName } from "@/components/code/code-example";
|
||||
import { CircleDollarSignIcon } from "lucide-react";
|
||||
import ThirdwebProvider from "@/components/thirdweb-provider";
|
||||
import { PageLayout } from "../../../components/blocks/APIHeader";
|
||||
import { createMetadata } from "../../../lib/metadata";
|
||||
import { X402ClientPreview } from "./components/x402-client-preview";
|
||||
import { X402Playground } from "./components/X402Playground";
|
||||
|
||||
const title = "x402 Payments";
|
||||
const description =
|
||||
@@ -30,112 +28,8 @@ export default function Page() {
|
||||
description={description}
|
||||
docsLink="https://portal.thirdweb.com/payments/x402?utm_source=playground"
|
||||
>
|
||||
<X402Example />
|
||||
<div className="h-8" />
|
||||
<ServerCodeExample />
|
||||
<X402Playground />
|
||||
</PageLayout>
|
||||
</ThirdwebProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ServerCodeExample() {
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4">
|
||||
<h2 className="font-semibold text-xl tracking-tight">
|
||||
Next.js Server Code Example
|
||||
</h2>
|
||||
<p className="max-w-4xl text-muted-foreground text-balance text-sm md:text-base">
|
||||
Create middleware with the thirdweb facilitator to settle transactions
|
||||
with your server wallet.
|
||||
</p>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-lg border bg-card">
|
||||
<div className="flex grow flex-col border-b md:border-r md:border-b-0">
|
||||
<TabName icon={Code2Icon} name="Server Code" />
|
||||
<CodeServer
|
||||
className="h-full rounded-none border-none"
|
||||
code={`// src/middleware.ts
|
||||
|
||||
import { facilitator, settlePayment } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({ secretKey: "your-secret-key" });
|
||||
const thirdwebX402Facilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0xYourWalletAddress",
|
||||
});
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const method = request.method.toUpperCase();
|
||||
const resourceUrl = request.nextUrl.toString();
|
||||
const paymentData = request.headers.get("X-PAYMENT");
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl,
|
||||
method,
|
||||
paymentData,
|
||||
payTo: "0xYourWalletAddress",
|
||||
network: arbitrumSepolia, // or any other chain
|
||||
price: "$0.01", // can also be a ERC20 token amount
|
||||
facilitator: thirdwebX402Facilitator,
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// payment successful, execute the request
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
// otherwise, request payment
|
||||
return NextResponse.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// Configure which paths the middleware should run on
|
||||
export const config = {
|
||||
matcher: ["/api/paid-endpoint"],
|
||||
};
|
||||
|
||||
`}
|
||||
lang="tsx"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function X402Example() {
|
||||
return (
|
||||
<CodeExample
|
||||
header={{
|
||||
title: "Client Code Example",
|
||||
description:
|
||||
"Wrap your fetch requests with the `wrapFetchWithPayment` function to enable x402 payments.",
|
||||
}}
|
||||
code={`import { createThirdwebClient } from "thirdweb";
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
import { useActiveWallet } from "thirdweb/react";
|
||||
|
||||
const client = createThirdwebClient({ clientId: "your-client-id" });
|
||||
|
||||
export default function Page() {
|
||||
const wallet = useActiveWallet();
|
||||
|
||||
const onClick = async () => {
|
||||
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
|
||||
const response = await fetchWithPay('/api/paid-endpoint');
|
||||
}
|
||||
|
||||
return (
|
||||
<Button onClick={onClick}>Pay Now</Button>
|
||||
);
|
||||
}`}
|
||||
lang="tsx"
|
||||
preview={<X402ClientPreview />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import { type NextRequest, NextResponse } from "next/server";
|
||||
import { createThirdwebClient, defineChain } from "thirdweb";
|
||||
import { facilitator, settlePayment } from "thirdweb/x402";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY as string,
|
||||
});
|
||||
|
||||
const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_WALLET as string;
|
||||
// const BACKEND_WALLET_ADDRESS = process.env.ENGINE_BACKEND_SMART_WALLET as string;
|
||||
const ENGINE_VAULT_ACCESS_TOKEN = process.env
|
||||
.ENGINE_VAULT_ACCESS_TOKEN as string;
|
||||
const API_URL = `https://${process.env.NEXT_PUBLIC_API_URL || "api.thirdweb.com"}`;
|
||||
const twFacilitator = facilitator({
|
||||
baseUrl: `${API_URL}/v1/payments/x402`,
|
||||
client,
|
||||
serverWalletAddress: BACKEND_WALLET_ADDRESS,
|
||||
vaultAccessToken: ENGINE_VAULT_ACCESS_TOKEN,
|
||||
});
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const pathname = request.nextUrl.pathname;
|
||||
const method = request.method.toUpperCase();
|
||||
const resourceUrl = `${request.nextUrl.protocol}//${request.nextUrl.host}${pathname}`;
|
||||
const paymentData = request.headers.get("X-PAYMENT");
|
||||
const queryParams = request.nextUrl.searchParams;
|
||||
|
||||
const chainId = queryParams.get("chainId");
|
||||
const payTo = queryParams.get("payTo");
|
||||
|
||||
if (!chainId || !payTo) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing required parameters" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
// TODO (402): dynamic from playground config
|
||||
// const amount = queryParams.get("amount");
|
||||
// const tokenAddress = queryParams.get("tokenAddress");
|
||||
// const decimals = queryParams.get("decimals");
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl,
|
||||
method,
|
||||
paymentData,
|
||||
payTo: payTo as `0x${string}`,
|
||||
network: defineChain(Number(chainId)),
|
||||
price: "$0.01",
|
||||
// price: {
|
||||
// amount: toUnits(amount as string, parseInt(decimals as string)).toString(),
|
||||
// asset: {
|
||||
// address: tokenAddress as `0x${string}`,
|
||||
// decimals: decimals ? parseInt(decimals) : token.decimals,
|
||||
// eip712: {
|
||||
// name: token.name,
|
||||
// version: token.version,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
},
|
||||
facilitator: twFacilitator,
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// payment successful, execute the request
|
||||
const response = NextResponse.next();
|
||||
for (const [key, value] of Object.entries(result.responseHeaders)) {
|
||||
response.headers.set(key, value);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
// otherwise, request payment
|
||||
return NextResponse.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// Configure which paths the middleware should run on
|
||||
export const config = {
|
||||
matcher: ["/api/paywall"],
|
||||
};
|
||||
@@ -738,6 +738,10 @@ const paymentRedirects = {
|
||||
"/connect/pay/buy-with-fiat": "/payments",
|
||||
"/connect/pay/enable-test-mode": "/payments",
|
||||
"/connect/pay/guides/enable-test-mode": "/payments",
|
||||
"/payments/sell": "/bridge/sell",
|
||||
"/payments/swap": "/bridge/swap",
|
||||
"/payments/tokens": "/bridge/tokens",
|
||||
"/payments/routes": "/bridge/routes",
|
||||
};
|
||||
|
||||
const contractRedirects = {
|
||||
|
||||
@@ -17,6 +17,76 @@ https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>
|
||||
|
||||
Make sure to keep your secret key safe and never share it with anyone.
|
||||
|
||||
By default, all tools are available. You can filter the tools available by passing a comma-separated list of tools as a query parameter.
|
||||
|
||||
```http
|
||||
https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>&tools=fetchWithPayment,getWalletBalance
|
||||
```
|
||||
|
||||
You can find all available tools at the bottom of this page.
|
||||
|
||||
## Usage with agents
|
||||
|
||||
Use your favorite agent framework to plug in the MCP server as a collection of tools for your agent. Refer to your agent framework's documentation for more information.
|
||||
|
||||
#### Example usage with langchain:
|
||||
|
||||
<Tabs defaultValue="typescript">
|
||||
|
||||
<TabsList>
|
||||
<TabsTrigger value="typescript">TypeScript</TabsTrigger>
|
||||
<TabsTrigger value="python">Python</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="typescript">
|
||||
|
||||
```typescript
|
||||
import { createReactAgent } from "@langchain/langgraph/prebuilt";
|
||||
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
||||
|
||||
const mcpServers = {
|
||||
thirdweb: {
|
||||
url: `https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>`
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to MCP servers and get tools
|
||||
const client = new MultiServerMCPClient(mcpServers);
|
||||
const tools = await client.getTools();
|
||||
|
||||
const agent = createReactAgent({
|
||||
llm: model,
|
||||
tools: tools,
|
||||
});
|
||||
await agent.invoke({messages: [{ role: "user", content: "create a server wallet called 'my-wallet'" }]})
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="python">
|
||||
|
||||
```python
|
||||
from langchain_mcp_adapters.client import MultiServerMCPClient
|
||||
from langgraph.prebuilt import create_react_agent
|
||||
|
||||
client = MultiServerMCPClient(
|
||||
{
|
||||
"thirdweb": {
|
||||
"url": "https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>",
|
||||
}
|
||||
}
|
||||
)
|
||||
tools = await client.get_tools()
|
||||
agent = create_react_agent("openai:gpt-4.1", tools)
|
||||
response = await agent.invoke({"messages": "create a server wallet called 'my-wallet'"})
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
|
||||
</Tabs>
|
||||
|
||||
Once installed, you can use the entire thirdweb API with natural language.
|
||||
|
||||
## Usage with LLM clients
|
||||
|
||||
You can also use the MCP server on your own LLM client, like cursor, claude code and more. Refer to your LLM client's documentation for more information.
|
||||
@@ -112,31 +182,6 @@ claude mcp add --transport http "thirdweb-api" "https://api.thirdweb.com/mcp?sec
|
||||
|
||||
</Tabs>
|
||||
|
||||
## Usage with agents
|
||||
|
||||
Use your favorite agent framework to plug in the MCP server as a collection of tools for your agent. Refer to your agent framework's documentation for more information.
|
||||
|
||||
#### Example usage with langchain:
|
||||
|
||||
```python
|
||||
from langchain_mcp_adapters.client import MultiServerMCPClient
|
||||
from langgraph.prebuilt import create_react_agent
|
||||
|
||||
client = MultiServerMCPClient(
|
||||
{
|
||||
"thirdweb-api": {
|
||||
"transport": "streamable_http",
|
||||
"url": "https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>",
|
||||
}
|
||||
}
|
||||
)
|
||||
tools = await client.get_tools()
|
||||
agent = create_react_agent("openai:gpt-4.1", tools)
|
||||
response = await agent.ainvoke({"messages": "create a server wallet called 'my-wallet'"})
|
||||
```
|
||||
|
||||
Once installed, you can use the entire thirdweb API with natural language.
|
||||
|
||||
## Example prompts
|
||||
|
||||
#### Managing server wallets
|
||||
@@ -164,3 +209,46 @@ List my contracts
|
||||
```
|
||||
approve 100 USDC from treasury wallet to executor wallet
|
||||
```
|
||||
|
||||
## Available tools
|
||||
|
||||
Currently, the following tools are available:
|
||||
|
||||
- `initiateAuthentication`
|
||||
- `completeAuthentication`
|
||||
- `linkAuthentication`
|
||||
- `unlinkAuthentication`
|
||||
- `getMyWallet`
|
||||
- `listUserWallets`
|
||||
- `createUserWallet`
|
||||
- `listServerWallets`
|
||||
- `createServerWallet`
|
||||
- `getWalletBalance`
|
||||
- `getWalletTransactions`
|
||||
- `getWalletTokens`
|
||||
- `getWalletNFTs`
|
||||
- `signMessage`
|
||||
- `signTypedData`
|
||||
- `sendTokens`
|
||||
- `listContracts`
|
||||
- `deployContract`
|
||||
- `readContract`
|
||||
- `writeContract`
|
||||
- `getContractTransactions`
|
||||
- `getContractEvents`
|
||||
- `getContractMetadata`
|
||||
- `getContractSignatures`
|
||||
- `getTransactionById`
|
||||
- `listTransactions`
|
||||
- `sendTransactions`
|
||||
- `createPayment`
|
||||
- `paymentsPurchase`
|
||||
- `getPaymentHistory`
|
||||
- `fetchWithPayment`
|
||||
- `createToken`
|
||||
- `listTokens`
|
||||
- `getTokenOwners`
|
||||
- `getBridgeChains`
|
||||
- `convertFiatToCrypto`
|
||||
- `bridgeSwap`
|
||||
- `chat`
|
||||
@@ -53,10 +53,6 @@ The BridgeWidget Script makes it easy to embed cross-chain swaps and fiat onramp
|
||||
BridgeWidget.render(container, {
|
||||
clientId: "your-thirdweb-client-id",
|
||||
theme: "dark",
|
||||
buy: {
|
||||
chainId: 8453,
|
||||
amount: "0.1",
|
||||
},
|
||||
});
|
||||
</script>
|
||||
```
|
||||
@@ -126,9 +122,9 @@ type Options = {
|
||||
};
|
||||
};
|
||||
};
|
||||
buy: {
|
||||
amount: string;
|
||||
chainId: number;
|
||||
buy?: {
|
||||
amount?: string;
|
||||
chainId?: number;
|
||||
tokenAddress?: string;
|
||||
buttonLabel?: string;
|
||||
onCancel?: (quote: BuyOrOnrampPrepareResult | undefined) => void;
|
||||
@@ -310,8 +306,8 @@ The options to configure the "Buy" tab UI.
|
||||
|
||||
```ts
|
||||
type Buy = {
|
||||
amount: string; // Required
|
||||
chainId: number; // Required
|
||||
amount?: string;
|
||||
chainId?: number;
|
||||
tokenAddress?: string;
|
||||
buttonLabel?: string;
|
||||
onCancel?: (quote: BuyOrOnrampPrepareResult | undefined) => void;
|
||||
@@ -327,21 +323,21 @@ type Buy = {
|
||||
```
|
||||
|
||||
|
||||
<Details summary="amount" tags={["Required"]}>
|
||||
<Details summary="amount">
|
||||
|
||||
Set the default token amount shown in the "Buy" tab.
|
||||
|
||||
</Details>
|
||||
|
||||
<Details summary="chainId" tags={["Required"]}>
|
||||
<Details summary="chainId">
|
||||
|
||||
Specify which chain should be selected in the "Buy" tab.
|
||||
Specify the default chain to be selected in the "Buy" tab.
|
||||
|
||||
</Details>
|
||||
|
||||
<Details summary="tokenAddress">
|
||||
|
||||
Specify which token should be selected in the "Buy" tab. If not specified, the native token of the selected chain will be selected.
|
||||
Specify the default token to be selected in the "Buy" tab. If not specified, the native token of the selected chain will be selected.
|
||||
|
||||
</Details>
|
||||
|
||||
|
||||
@@ -2,15 +2,6 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
.changelog-page a {
|
||||
text-decoration: underline;
|
||||
text-decoration-color: hsl(var(--muted-foreground));
|
||||
text-decoration-style: dotted;
|
||||
color: hsl(var(--foreground));
|
||||
text-underline-offset: 5px;
|
||||
transition: color 200ms ease;
|
||||
}
|
||||
|
||||
.changelog-page h2 a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@doc";
|
||||
|
||||
# Session Keys Guide
|
||||
|
||||
Session keys enable secure transaction execution on behalf of smart accounts without requiring direct access to the main account's private key. This guide will walk you through creating and using session keys with the thirdweb TypeScript SDK.
|
||||
Session keys enable secure transaction execution on behalf of accounts without requiring direct access to the main account's private key. This guide covers session keys for both ERC-4337 smart accounts and ERC-7702 smart EOAs (Externally Owned Accounts).
|
||||
|
||||
<Tabs defaultValue="erc4337">
|
||||
<TabsList>
|
||||
<TabsTrigger value="erc4337">ERC-4337 Smart Accounts</TabsTrigger>
|
||||
<TabsTrigger value="erc7702">ERC-7702 Smart EOAs</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="erc4337">
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -323,8 +333,409 @@ try {
|
||||
}
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="erc7702">
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, ensure you have:
|
||||
- A thirdweb client configured
|
||||
- An in-app wallet with ERC-7702 support
|
||||
- A session key account address (can be generated or an existing wallet)
|
||||
|
||||
## Setup
|
||||
|
||||
First, let's set up the necessary imports and configuration:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createThirdwebClient,
|
||||
getContract,
|
||||
sendTransaction,
|
||||
prepareTransaction
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { inAppWallet, createSessionKey } from "thirdweb/wallets/in-app";
|
||||
|
||||
// Configure your client
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key" // Only use in server environments
|
||||
});
|
||||
|
||||
// Your session key account address
|
||||
const sessionKeyAccountAddress = "0x..."; // Replace with your session key address
|
||||
```
|
||||
|
||||
## Step 1: Create ERC-7702 Smart EOA
|
||||
|
||||
Create an in-app wallet configured with ERC-7702 execution mode:
|
||||
|
||||
```typescript
|
||||
const wallet = inAppWallet({
|
||||
executionMode: {
|
||||
mode: "EIP7702",
|
||||
sponsorGas: true, // Enable gas sponsorship
|
||||
},
|
||||
});
|
||||
|
||||
// Connect the wallet (user authentication)
|
||||
const account = await wallet.connect({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
strategy: "google", // or "email", "guest", etc.
|
||||
});
|
||||
|
||||
console.log("Smart EOA address:", account.address);
|
||||
```
|
||||
|
||||
### Execution Modes
|
||||
|
||||
The `executionMode` option allows you to configure the wallet behavior:
|
||||
|
||||
- `mode`: Set to `"EIP7702"` for ERC-7702 smart EOA functionality
|
||||
- `sponsorGas`: Enable gas sponsorship for gasless transactions
|
||||
|
||||
## Step 2: Deploy/Upgrade the Account
|
||||
|
||||
Send a transaction to trigger the account deployment or upgrade to ERC-7702:
|
||||
|
||||
```typescript
|
||||
await sendTransaction({
|
||||
account: account,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: account.address,
|
||||
value: 0n, // Self-transfer to trigger deployment
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Smart EOA deployed/upgraded successfully");
|
||||
```
|
||||
|
||||
## Step 3: Get Account Contract
|
||||
|
||||
Create a contract instance for the deployed smart EOA:
|
||||
|
||||
```typescript
|
||||
const accountContract = getContract({
|
||||
address: account.address,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
// ABI will be automatically resolved since the contract is deployed
|
||||
});
|
||||
```
|
||||
|
||||
## Step 4: Create Session Key with Full Permissions
|
||||
|
||||
Add a session key with full execution permissions:
|
||||
|
||||
```typescript
|
||||
const tx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: true, // Allow unrestricted access
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key created:", tx.transactionHash);
|
||||
```
|
||||
|
||||
### Session Key Options
|
||||
|
||||
- `account`: The admin account that will create the session key
|
||||
- `contract`: The smart EOA contract instance
|
||||
- `sessionKeyAddress`: The address that will be granted session key permissions
|
||||
- `durationInSeconds`: How long the session key should be valid (in seconds)
|
||||
- `grantFullPermissions`: If `true`, grants unrestricted access. If `false`, you must specify policies.
|
||||
|
||||
## Step 5 (Advanced): Create Session Key with Granular Permissions
|
||||
|
||||
For more fine-grained control, you can specify call and transfer policies:
|
||||
|
||||
```typescript
|
||||
import { Condition, LimitType } from "thirdweb/wallets/in-app";
|
||||
|
||||
const tx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: false, // Use granular permissions
|
||||
callPolicies: [
|
||||
{
|
||||
target: "0x123...", // Target contract address
|
||||
selector: "0xa9059cbb", // Function selector (e.g., ERC20 transfer)
|
||||
maxValuePerUse: 0n, // Max ETH value per call
|
||||
valueLimit: {
|
||||
limitType: LimitType.Lifetime, // Lifetime limit
|
||||
limit: 1000000n, // Max total value in wei
|
||||
period: 0n, // Not used for lifetime limits
|
||||
},
|
||||
constraints: [
|
||||
{
|
||||
condition: Condition.Equal, // Constraint type
|
||||
index: 0n, // Parameter index
|
||||
refValue: "0x000000000000000000000000abc...", // Expected value
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
transferPolicies: [
|
||||
{
|
||||
target: "0x456...", // Recipient address for transfers
|
||||
maxValuePerUse: 100000n, // Max wei per transfer
|
||||
valueLimit: {
|
||||
limitType: LimitType.Allowance, // Allowance-based limit
|
||||
limit: 1000000n, // Total allowance in wei
|
||||
period: 86400n, // Reset period in seconds
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key with policies created:", tx.transactionHash);
|
||||
```
|
||||
|
||||
### Permission Types
|
||||
|
||||
#### Call Policies
|
||||
|
||||
Control which smart contract calls the session key can make:
|
||||
|
||||
- `target`: The contract address the session key can call
|
||||
- `selector`: The function selector (4-byte identifier) that can be called
|
||||
- `maxValuePerUse`: Maximum ETH value that can be sent per transaction
|
||||
- `valueLimit`: Total value limits over time
|
||||
- `constraints`: Parameter-level constraints for function calls
|
||||
|
||||
#### Transfer Policies
|
||||
|
||||
Control native token transfers the session key can make:
|
||||
|
||||
- `target`: The recipient address for transfers
|
||||
- `maxValuePerUse`: Maximum wei per individual transfer
|
||||
- `valueLimit`: Total transfer limits over time
|
||||
|
||||
#### Limit Types
|
||||
|
||||
```typescript
|
||||
enum LimitType {
|
||||
Unlimited = 0, // No limit
|
||||
Lifetime = 1, // One-time total limit
|
||||
Allowance = 2, // Renewable allowance based on period
|
||||
}
|
||||
```
|
||||
|
||||
#### Constraint Conditions
|
||||
|
||||
```typescript
|
||||
enum Condition {
|
||||
Unconstrained = 0, // No constraint
|
||||
Equal = 1, // Must equal reference value
|
||||
Greater = 2, // Must be greater than reference value
|
||||
Less = 3, // Must be less than reference value
|
||||
GreaterOrEqual = 4, // Must be >= reference value
|
||||
LessOrEqual = 5, // Must be <= reference value
|
||||
NotEqual = 6, // Must not equal reference value
|
||||
}
|
||||
```
|
||||
|
||||
## Step 6: Use the Session Key
|
||||
|
||||
Once created, the session key can be used with Engine or other server-side execution:
|
||||
|
||||
```typescript
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
vaultAccessToken: process.env.VAULT_TOKEN as string,
|
||||
});
|
||||
|
||||
// Execute transactions with the session key
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: "0x...", // Target address
|
||||
value: 0n,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Transaction executed:", tx.transactionHash);
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a complete example for setting up and using a session key with ERC-7702:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createThirdwebClient,
|
||||
getContract,
|
||||
sendTransaction,
|
||||
prepareTransaction
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { inAppWallet, createSessionKey } from "thirdweb/wallets/in-app";
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
async function setupSessionKeyWith7702() {
|
||||
// Configuration
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key"
|
||||
});
|
||||
|
||||
const sessionKeyAccountAddress = "0x..."; // Your session key address
|
||||
|
||||
try {
|
||||
// Step 1: Create 7702 Smart EOA
|
||||
const wallet = inAppWallet({
|
||||
executionMode: {
|
||||
mode: "EIP7702",
|
||||
sponsorGas: true,
|
||||
},
|
||||
});
|
||||
|
||||
const account = await wallet.connect({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
strategy: "google",
|
||||
});
|
||||
|
||||
console.log("Smart EOA created:", account.address);
|
||||
|
||||
// Step 2: Deploy/upgrade the account
|
||||
await sendTransaction({
|
||||
account: account,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: account.address,
|
||||
value: 0n,
|
||||
}),
|
||||
});
|
||||
|
||||
// Step 3: Get account contract
|
||||
const accountContract = getContract({
|
||||
address: account.address,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
});
|
||||
|
||||
// Step 4: Create session key
|
||||
const sessionTx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: true,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key created:", sessionTx.transactionHash);
|
||||
|
||||
// Step 5: Use the session key with Engine
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
vaultAccessToken: process.env.VAULT_TOKEN as string,
|
||||
});
|
||||
|
||||
// Execute a transaction with the session key
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: "0x...", // Target address
|
||||
value: 0n,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Transaction successful:", tx.transactionHash);
|
||||
return tx;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the function
|
||||
setupSessionKeyWith7702()
|
||||
.then((tx) => console.log("Done!", tx.transactionHash))
|
||||
.catch((error) => console.error("Failed:", error));
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Session Key Storage**: Store session keys securely, preferably in a vault system
|
||||
- **Permission Scope**: Use granular permissions (`grantFullPermissions: false`) for production use cases
|
||||
- **Time Limits**: Set appropriate `durationInSeconds` values based on your use case
|
||||
- **Policy Design**: Carefully design call and transfer policies to minimize risk
|
||||
- **Key Rotation**: Regularly rotate session keys and revoke unused ones
|
||||
- **Monitoring**: Monitor session key usage for suspicious activity
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Account not deployed**: Ensure you've sent a transaction to trigger the account deployment/upgrade
|
||||
2. **Invalid signature**: Make sure the admin account is properly authenticated and can sign typed data
|
||||
3. **Permission denied**: Verify the session key has the necessary policies for the operation
|
||||
4. **Expired session key**: Check that the current time is within the session key's validity period
|
||||
|
||||
### Error Handling
|
||||
|
||||
Always wrap your session key operations in try-catch blocks:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const tx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400,
|
||||
grantFullPermissions: true,
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error.message.includes("signature")) {
|
||||
console.error("Failed to sign session key creation");
|
||||
} else if (error.message.includes("duration")) {
|
||||
console.error("Invalid duration specified");
|
||||
} else {
|
||||
console.error("Session key creation failed:", error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn more about [Smart Wallets](/engine/v3/configure-wallets/server-wallets)
|
||||
- Learn more about [In-App Wallets](/wallets/in-app-wallet/overview)
|
||||
- Explore [Engine API Reference](https://engine.thirdweb.com/reference)
|
||||
- Check out the [TypeScript SDK](/references/typescript/v5/serverWallet) documentation
|
||||
- Check out the [TypeScript SDK](/references/typescript/v5) documentation
|
||||
- Read about [ERC-7702](https://eips.ethereum.org/EIPS/eip-7702) specification
|
||||
|
||||
@@ -61,14 +61,37 @@ export const sidebar: SideBar = {
|
||||
href: `${paymentsSlug}/custom-data`,
|
||||
name: "Custom Data",
|
||||
},
|
||||
{
|
||||
href: `${paymentsSlug}/x402`,
|
||||
name: "x402",
|
||||
},
|
||||
],
|
||||
name: "Guides",
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
isCollapsible: false,
|
||||
links: [
|
||||
{
|
||||
href: `${paymentsSlug}/x402`,
|
||||
name: "Get Started",
|
||||
},
|
||||
{
|
||||
href: `${paymentsSlug}/x402/client`,
|
||||
name: "Client Side",
|
||||
},
|
||||
{
|
||||
href: `${paymentsSlug}/x402/server`,
|
||||
name: "Server Side",
|
||||
},
|
||||
{
|
||||
href: `${paymentsSlug}/x402/agents`,
|
||||
name: "Agents",
|
||||
},
|
||||
{
|
||||
href: `${paymentsSlug}/x402/facilitator`,
|
||||
name: "Facilitator",
|
||||
},
|
||||
],
|
||||
name: "x402",
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
isCollapsible: false,
|
||||
links: [
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import { OpenApiEndpoint, createMetadata } from "@doc";
|
||||
|
||||
export const metadata = createMetadata({
|
||||
image: {
|
||||
title: "x402 Agents",
|
||||
icon: "payments",
|
||||
},
|
||||
title: "x402 Agents",
|
||||
description: "Easily create AI agents that can pay for any x402-compatible API calls.",
|
||||
});
|
||||
|
||||
# x402 Agents
|
||||
|
||||
Easily create AI agents that can pay for any x402-compatible API calls.
|
||||
|
||||
## Using the MCP Server
|
||||
|
||||
The easiest way to equip your agents with the ability to pay for API calls is to use the [remote MCP server](/ai/mcp) and provide the tools to your agent.
|
||||
|
||||
The MCP server comes with all the tools by default, but you can filter the tools available by passing a comma-separated list of tools as a query parameter.
|
||||
|
||||
In this example, we create a ReAct agent using LangChain and filter the MCP tools to `fetchWithPayment` and `getWalletBalance` as the only 2 tools we give our agent. You can view the full list of available tools [here](/ai/mcp#available-tools).
|
||||
|
||||
<Tabs defaultValue="typescript">
|
||||
|
||||
<TabsList>
|
||||
<TabsTrigger value="typescript">TypeScript</TabsTrigger>
|
||||
<TabsTrigger value="python">Python</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="typescript">
|
||||
|
||||
```typescript
|
||||
import { createReactAgent } from "@langchain/langgraph/prebuilt";
|
||||
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
|
||||
import { ChatOpenAI } from "@langchain/openai";
|
||||
|
||||
const model = new ChatOpenAI({
|
||||
model: "gpt-4.1",
|
||||
});
|
||||
|
||||
const mcpServers = {
|
||||
thirdweb: {
|
||||
url: `https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>&tools=fetchWithPayment,getWalletBalance`
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to MCP servers and get tools
|
||||
const client = new MultiServerMCPClient(mcpServers);
|
||||
const tools = await client.getTools();
|
||||
|
||||
const agent = createReactAgent({
|
||||
llm: model,
|
||||
tools: tools,
|
||||
prompt: "Use the fetchWithPayment tool to fetch any endpoint. Always pay in {{tokenAddress}}. Your wallet address is {{walletAddress}}."
|
||||
});
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="python">
|
||||
|
||||
```python
|
||||
from langchain_mcp_adapters.client import MultiServerMCPClient
|
||||
from langgraph.prebuilt import create_react_agent
|
||||
|
||||
client = MultiServerMCPClient(
|
||||
{
|
||||
"thirdweb": {
|
||||
"url": "https://api.thirdweb.com/mcp?secretKey=<your-project-secret-key>&tools=fetchWithPayment,getWalletBalance",
|
||||
}
|
||||
}
|
||||
)
|
||||
tools = await client.get_tools()
|
||||
agent = create_react_agent("openai:gpt-4.1", tools, prompt="Use the fetchWithPayment tool to fetch any endpoint. Always pay in {{tokenAddress}}. Your wallet address is {{walletAddress}}.")
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Using the API directly
|
||||
|
||||
You can also create your own MCP tool or wrap all external calls with the `/v1/x402/fetchWithPayment` endpoint to automatically handle payment flows when APIs return a `402 Payment Required` response.
|
||||
|
||||
Pass the target `url`, `method` and optional `from` wallet address to the endpoint that will complete the payment. The address should be one of your [user wallets](/wallets/users) or [server wallets](/wallets/server).
|
||||
|
||||
```bash
|
||||
curl -X POST https://api.thirdweb.com/v1/payments/x402/fetch?url=https://api.example.com/premium&method=GET&from=0x1234... \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "x-secret-key: <your-project-secret-key>" \
|
||||
-d '{ ... }' # optional request body passed through to the url called.
|
||||
```
|
||||
|
||||
<OpenApiEndpoint path="/v1/payments/x402/fetch" method="POST" />
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent, OpenApiEndpoint, createMetadata } from "@doc";
|
||||
import { TypeScriptIcon, EngineIcon } from "@/icons";
|
||||
|
||||
export const metadata = createMetadata({
|
||||
image: {
|
||||
title: "x402 Client",
|
||||
icon: "payments",
|
||||
},
|
||||
title: "x402 Client",
|
||||
description: "Make requests to any x402-compatible backend and automatically handle payment flows when APIs return a `402 Payment Required` response.",
|
||||
});
|
||||
|
||||
# Client Side
|
||||
|
||||
Make requests to any x402-compatible backend and automatically handle payment flows when APIs return a `402 Payment Required` response.
|
||||
|
||||
The client library wraps the native `fetch` API and handles:
|
||||
1. Initial request to the API
|
||||
2. Detection of `402 Payment Required` responses
|
||||
3. Parsing payment requirements from the response
|
||||
4. Creating and signing payment authorization
|
||||
5. Retrying the request with payment credentials
|
||||
|
||||
<Tabs defaultValue="typescript">
|
||||
<TabsList>
|
||||
<TabsTrigger value="typescript" className="flex items-center [&>p]:mb-0">
|
||||
<TypeScriptIcon className="size-4 mr-1.5" />
|
||||
TypeScript
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="http" className="flex items-center [&>p]:mb-0">
|
||||
<EngineIcon className="size-4 mr-1.5" />
|
||||
HTTP API
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="typescript">
|
||||
## Using `wrapFetchWithPayment`
|
||||
|
||||
The `wrapFetchWithPayment` function wraps the native fetch API to automatically handle 402 Payment Required responses.
|
||||
|
||||
```typescript
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { createWallet } from "thirdweb/wallets";
|
||||
|
||||
const client = createThirdwebClient({ clientId: "your-client-id" });
|
||||
const wallet = createWallet("io.metamask"); // or any other wallet
|
||||
await wallet.connect({ client })
|
||||
|
||||
// Wrap fetch with payment handling
|
||||
// maxValue is the maximum payment amount in base units (defaults to 1 USDC = 1_000_000)
|
||||
const fetchWithPay = wrapFetchWithPayment(
|
||||
fetch,
|
||||
client,
|
||||
wallet,
|
||||
BigInt(1 * 10 ** 6) // max 1 USDC
|
||||
);
|
||||
|
||||
// Make a request that may require payment
|
||||
const response = await fetchWithPay('https://api.example.com/paid-endpoint');
|
||||
const data = await response.json();
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
- `fetch` - The fetch function to wrap (typically `globalThis.fetch`)
|
||||
- `client` - The thirdweb client used to access RPC infrastructure
|
||||
- `wallet` - The wallet used to sign payment messages
|
||||
- `maxValue` - (Optional) The maximum allowed payment amount in base units (defaults to 1 USDC = 1,000,000)
|
||||
|
||||
### Reference
|
||||
|
||||
For full API documentation, see the [TypeScript Reference](/references/typescript/v5/x402/wrapFetchWithPayment).
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="http">
|
||||
## Prepare Payment
|
||||
|
||||
Fetch any x402-compatible API and automatically handle payment flows when APIs return a `402 Payment Required` response using the authenticated wallet.
|
||||
|
||||
Only requires passing a 'url' and 'from' query parameters with the authenticated wallet address (server or user wallet) to complete the payment.
|
||||
|
||||
```bash
|
||||
curl -X POST https://api.thirdweb.com/v1/payments/x402/fetch?url=https://api.example.com/premium&from=0x1234... \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer <user-wallet-token>" \
|
||||
-d '{ ... }' # request body passed through to the url called.
|
||||
```
|
||||
|
||||
<OpenApiEndpoint path="/v1/payments/x402/fetch" method="POST" />
|
||||
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,360 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent, OpenApiEndpoint, Callout, createMetadata } from "@doc";
|
||||
import { TypeScriptIcon, EngineIcon } from "@/icons";
|
||||
|
||||
export const metadata = createMetadata({
|
||||
image: {
|
||||
title: "x402 Facilitator",
|
||||
icon: "payments",
|
||||
},
|
||||
title: "x402 Facilitator",
|
||||
description: "Verify and submit x402 payments using your own server wallet.",
|
||||
});
|
||||
|
||||
# Facilitator
|
||||
|
||||
The facilitator is a service that handles verifying and submitting x402 payments. It uses your own [server wallet](/wallets/server) and leverages EIP-7702 to submit transactions gaslessly.
|
||||
|
||||
The thirdweb facilitator is compatible with any x402 backend and middleware libraries like `x402-hono`, `x402-next`, and more.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Verification** - Validates payment signatures and requirements
|
||||
2. **Settlement** - Submits the payment transaction on-chain
|
||||
3. **Gasless** - Uses [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) for gasless transactions
|
||||
4. **Your Wallet** - Uses your own server wallet for receiving payments
|
||||
|
||||
You can view all transactions processed by your facilitator in your project dashboard.
|
||||
|
||||
## Chain and token support
|
||||
|
||||
Our facilitator supports payments on any EVM chain, as long as the payment token supports either:
|
||||
|
||||
- ERC-2612 permit (most ERC20 tokens)
|
||||
- ERC-3009 sign with authorization (USDC on all chains)
|
||||
|
||||
<Tabs defaultValue="typescript">
|
||||
<TabsList>
|
||||
<TabsTrigger value="typescript" className="flex items-center [&>p]:mb-0">
|
||||
<TypeScriptIcon className="size-4 mr-1.5" />
|
||||
TypeScript API
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="http" className="flex items-center [&>p]:mb-0">
|
||||
<EngineIcon className="size-4 mr-1.5" />
|
||||
HTTP API
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="typescript">
|
||||
## Creating a Facilitator
|
||||
|
||||
Create a facilitator instance to use with `settlePayment()` or external middleware:
|
||||
|
||||
```typescript
|
||||
import { facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: "your-secret-key",
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client: client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
```typescript
|
||||
const thirdwebFacilitator = facilitator({
|
||||
// Required: Your thirdweb client with secret key
|
||||
client: client,
|
||||
|
||||
// Required: Your server wallet address that will execute transactions
|
||||
// get it from your project dashboard
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
|
||||
// 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",
|
||||
});
|
||||
```
|
||||
|
||||
## Usage with settlePayment()
|
||||
|
||||
Use the facilitator with the `settlePayment()` function:
|
||||
|
||||
```typescript
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const paymentData = request.headers.get("x-payment");
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl: "https://api.example.com/premium-content",
|
||||
method: "GET",
|
||||
paymentData,
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.10",
|
||||
facilitator: thirdwebFacilitator, // Pass the facilitator here
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
return Response.json({ data: "premium content" });
|
||||
} else {
|
||||
return Response.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Usage with other x402 middleware libraries
|
||||
|
||||
Use the facilitator with third-party x402 middleware libraries:
|
||||
|
||||
<Tabs defaultValue="hono">
|
||||
<TabsList>
|
||||
<TabsTrigger value="hono">x402-hono</TabsTrigger>
|
||||
<TabsTrigger value="next">x402-next</TabsTrigger>
|
||||
<TabsTrigger value="express">x402-express</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="hono">
|
||||
```typescript
|
||||
import { Hono } from "hono";
|
||||
import { paymentMiddleware } from "x402-hono";
|
||||
import { facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: "your-secret-key",
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client: client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// Add the facilitator to the x402 middleware
|
||||
app.use(paymentMiddleware(
|
||||
"0xYourWalletAddress",
|
||||
{
|
||||
"/api/paywall": {
|
||||
price: "$0.01",
|
||||
network: "base-sepolia",
|
||||
config: {
|
||||
description: "Access to paid content",
|
||||
},
|
||||
},
|
||||
},
|
||||
thirdwebFacilitator, // Pass the facilitator to the middleware
|
||||
)
|
||||
);
|
||||
|
||||
app.get("/api/paywall", (c) => {
|
||||
return c.json({ message: "This is premium content!" });
|
||||
});
|
||||
|
||||
export default app;
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="next">
|
||||
```typescript
|
||||
// middleware.ts
|
||||
import { paymentMiddleware } from "x402-next";
|
||||
import { facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: process.env.SERVER_WALLET_ADDRESS,
|
||||
});
|
||||
|
||||
export const middleware = paymentMiddleware(
|
||||
'0xYourWalletAddress',
|
||||
{
|
||||
"/api/premium": {
|
||||
price: "$0.05",
|
||||
network: "base-sepolia",
|
||||
},
|
||||
},
|
||||
thirdwebFacilitator // Pass the facilitator to the middleware
|
||||
);
|
||||
|
||||
export const config = {
|
||||
matcher: ["/api/premium/:path*"],
|
||||
};
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="express">
|
||||
```typescript
|
||||
import express from "express";
|
||||
import { paymentMiddleware } from "x402-express";
|
||||
import { facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: "your-secret-key",
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client: client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
const app = express();
|
||||
|
||||
// Add the facilitator to the x402 middleware
|
||||
app.use(
|
||||
paymentMiddleware(
|
||||
"0xYourWalletAddress",
|
||||
{
|
||||
"/api/paywall": {
|
||||
price: "$0.01",
|
||||
network: "base-sepolia",
|
||||
config: {
|
||||
description: "Access to paid content",
|
||||
},
|
||||
},
|
||||
},
|
||||
thirdwebFacilitator, // Pass the facilitator to the middleware
|
||||
)
|
||||
);
|
||||
|
||||
app.get("/api/paywall", (req, res) => {
|
||||
res.json({ message: "This content is behind a paywall!" });
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
```
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Getting Supported Payment Methods
|
||||
|
||||
Query which payment methods are supported by the facilitator:
|
||||
|
||||
```typescript
|
||||
// Get all supported payment methods
|
||||
const allSupported = await thirdwebFacilitator.supported();
|
||||
|
||||
// Filter by chain
|
||||
const baseSupported = await thirdwebFacilitator.supported({
|
||||
chainId: 8453, // Base
|
||||
});
|
||||
|
||||
// Filter by chain and token
|
||||
const usdcOnBase = await thirdwebFacilitator.supported({
|
||||
chainId: 8453,
|
||||
tokenAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
||||
});
|
||||
```
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="http">
|
||||
## HTTP API Reference
|
||||
|
||||
Use the HTTP API directly if you're not using the TypeScript SDK.
|
||||
|
||||
### Example Flow
|
||||
|
||||
```bash
|
||||
# 1. First request returns 402 Payment Required
|
||||
curl -X GET https://api.example.com/premium \
|
||||
-H "Content-Type: application/json"
|
||||
|
||||
# Response (402):
|
||||
# {
|
||||
# "x402Version": 1,
|
||||
# "accepts": [{
|
||||
# "scheme": "exact",
|
||||
# "network": "eip155:421614",
|
||||
# "maxAmountRequired": "100000",
|
||||
# "resource": "https://api.example.com/premium",
|
||||
# "description": "Premium content access",
|
||||
# "mimeType": "application/json",
|
||||
# "payTo": "0x1234...",
|
||||
# "maxTimeoutSeconds": 300,
|
||||
# "asset": "0x..."
|
||||
# }],
|
||||
# "error": "Payment required"
|
||||
# }
|
||||
|
||||
# 2. Prepare payment (see Client Side docs)
|
||||
# This selects the payment method and creates a signed payment payload
|
||||
|
||||
# 3. Verify the payment (optional)
|
||||
curl -X POST https://api.thirdweb.com/v1/payments/x402/verify \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "x-secret-key: YOUR_SECRET_KEY" \
|
||||
-d '{
|
||||
"x402Version": 1,
|
||||
"paymentPayload": { ... },
|
||||
"paymentRequirements": { ... }
|
||||
}'
|
||||
|
||||
# 4. Settle the payment
|
||||
curl -X POST https://api.thirdweb.com/v1/payments/x402/settle \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "x-secret-key: YOUR_SECRET_KEY" \
|
||||
-d '{
|
||||
"x402Version": 1,
|
||||
"paymentPayload": { ... },
|
||||
"paymentRequirements": { ...},
|
||||
"waitUntil": "confirmed"
|
||||
}'
|
||||
```
|
||||
|
||||
<Callout variant="info">
|
||||
All facilitator HTTP API endpoints require authentication using the `x-secret-key` header with your project secret key.
|
||||
</Callout>
|
||||
|
||||
### Verify Payment
|
||||
|
||||
Verify a payment signature and requirements without settling:
|
||||
|
||||
<OpenApiEndpoint path="/v1/payments/x402/verify" method="POST" />
|
||||
|
||||
---
|
||||
|
||||
### Settle Payment
|
||||
|
||||
Verify and submit a payment transaction on-chain:
|
||||
|
||||
<OpenApiEndpoint path="/v1/payments/x402/settle" method="POST" />
|
||||
|
||||
---
|
||||
|
||||
### List Supported Payment Methods
|
||||
|
||||
Get a list of payment methods supported by the facilitator:
|
||||
|
||||
<OpenApiEndpoint path="/v1/payments/x402/supported" method="GET" />
|
||||
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
@@ -1,28 +1,31 @@
|
||||
import { ArticleIconCard } from "@doc";
|
||||
import { ReactIcon } from "@/icons";
|
||||
import { ArticleIconCard, createMetadata } from "@doc";
|
||||
import { ReactIcon, TypeScriptIcon, EngineIcon } from "@/icons";
|
||||
|
||||
# x402 payments
|
||||
export const metadata = createMetadata({
|
||||
image: {
|
||||
title: "x402 Payments",
|
||||
icon: "payments",
|
||||
},
|
||||
title: "x402 Payments",
|
||||
description: "Instant payments for your APIs, websites, and autonomous agents.",
|
||||
});
|
||||
|
||||
Implement paid API calls using the x402 protocol. Every request is paid for by the user with a micro payment onchain.
|
||||
# x402 Payments
|
||||
|
||||
x402 is an open-source protocol that turns the dormant HTTP 402 Payment Required status code into a fully-featured, on-chain payment layer for APIs, websites, and autonomous agents.
|
||||
|
||||
Learn more about the protocol at [x402.org](https://x402.org).
|
||||
|
||||
<ArticleIconCard
|
||||
title="x402 Playground"
|
||||
description="Try out a x402 payment in our live playground"
|
||||
description="Try out x402 payments in our live playground"
|
||||
icon={ReactIcon}
|
||||
href="https://playground.thirdweb.com/payments/x402"
|
||||
/>
|
||||
|
||||
## Client Side
|
||||
|
||||
`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any API call. It will:
|
||||
1. Make the initial request
|
||||
2. If a 402 response is received, parse the payment requirements
|
||||
3. Verify the payment amount is within the allowed maximum
|
||||
4. Sign a payment authorization
|
||||
5. Create a payment header using the provided wallet signature
|
||||
6. Retry the request with the payment header
|
||||
|
||||
Here's an example:
|
||||
`wrapFetchWithPayment` wraps the native fetch API to automatically handle `402 Payment Required` responses from any x402-compatible API:
|
||||
|
||||
```typescript
|
||||
import { wrapFetchWithPayment } from "thirdweb/x402";
|
||||
@@ -30,7 +33,7 @@ import { createThirdwebClient } from "thirdweb";
|
||||
import { createWallet } from "thirdweb/wallets";
|
||||
|
||||
const client = createThirdwebClient({ clientId: "your-client-id" });
|
||||
const wallet = createWallet("io.metamask"); // or any other wallet
|
||||
const wallet = createWallet("io.metamask");
|
||||
await wallet.connect({ client })
|
||||
|
||||
const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
|
||||
@@ -39,13 +42,11 @@ const fetchWithPay = wrapFetchWithPayment(fetch, client, wallet);
|
||||
const response = await fetchWithPay('https://api.example.com/paid-endpoint');
|
||||
```
|
||||
|
||||
You can also use the thirdweb API to fetch any x402 compatible endpoint and pay for it with the authenticated wallet. See the [client side docs](/payments/x402/client) for more details.
|
||||
|
||||
## Server Side
|
||||
|
||||
To make your API calls payable, you can use the `settlePayment` function in a middleware or in your endpoint directly.
|
||||
|
||||
Use the `facilitator` configuration function settle transactions with your thirdweb server wallet gaslessly and pass it to the `settlePayment` function.
|
||||
|
||||
Here's an example with a Next.js middleware:
|
||||
To make your API calls payable, use the `settlePayment` function in a middleware or endpoint:
|
||||
|
||||
```typescript
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
@@ -58,45 +59,56 @@ const thirdwebX402Facilitator = facilitator({
|
||||
serverWalletAddress: "0xYourWalletAddress",
|
||||
});
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const method = request.method.toUpperCase();
|
||||
const resourceUrl = request.nextUrl.toString();
|
||||
const paymentData = request.headers.get("X-PAYMENT");
|
||||
export async function GET(request: Request) {
|
||||
const paymentData = request.headers.get("x-payment");
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl,
|
||||
method,
|
||||
resourceUrl: "https://api.example.com/premium-content",
|
||||
method: "GET",
|
||||
paymentData,
|
||||
payTo: "0xYourWalletAddress",
|
||||
network: arbitrumSepolia, // or any other chain
|
||||
price: "$0.01", // can also be a ERC20 token amount
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
},
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.01",
|
||||
facilitator: thirdwebX402Facilitator,
|
||||
routeConfig: {
|
||||
description: "Access to premium API content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// payment successful, execute the request
|
||||
const response = NextResponse.next();
|
||||
// optionally set the response headers back to the client
|
||||
for (const [key, value] of Object.entries(result.responseHeaders)) {
|
||||
response.headers.set(key, value);
|
||||
}
|
||||
return response;
|
||||
return Response.json({ data: "premium content" });
|
||||
} else {
|
||||
return Response.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// otherwise, request payment
|
||||
return NextResponse.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// Configure which paths the middleware should run on
|
||||
export const config = {
|
||||
matcher: ["/api/paid-endpoint"],
|
||||
};
|
||||
```
|
||||
|
||||
You can also use the `verifyPayment` function to verify the payment before settling it. This lets you do the work that requires payment first and then settle the payment.
|
||||
You can also create middlewares to handle payment for multiple endpoints, see the [server side docs](/payments/x402/server) for more details. The [facilitator](/payments/x402/facilitator) handles settling the payment onchain using your own server wallet.
|
||||
|
||||
## Going Further
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
|
||||
<ArticleIconCard
|
||||
title="Client Side"
|
||||
description="Learn how to interact with x402-compatible APIs from your client applications"
|
||||
icon={TypeScriptIcon}
|
||||
href="/payments/x402/client"
|
||||
/>
|
||||
<ArticleIconCard
|
||||
title="Server Side"
|
||||
description="Accept x402 payments in your APIs with middleware or dedicated endpoints"
|
||||
icon={EngineIcon}
|
||||
href="/payments/x402/server"
|
||||
/>
|
||||
<ArticleIconCard
|
||||
title="Facilitator API"
|
||||
description="Configure the facilitator service to verify and settle payments"
|
||||
icon={EngineIcon}
|
||||
href="/payments/x402/facilitator"
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,447 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent, DocImage, createMetadata } from "@doc";
|
||||
import { Steps, Step } from "@doc";
|
||||
import PaymentFlow from "./x402-protocol-flow.png";
|
||||
|
||||
export const metadata = createMetadata({
|
||||
image: {
|
||||
title: "x402 Server",
|
||||
icon: "payments",
|
||||
},
|
||||
title: "x402 Server",
|
||||
description: "Accept x402 payments in your APIs from any x402-compatible client.",
|
||||
});
|
||||
|
||||
# Server Side
|
||||
|
||||
Accept x402 payments in your APIs using any x402-compatible client. Your server can verify and settle payments using thirdweb's facilitator service or any custom facilitator.
|
||||
|
||||
## Payment Flow
|
||||
|
||||
The x402 protocol follows this flow:
|
||||
|
||||
<DocImage src={PaymentFlow} alt="x402 Protocol Flow" />
|
||||
|
||||
1. **Client Request** - Client makes a request to your API
|
||||
2. **Payment Required** - Server responds with 402 and payment requirements
|
||||
3. **Client Signs** - Client signs payment authorization
|
||||
4. **Paid Request** - Client retries with payment header
|
||||
5. **Verify & Settle** - Server verifies and settles the payment
|
||||
6. **Success** - Server returns the protected content
|
||||
|
||||
## Verify vs Settle
|
||||
|
||||
You have two options for handling payments:
|
||||
|
||||
### Option 1: Settle Payment Directly
|
||||
|
||||
Use `settlePayment()` to verify and settle the payment in one step. This is the simplest approach:
|
||||
|
||||
```typescript
|
||||
const result = await settlePayment(paymentArgs);
|
||||
|
||||
if (result.status === 200) {
|
||||
// Payment settled, do the paid work
|
||||
return Response.json({ data: "premium content" });
|
||||
}
|
||||
```
|
||||
|
||||
### Option 2: Verify First, Then Settle
|
||||
|
||||
Use `verifyPayment()` first, do the work, then `settlePayment()`. This is useful when:
|
||||
- The final price might be dynamic based on the work performed
|
||||
- You want to ensure the payment is valid before doing expensive work
|
||||
- You need to calculate resource usage before charging
|
||||
|
||||
```typescript
|
||||
// First verify the payment is valid
|
||||
const verifyResult = await verifyPayment(paymentArgs);
|
||||
|
||||
if (verifyResult.status !== 200) {
|
||||
return Response.json(verifyResult.responseBody, {
|
||||
status: verifyResult.status,
|
||||
headers: verifyResult.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// Do the expensive work that requires payment
|
||||
const result = await doExpensiveWork();
|
||||
|
||||
// Now settle the payment based on actual usage
|
||||
const settleResult = await settlePayment({
|
||||
...paymentArgs,
|
||||
price: calculateDynamicPrice(result), // adjust price based on usage
|
||||
});
|
||||
|
||||
return Response.json(result);
|
||||
```
|
||||
|
||||
## Dedicated Endpoint Examples
|
||||
|
||||
Protect individual API endpoints with x402 payments:
|
||||
|
||||
<Tabs defaultValue="nextjs">
|
||||
<TabsList>
|
||||
<TabsTrigger value="nextjs">Next.js</TabsTrigger>
|
||||
<TabsTrigger value="express">Express</TabsTrigger>
|
||||
<TabsTrigger value="hono">Hono</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="nextjs">
|
||||
```typescript
|
||||
// app/api/premium-content/route.ts
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
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,
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.10", // or { amount: "100000", asset: { address: "0x...", decimals: 6 } }
|
||||
facilitator: thirdwebFacilitator,
|
||||
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,
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="express">
|
||||
```typescript
|
||||
// server.ts
|
||||
import express from "express";
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
const app = express();
|
||||
|
||||
app.get("/api/premium", async (req, res) => {
|
||||
const result = await settlePayment({
|
||||
resourceUrl: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
|
||||
method: req.method,
|
||||
paymentData: req.headers["x-payment"],
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.05",
|
||||
facilitator: thirdwebFacilitator,
|
||||
routeConfig: {
|
||||
description: "Access to premium content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// Set payment receipt headers
|
||||
Object.entries(result.responseHeaders).forEach(([key, value]) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
res.json({ message: "This is premium content!" });
|
||||
} else {
|
||||
res.status(result.status)
|
||||
.set(result.responseHeaders)
|
||||
.json(result.responseBody);
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="hono">
|
||||
```typescript
|
||||
// server.ts
|
||||
import { Hono } from "hono";
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
app.get("/api/premium", async (c) => {
|
||||
const result = await settlePayment({
|
||||
resourceUrl: new URL(c.req.url).toString(),
|
||||
method: c.req.method,
|
||||
paymentData: c.req.header("x-payment"),
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.05",
|
||||
facilitator: thirdwebFacilitator,
|
||||
routeConfig: {
|
||||
description: "Access to premium content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
return c.json(
|
||||
{ message: "This is premium content!" },
|
||||
{ headers: result.responseHeaders }
|
||||
);
|
||||
} else {
|
||||
return c.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export default app;
|
||||
```
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Middleware Examples
|
||||
|
||||
Protect multiple endpoints with a shared middleware:
|
||||
|
||||
<Tabs defaultValue="nextjs">
|
||||
<TabsList>
|
||||
<TabsTrigger value="nextjs">Next.js</TabsTrigger>
|
||||
<TabsTrigger value="express">Express</TabsTrigger>
|
||||
<TabsTrigger value="hono">Hono</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="nextjs">
|
||||
```typescript
|
||||
// middleware.ts
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
const method = request.method.toUpperCase();
|
||||
const resourceUrl = request.nextUrl.toString();
|
||||
const paymentData = request.headers.get("x-payment");
|
||||
|
||||
const result = await settlePayment({
|
||||
resourceUrl,
|
||||
method,
|
||||
paymentData,
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.01",
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
facilitator: thirdwebFacilitator,
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// Payment successful, continue to the route
|
||||
const response = NextResponse.next();
|
||||
// Set payment receipt headers
|
||||
for (const [key, value] of Object.entries(result.responseHeaders)) {
|
||||
response.headers.set(key, value);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
// Payment required
|
||||
return NextResponse.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
// Configure which paths the middleware should run on
|
||||
export const config = {
|
||||
matcher: ["/api/paid/:path*"],
|
||||
};
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="express">
|
||||
```typescript
|
||||
// middleware.ts
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
export async function paymentMiddleware(req, res, next) {
|
||||
const result = await settlePayment({
|
||||
resourceUrl: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
|
||||
method: req.method,
|
||||
paymentData: req.headers["x-payment"],
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.05",
|
||||
facilitator: thirdwebFacilitator,
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
app.get("/api/premium", paymentMiddleware, (req, res) => {
|
||||
res.json({ message: "This is premium content!" });
|
||||
});
|
||||
```
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="hono">
|
||||
```typescript
|
||||
// middleware.ts
|
||||
import type { Context, Next } from "hono";
|
||||
import { settlePayment, facilitator } from "thirdweb/x402";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
import { arbitrumSepolia } from "thirdweb/chains";
|
||||
|
||||
const client = createThirdwebClient({
|
||||
secretKey: process.env.THIRDWEB_SECRET_KEY,
|
||||
});
|
||||
|
||||
const thirdwebFacilitator = facilitator({
|
||||
client,
|
||||
serverWalletAddress: "0x1234567890123456789012345678901234567890",
|
||||
});
|
||||
|
||||
export async function paymentMiddleware(c: Context, next: Next) {
|
||||
const result = await settlePayment({
|
||||
resourceUrl: new URL(c.req.url).toString(),
|
||||
method: c.req.method,
|
||||
paymentData: c.req.header("x-payment"),
|
||||
payTo: "0x1234567890123456789012345678901234567890",
|
||||
network: arbitrumSepolia,
|
||||
price: "$0.05",
|
||||
facilitator: thirdwebFacilitator,
|
||||
routeConfig: {
|
||||
description: "Access to paid content",
|
||||
mimeType: "application/json",
|
||||
maxTimeoutSeconds: 300,
|
||||
},
|
||||
});
|
||||
|
||||
if (result.status === 200) {
|
||||
// Set payment receipt headers and continue
|
||||
Object.entries(result.responseHeaders).forEach(([key, value]) => {
|
||||
c.header(key, value);
|
||||
});
|
||||
await next();
|
||||
} else {
|
||||
return c.json(result.responseBody, {
|
||||
status: result.status,
|
||||
headers: result.responseHeaders,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
app.get("/api/premium", paymentMiddleware, (c) => {
|
||||
return c.json({ message: "This is premium content!" });
|
||||
});
|
||||
```
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Price Configuration
|
||||
|
||||
You can specify prices in multiple ways:
|
||||
|
||||
### USD String
|
||||
|
||||
```typescript
|
||||
price: "$0.10" // 10 cents in USD
|
||||
```
|
||||
|
||||
### ERC20 Token
|
||||
|
||||
```typescript
|
||||
price: {
|
||||
amount: "100000", // Amount in base units (100000 = 0.1 USDC with 6 decimals)
|
||||
asset: {
|
||||
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // Token address
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Native Token
|
||||
|
||||
Payments in native tokens are not currently supported.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 376 KiB |
@@ -0,0 +1,63 @@
|
||||
# Gas Sponsorship Policies
|
||||
|
||||
Sponsorship policies are a way to control the execution of sponsored transactions on your account.
|
||||
|
||||
You can use them to:
|
||||
|
||||
- Set global spend limits.
|
||||
- Restrict sponsorship to a particular chain.
|
||||
- Restrict sponsorship to a particular contract.
|
||||
- Allow/Disallow specific wallets
|
||||
- Setup your own server verifier.
|
||||
|
||||
These policies can be set from your project dashboard, under project > account abstraction > settings.
|
||||
|
||||
## Server Verifier
|
||||
|
||||
The most flexible and powerful way to control the execution of sponsored transactions is to setup your own server verifier.
|
||||
|
||||
In the project dashboard, under project > account abstraction > settings, setup your backend URL and any additional headers you need to pass to the verifier.
|
||||
|
||||
On every user transaction, your backend will be called with the transaction data and the user's wallet address, your endpoint should return a boolean indicating whether the transaction should be sponsored.
|
||||
|
||||
### Backend endpoint specification:
|
||||
|
||||
Your backend will be called with the following request:
|
||||
|
||||
```http
|
||||
POST https://your-backend-url/verify-transaction
|
||||
Content-Type: application/json
|
||||
Referer: "https://api.thirdweb.com",
|
||||
# additional custom headers
|
||||
|
||||
# request body
|
||||
{
|
||||
"clientId": string;
|
||||
"chainId": number;
|
||||
"userOp": {
|
||||
sender: string;
|
||||
targets: string[];
|
||||
gasLimit: string;
|
||||
gasPrice: string;
|
||||
data?: {
|
||||
targets: string[];
|
||||
callDatas: string[];
|
||||
values: string[];
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Your backend should process the request, apply your own policy logic based on the request data and return the following JSON response:
|
||||
|
||||
```http
|
||||
HTTP/1.1 200 OK
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"isAllowed": boolean;
|
||||
"reason"?: string;
|
||||
}
|
||||
```
|
||||
|
||||
The `isAllowed` field indicates whether the transaction should be sponsored or not. `reason` is an optional field that can be used to provide a reason for the decision.
|
||||
@@ -42,6 +42,10 @@ export const sidebar: SideBar = {
|
||||
href: `${transactionsSlug}/session-keys`,
|
||||
name: "Session Keys",
|
||||
},
|
||||
{
|
||||
href: `${transactionsSlug}/policies`,
|
||||
name: "Sponsorship Policies",
|
||||
},
|
||||
],
|
||||
},
|
||||
{ separator: true },
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@doc";
|
||||
|
||||
# Session Keys Guide
|
||||
|
||||
Session keys enable secure transaction execution on behalf of accounts without requiring direct access to the main account's private key. This guide covers session keys for both ERC-4337 smart accounts and ERC-7702 smart EOAs (Externally Owned Accounts).
|
||||
|
||||
<Tabs defaultValue="erc7702">
|
||||
<TabsList>
|
||||
<TabsTrigger value="erc7702">EIP-7702 Upgraded EOAs</TabsTrigger>
|
||||
<TabsTrigger value="erc4337">ERC-4337 Smart Accounts</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="erc4337">
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, ensure you have:
|
||||
- A thirdweb client configured
|
||||
- Access to a session key account address
|
||||
|
||||
## Setup
|
||||
|
||||
First, let's set up the necessary imports and configuration:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
generateAccount,
|
||||
smartWallet,
|
||||
sendTransaction,
|
||||
getContract,
|
||||
createThirdwebClient
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { getAllActiveSigners } from "thirdweb/extensions/erc4337";
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
// Configure your client
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key" // Only use in server environments
|
||||
});
|
||||
|
||||
// Your session key account address
|
||||
const sessionKeyAccountAddress = "0x..."; // Replace with your session key address (server wallet)
|
||||
|
||||
// Target address for transactions
|
||||
const targetAddress = "0x..."; // Replace with your target address
|
||||
```
|
||||
|
||||
## Step 1: Configure User Smart Wallet with Session Key
|
||||
|
||||
The first step is to add our session key address as a signer to the user's smart account. This is typically done on the client side since it needs explicit user approval. This can be done by configuring the smart wallet with the session key address and permissions.
|
||||
|
||||
In a React application, this can be done by using the `ConnectButton` or `ConnectEmbed` component. This will automatically configure the smart wallet with the session key address and permissions.
|
||||
|
||||
```typescript
|
||||
<ConnectButton
|
||||
accountAbstraction={{
|
||||
chain: sepolia,
|
||||
sessionKey: {
|
||||
address: sessionKeyAccountAddress,
|
||||
permissions: {
|
||||
// "*" allows all targets, or specify specific contract addresses
|
||||
approvedTargets: "*",
|
||||
},
|
||||
},
|
||||
sponsorGas: true,
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
This can also be done in pure TypeScript by using the `smartWallet` function and connecting it to a personal account.
|
||||
|
||||
For this guide, we'll generate a random personal account that will be used to create the smart wallet:
|
||||
|
||||
```typescript
|
||||
// this would be the user's personal account
|
||||
const personalAccount = await generateAccount({
|
||||
client: client,
|
||||
});
|
||||
|
||||
// wrapped in a smart wallet with session key permissions
|
||||
const smart = smartWallet({
|
||||
chain: sepolia,
|
||||
sessionKey: {
|
||||
address: sessionKeyAccountAddress,
|
||||
permissions: {
|
||||
// "*" allows all targets, or specify specific contract addresses
|
||||
approvedTargets: "*",
|
||||
},
|
||||
},
|
||||
sponsorGas: true, // Enable gas sponsorship
|
||||
});
|
||||
|
||||
console.log("Personal account created:", personalAccount.address);
|
||||
```
|
||||
|
||||
### Session Key Permissions
|
||||
|
||||
The `permissions` object allows you to control what the session key can do:
|
||||
|
||||
- `approvedTargets`: Specify which contract addresses the session key can interact with
|
||||
- Use `"*"` for all targets
|
||||
- Use an array of addresses for specific contracts: `["0x123...", "0x456..."]`
|
||||
|
||||
## Step 2: Connect Smart Account
|
||||
|
||||
Connect the smart wallet using the personal account:
|
||||
|
||||
```typescript
|
||||
const smartAccount = await smart.connect({
|
||||
client: client,
|
||||
personalAccount: personalAccount,
|
||||
});
|
||||
|
||||
console.log("Smart account address:", smartAccount.address);
|
||||
```
|
||||
|
||||
Note that in a React application, this would be done automatically by the `ConnectButton` or `ConnectEmbed` component.
|
||||
|
||||
## Step 3 (Optional): Verify Session Key Registration
|
||||
|
||||
Check that the session key is properly registered as an active signer:
|
||||
|
||||
```typescript
|
||||
const signers = await getAllActiveSigners({
|
||||
contract: getContract({
|
||||
address: smartAccount.address,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
}),
|
||||
});
|
||||
|
||||
// Verify the session key is in the list of active signers
|
||||
const isSessionKeyActive = signers
|
||||
.map((s) => s.signer)
|
||||
.includes(sessionKeyAccountAddress);
|
||||
|
||||
console.log("Session key is active:", isSessionKeyActive);
|
||||
console.log("All active signers:", signers.map((s) => s.signer));
|
||||
```
|
||||
|
||||
## Step 4: Create Engine Server Wallet
|
||||
|
||||
Set up an Engine server wallet using the session key for transaction execution:
|
||||
|
||||
```typescript
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
executionOptions: {
|
||||
entrypointVersion: "0.6", // ERC-4337 entrypoint version
|
||||
signerAddress: sessionKeyAccountAddress,
|
||||
smartAccountAddress: smartAccount.address,
|
||||
type: "ERC4337",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Execution Options
|
||||
|
||||
- `entrypointVersion`: The ERC-4337 entrypoint version to use
|
||||
- `signerAddress`: The session key address that will sign transactions
|
||||
- `smartAccountAddress`: The smart account address that will execute transactions
|
||||
- `type`: The account abstraction type (ERC4337)
|
||||
|
||||
## Step 5: Execute Transactions
|
||||
|
||||
Now you can execute transactions using the session key, here we are sending 0 ETH to the target address for testing purposes:
|
||||
|
||||
```typescript
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: {
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: targetAddress,
|
||||
value: 0n, // Amount in wei (0 for no ETH transfer)
|
||||
// data: "0x...", // Optional: contract call data
|
||||
},
|
||||
});
|
||||
|
||||
console.log("Transaction sent:", tx.transactionHash);
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a complete example putting it all together:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
generateAccount,
|
||||
smartWallet,
|
||||
sendTransaction,
|
||||
getContract,
|
||||
createThirdwebClient
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { getAllActiveSigners } from "thirdweb/extensions/erc4337";
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
async function executeTransactionWithSessionKey() {
|
||||
// Configuration
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key"
|
||||
});
|
||||
|
||||
const sessionKeyAccountAddress = "0x..."; // Your session key address (server wallet)
|
||||
const targetAddress = "0x..."; // Target address for the final transaction
|
||||
|
||||
try {
|
||||
// Step 1: Create personal account
|
||||
const personalAccount = await generateAccount({ client });
|
||||
|
||||
// Step 2: Configure smart wallet
|
||||
const smart = smartWallet({
|
||||
chain: sepolia,
|
||||
sessionKey: {
|
||||
address: sessionKeyAccountAddress,
|
||||
permissions: {
|
||||
approvedTargets: "*",
|
||||
},
|
||||
},
|
||||
sponsorGas: true,
|
||||
});
|
||||
|
||||
// Step 3: Connect smart account
|
||||
const smartAccount = await smart.connect({
|
||||
client,
|
||||
personalAccount,
|
||||
});
|
||||
|
||||
// Step 4: Verify session key
|
||||
const signers = await getAllActiveSigners({
|
||||
contract: getContract({
|
||||
address: smartAccount.address,
|
||||
chain: sepolia,
|
||||
client,
|
||||
}),
|
||||
});
|
||||
|
||||
const isSessionKeyActive = signers
|
||||
.map((s) => s.signer)
|
||||
.includes(sessionKeyAccountAddress);
|
||||
|
||||
if (!isSessionKeyActive) {
|
||||
throw new Error("Session key is not active");
|
||||
}
|
||||
|
||||
// Step 5: Create server wallet
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client,
|
||||
executionOptions: {
|
||||
entrypointVersion: "0.6",
|
||||
signerAddress: sessionKeyAccountAddress,
|
||||
smartAccountAddress: smartAccount.address,
|
||||
type: "ERC4337",
|
||||
},
|
||||
});
|
||||
|
||||
// Step 6: Execute transaction
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: {
|
||||
chain: sepolia,
|
||||
client,
|
||||
to: targetAddress,
|
||||
value: 0n,
|
||||
},
|
||||
});
|
||||
|
||||
console.log("Transaction successful:", tx.transactionHash);
|
||||
return tx;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error executing transaction:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the function
|
||||
executeTransactionWithSessionKey()
|
||||
.then((tx) => console.log("Done!", tx.transactionHash))
|
||||
.catch((error) => console.error("Failed:", error));
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Session Key Storage**: Store session keys securely, preferably in a vault system
|
||||
- **Permission Scope**: Limit session key permissions to only necessary targets
|
||||
- **Key Rotation**: Regularly rotate session keys for enhanced security
|
||||
- **Monitoring**: Monitor session key usage for suspicious activity
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Session key not active**: Ensure the session key is properly registered with the smart account
|
||||
2. **Permission denied**: Check that the target address is included in `approvedTargets`
|
||||
3. **Gas estimation failed**: Verify that gas sponsorship is properly configured
|
||||
|
||||
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="erc7702">
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, ensure you have:
|
||||
- A thirdweb client configured
|
||||
- An in-app wallet with ERC-7702 support
|
||||
- A session key account address (can be generated or an existing wallet)
|
||||
|
||||
## Setup
|
||||
|
||||
First, let's set up the necessary imports and configuration:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createThirdwebClient,
|
||||
getContract,
|
||||
sendTransaction,
|
||||
prepareTransaction
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { inAppWallet, createSessionKey } from "thirdweb/wallets/in-app";
|
||||
|
||||
// Configure your client
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key" // Only use in server environments
|
||||
});
|
||||
|
||||
// Your session key account address
|
||||
const sessionKeyAccountAddress = "0x..."; // Replace with your session key address (server wallet)
|
||||
```
|
||||
|
||||
## Step 1: Create ERC-7702 Smart EOA
|
||||
|
||||
Create an in-app wallet configured with ERC-7702 execution mode:
|
||||
|
||||
```typescript
|
||||
const wallet = inAppWallet({
|
||||
executionMode: {
|
||||
mode: "EIP7702",
|
||||
sponsorGas: true, // Enable gas sponsorship
|
||||
},
|
||||
});
|
||||
|
||||
// Connect the wallet (user authentication)
|
||||
const account = await wallet.connect({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
strategy: "google", // or "email", "guest", etc.
|
||||
});
|
||||
|
||||
console.log("Upgraded EOA address:", account.address);
|
||||
```
|
||||
|
||||
### Execution Modes
|
||||
|
||||
The `executionMode` option allows you to configure the wallet behavior:
|
||||
|
||||
- `mode`: Set to `"EIP7702"` for EIP-7702 upgraded EOA functionality
|
||||
- `sponsorGas`: Enable gas sponsorship for gasless transactions
|
||||
|
||||
## Step 2: Get Account Contract
|
||||
|
||||
Create a contract instance for the deployed smart EOA:
|
||||
|
||||
```typescript
|
||||
const accountContract = getContract({
|
||||
address: account.address,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
});
|
||||
```
|
||||
|
||||
## Step 3: Create Session Key with Full Permissions
|
||||
|
||||
Add a session key with full execution permissions:
|
||||
|
||||
```typescript
|
||||
const tx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: true, // Allow unrestricted access
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key created:", tx.transactionHash);
|
||||
```
|
||||
|
||||
### Session Key Options
|
||||
|
||||
- `account`: The admin account that will create the session key
|
||||
- `contract`: The smart EOA contract instance
|
||||
- `sessionKeyAddress`: The address that will be granted session key permissions
|
||||
- `durationInSeconds`: How long the session key should be valid (in seconds)
|
||||
- `grantFullPermissions`: If `true`, grants unrestricted access. If `false`, you must specify policies.
|
||||
|
||||
## Step 4 (Advanced): Create Session Key with Granular Permissions
|
||||
|
||||
For more fine-grained control, you can specify call and transfer policies:
|
||||
|
||||
```typescript
|
||||
import { Condition, LimitType } from "thirdweb/wallets/in-app";
|
||||
|
||||
const tx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: false, // Use granular permissions
|
||||
callPolicies: [
|
||||
{
|
||||
target: "0x123...", // Target contract address
|
||||
selector: "0xa9059cbb", // Function selector (e.g., ERC20 transfer)
|
||||
maxValuePerUse: 0n, // Max ETH value per call
|
||||
valueLimit: {
|
||||
limitType: LimitType.Lifetime, // Lifetime limit
|
||||
limit: 1000000n, // Max total value in wei
|
||||
period: 0n, // Not used for lifetime limits
|
||||
},
|
||||
constraints: [
|
||||
{
|
||||
condition: Condition.Equal, // Constraint type
|
||||
index: 0n, // Parameter index
|
||||
refValue: "0x000000000000000000000000abc...", // Expected value
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
transferPolicies: [
|
||||
{
|
||||
target: "0x456...", // Recipient address for transfers
|
||||
maxValuePerUse: 100000n, // Max wei per transfer
|
||||
valueLimit: {
|
||||
limitType: LimitType.Allowance, // Allowance-based limit
|
||||
limit: 1000000n, // Total allowance in wei
|
||||
period: 86400n, // Reset period in seconds
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key with policies created:", tx.transactionHash);
|
||||
```
|
||||
|
||||
### Permission Types
|
||||
|
||||
#### Call Policies
|
||||
|
||||
Control which smart contract calls the session key can make:
|
||||
|
||||
- `target`: The contract address the session key can call
|
||||
- `selector`: The function selector (4-byte identifier) that can be called
|
||||
- `maxValuePerUse`: Maximum ETH value that can be sent per transaction
|
||||
- `valueLimit`: Total value limits over time
|
||||
- `constraints`: Parameter-level constraints for function calls
|
||||
|
||||
#### Transfer Policies
|
||||
|
||||
Control native token transfers the session key can make:
|
||||
|
||||
- `target`: The recipient address for transfers
|
||||
- `maxValuePerUse`: Maximum wei per individual transfer
|
||||
- `valueLimit`: Total transfer limits over time
|
||||
|
||||
#### Limit Types
|
||||
|
||||
```typescript
|
||||
enum LimitType {
|
||||
Unlimited = 0, // No limit
|
||||
Lifetime = 1, // One-time total limit
|
||||
Allowance = 2, // Renewable allowance based on period
|
||||
}
|
||||
```
|
||||
|
||||
#### Constraint Conditions
|
||||
|
||||
```typescript
|
||||
enum Condition {
|
||||
Unconstrained = 0, // No constraint
|
||||
Equal = 1, // Must equal reference value
|
||||
Greater = 2, // Must be greater than reference value
|
||||
Less = 3, // Must be less than reference value
|
||||
GreaterOrEqual = 4, // Must be >= reference value
|
||||
LessOrEqual = 5, // Must be <= reference value
|
||||
NotEqual = 6, // Must not equal reference value
|
||||
}
|
||||
```
|
||||
|
||||
## Step 5: Use the Session Key
|
||||
|
||||
Once created, the session key can be used with Engine or other server-side execution:
|
||||
|
||||
```typescript
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
executionOptions: {
|
||||
type: "EIP7702",
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
accountAddress: account.address,
|
||||
},
|
||||
});
|
||||
|
||||
// Execute transactions with the session key
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: "0x...", // Target address
|
||||
value: 0n,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Transaction executed:", tx.transactionHash);
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a complete example for setting up and using a session key with ERC-7702:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createThirdwebClient,
|
||||
getContract,
|
||||
sendTransaction,
|
||||
prepareTransaction
|
||||
} from "thirdweb";
|
||||
import { sepolia } from "thirdweb/chains";
|
||||
import { inAppWallet, createSessionKey } from "thirdweb/wallets/in-app";
|
||||
import { Engine } from "thirdweb/engine";
|
||||
|
||||
async function setupSessionKeyWith7702() {
|
||||
// Configuration
|
||||
const client = createThirdwebClient({
|
||||
clientId: "your-client-id",
|
||||
secretKey: "your-secret-key"
|
||||
});
|
||||
|
||||
const sessionKeyAccountAddress = "0x..."; // Your session key address (server wallet)
|
||||
|
||||
try {
|
||||
// Step 1: Create 7702 Smart EOA
|
||||
const wallet = inAppWallet({
|
||||
executionMode: {
|
||||
mode: "EIP7702",
|
||||
sponsorGas: true,
|
||||
},
|
||||
});
|
||||
|
||||
const account = await wallet.connect({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
strategy: "google",
|
||||
});
|
||||
|
||||
console.log("Upgraded EOA created:", account.address);
|
||||
|
||||
// Step 2: Get account contract
|
||||
const accountContract = getContract({
|
||||
address: account.address,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
});
|
||||
|
||||
// Step 3: Create session key
|
||||
const sessionTx = await sendTransaction({
|
||||
account: account,
|
||||
transaction: createSessionKey({
|
||||
account: account,
|
||||
contract: accountContract,
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
durationInSeconds: 86400, // 1 day
|
||||
grantFullPermissions: true,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Session key created:", sessionTx.transactionHash);
|
||||
|
||||
// Step 4: Use the session key with Engine
|
||||
const serverWallet = Engine.serverWallet({
|
||||
address: sessionKeyAccountAddress,
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
executionOptions: {
|
||||
type: "EIP7702",
|
||||
sessionKeyAddress: sessionKeyAccountAddress,
|
||||
accountAddress: account.address,
|
||||
},
|
||||
});
|
||||
|
||||
// Execute a transaction with the session key
|
||||
const tx = await sendTransaction({
|
||||
account: serverWallet,
|
||||
transaction: prepareTransaction({
|
||||
chain: sepolia,
|
||||
client: client,
|
||||
to: "0x...", // Target address
|
||||
value: 0n,
|
||||
}),
|
||||
});
|
||||
|
||||
console.log("Transaction successful:", tx.transactionHash);
|
||||
return tx;
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the function
|
||||
setupSessionKeyWith7702()
|
||||
.then((tx) => console.log("Done!", tx.transactionHash))
|
||||
.catch((error) => console.error("Failed:", error));
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Session Key Storage**: Store session keys securely, preferably in a vault system
|
||||
- **Permission Scope**: Use granular permissions (`grantFullPermissions: false`) for production use cases
|
||||
- **Time Limits**: Set appropriate `durationInSeconds` values based on your use case
|
||||
- **Policy Design**: Carefully design call and transfer policies to minimize risk
|
||||
- **Key Rotation**: Regularly rotate session keys and revoke unused ones
|
||||
- **Monitoring**: Monitor session key usage for suspicious activity
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Account not deployed**: Ensure you've sent a transaction to trigger the account deployment/upgrade
|
||||
2. **Invalid signature**: Make sure the admin account is properly authenticated and can sign typed data
|
||||
3. **Permission denied**: Verify the session key has the necessary policies for the operation
|
||||
4. **Expired session key**: Check that the current time is within the session key's validity period
|
||||
|
||||
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Learn more about [In-App Wallets](/wallets/users)
|
||||
- Explore the [API Reference](/reference)
|
||||
- Check out the [TypeScript SDK](/references/typescript/v5) documentation
|
||||
@@ -65,6 +65,10 @@ export const sidebar: SideBar = {
|
||||
href: `${walletSlug}/export-private-key`,
|
||||
name: "Export Private Keys",
|
||||
},
|
||||
{
|
||||
href: `${walletSlug}/session-keys`,
|
||||
name: "Session Keys",
|
||||
},
|
||||
{
|
||||
href: `${walletSlug}/adapters`,
|
||||
name: "Usage with other libraries",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user