Compare commits
104
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c328aa13a6 | ||
|
|
a85ef0b222 | ||
|
|
51177fbe17 | ||
|
|
1338a0cf2c | ||
|
|
96ebf378ff | ||
|
|
b7732d3a75 | ||
|
|
6f88d38ad2 | ||
|
|
d53f8a25b4 | ||
|
|
dd693169bc | ||
|
|
93f913c614 | ||
|
|
02502159b6 | ||
|
|
e9225c3bad | ||
|
|
5967fb8afa | ||
|
|
fddb791f0a | ||
|
|
1732e63bb8 | ||
|
|
7b8ceebb63 | ||
|
|
1d90437d34 | ||
|
|
59616d0082 | ||
|
|
32980f854b | ||
|
|
f3b3b89fca | ||
|
|
44826925d0 | ||
|
|
00dcc346bf | ||
|
|
e0738d68d2 | ||
|
|
e160deb8b7 | ||
|
|
a6f846fc1e | ||
|
|
0e3f3460ad | ||
|
|
552f7025c1 | ||
|
|
15f083912c | ||
|
|
04862de9e4 | ||
|
|
ea46572947 | ||
|
|
f276dcfd76 | ||
|
|
6495b94910 | ||
|
|
210f631cba | ||
|
|
557f0e29e8 | ||
|
|
f9bbf8101c | ||
|
|
59d226512c | ||
|
|
778bf2cc4b | ||
|
|
97e5080fdf | ||
|
|
9f9fadf242 | ||
|
|
224c9d034f | ||
|
|
8b8dfd9bf9 | ||
|
|
70e52188a1 | ||
|
|
c82b606cd2 | ||
|
|
1c6b12449b | ||
|
|
ea8061048a | ||
|
|
3ad9f7deba | ||
|
|
0b454050b1 | ||
|
|
dc1f7ab2ee | ||
|
|
bd17c08891 | ||
|
|
79e3694e37 | ||
|
|
ef15ba7c43 | ||
|
|
a724bc39a2 | ||
|
|
2eaff98d8a | ||
|
|
1759112d72 | ||
|
|
85d6074e92 | ||
|
|
2f6f3a0947 | ||
|
|
4284b9d77b | ||
|
|
b149019318 | ||
|
|
e2ebb602dc | ||
|
|
2d76cf9040 | ||
|
|
e7d0899e76 | ||
|
|
88001cfe49 | ||
|
|
a9c388a613 | ||
|
|
4ff1cf7979 | ||
|
|
e78a984b4e | ||
|
|
e37bd8e994 | ||
|
|
a94cf80dbd | ||
|
|
f789e7663a | ||
|
|
a51f4a0031 | ||
|
|
d06a15ecbb | ||
|
|
61fddefcb1 | ||
|
|
14fe9ee2b9 | ||
|
|
4ca407dbf0 | ||
|
|
f714e5d810 | ||
|
|
a328250be1 | ||
|
|
928704ad5c | ||
|
|
acbbf2039f | ||
|
|
4375e7331f | ||
|
|
22d736cb24 | ||
|
|
bb89561a1b | ||
|
|
c92081b056 | ||
|
|
dc57b850d3 | ||
|
|
6429a238c1 | ||
|
|
769019dd0b | ||
|
|
488a3af154 | ||
|
|
8a29e36934 | ||
|
|
ea98087d41 | ||
|
|
030349bb92 | ||
|
|
17d40afda3 | ||
|
|
bc6309ddc7 | ||
|
|
f47eda6842 | ||
|
|
2328985699 | ||
|
|
18b7f9104f | ||
|
|
82be4fa53a | ||
|
|
dbb2614306 | ||
|
|
b8f496603c | ||
|
|
4c782ad64d | ||
|
|
af6a306955 | ||
|
|
4b319c353d | ||
|
|
aadaf209b5 | ||
|
|
df6f8e2646 | ||
|
|
5b871ac281 | ||
|
|
7eed8e61db | ||
|
|
6ef2f3b37a |
@@ -172,6 +172,8 @@ See our [open source page](https://thirdweb.com/open-source) for more informatio
|
||||
- [Documentation](https://portal.thirdweb.com/)
|
||||
- [Templates](https://thirdweb.com/templates)
|
||||
- [YouTube](https://www.youtube.com/c/thirdweb)
|
||||
- [X/Twitter](https://x.com/thirdweb)
|
||||
- [Telegram](https://t.me/officialthirdweb)
|
||||
|
||||
## Support
|
||||
|
||||
|
||||
@@ -64,3 +64,5 @@ ANALYTICS_SERVICE_URL=""
|
||||
|
||||
# required for billing parts of the dashboard (team -> settings -> billing / invoices)
|
||||
STRIPE_SECRET_KEY=""
|
||||
GROWTH_PLAN_SKU=""
|
||||
PAYMENT_METHOD_CONFIGURATION=""
|
||||
|
||||
@@ -64,4 +64,5 @@ module.exports = [
|
||||
"/enterprise",
|
||||
"/token",
|
||||
"/vault",
|
||||
"/monetize/bridge",
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
],
|
||||
"ignoreBinaries": ["only-allow"],
|
||||
"ignoreDependencies": [
|
||||
"@thirdweb-dev/api",
|
||||
"@thirdweb-dev/service-utils",
|
||||
"@thirdweb-dev/vault-sdk",
|
||||
"thirdweb",
|
||||
|
||||
@@ -21,8 +21,11 @@
|
||||
"@radix-ui/react-tooltip": "1.2.7",
|
||||
"@sentry/nextjs": "9.34.0",
|
||||
"@shazow/whatsabi": "0.22.2",
|
||||
"@stripe/react-stripe-js": "4.0.2",
|
||||
"@stripe/stripe-js": "7.9.0",
|
||||
"@tanstack/react-query": "5.81.5",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@thirdweb-dev/api": "workspace:*",
|
||||
"@thirdweb-dev/service-utils": "workspace:*",
|
||||
"@thirdweb-dev/vault-sdk": "workspace:*",
|
||||
"@vercel/functions": "2.2.2",
|
||||
@@ -34,6 +37,7 @@
|
||||
"compare-versions": "^6.1.0",
|
||||
"date-fns": "4.1.0",
|
||||
"fast-xml-parser": "^5.2.5",
|
||||
"fetch-event-stream": "0.1.5",
|
||||
"fuse.js": "7.1.0",
|
||||
"input-otp": "^1.4.1",
|
||||
"ioredis": "^5.6.1",
|
||||
|
||||
@@ -474,6 +474,11 @@ async function redirects() {
|
||||
destination: "/team/~/~/support",
|
||||
permanent: false,
|
||||
},
|
||||
{
|
||||
source: "/routes",
|
||||
destination: "/tokens",
|
||||
permanent: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ type ProxyActionParams = {
|
||||
body?: string;
|
||||
headers?: Record<string, string>;
|
||||
parseAsText?: boolean;
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
|
||||
type ProxyActionResult<T> =
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import "server-only";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import Stripe from "stripe";
|
||||
import type { Team } from "@/api/team/get-team";
|
||||
import { STRIPE_SECRET_KEY } from "@/constants/server-envs";
|
||||
import {
|
||||
GROWTH_PLAN_SKU,
|
||||
PAYMENT_METHOD_CONFIGURATION,
|
||||
STRIPE_SECRET_KEY,
|
||||
} from "@/constants/server-envs";
|
||||
|
||||
let existingStripe: Stripe | undefined;
|
||||
|
||||
@@ -72,3 +77,59 @@ export async function getStripeBalance(customerId: string) {
|
||||
// Stripe returns a positive balance for credits, so we need to divide by -100 to get the actual balance (as long as the balance is not 0)
|
||||
return customer.balance === 0 ? 0 : customer.balance / -100;
|
||||
}
|
||||
|
||||
export async function fetchClientSecret(team: Team) {
|
||||
"use server";
|
||||
const origin = (await headers()).get("origin");
|
||||
const stripe = getStripe();
|
||||
const customerId = team.stripeCustomerId;
|
||||
|
||||
if (!customerId) {
|
||||
throw new Error("No customer ID found");
|
||||
}
|
||||
|
||||
// Create Checkout Sessions from body params.
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
ui_mode: "embedded",
|
||||
line_items: [
|
||||
{
|
||||
// Provide the exact Price ID (for example, price_1234) of
|
||||
// the product you want to sell
|
||||
price: GROWTH_PLAN_SKU,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
mode: "subscription",
|
||||
|
||||
return_url: `${origin}/get-started/team/${team.slug}/select-plan?session_id={CHECKOUT_SESSION_ID}`,
|
||||
automatic_tax: { enabled: true },
|
||||
allow_promotion_codes: true,
|
||||
customer: customerId,
|
||||
customer_update: {
|
||||
address: "auto",
|
||||
},
|
||||
payment_method_collection: "always",
|
||||
payment_method_configuration: PAYMENT_METHOD_CONFIGURATION,
|
||||
subscription_data: {
|
||||
trial_period_days: 14,
|
||||
trial_settings: {
|
||||
end_behavior: {
|
||||
missing_payment_method: "cancel",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!session.client_secret) {
|
||||
throw new Error("No client secret found");
|
||||
}
|
||||
|
||||
return session.client_secret;
|
||||
}
|
||||
|
||||
export async function getStripeSessionById(sessionId: string) {
|
||||
const session = await getStripe().checkout.sessions.retrieve(sessionId, {
|
||||
expand: ["line_items", "payment_intent"],
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -81,33 +81,6 @@ export function reportOnboardingStarted() {
|
||||
posthog.capture("onboarding started");
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the number of teams that select a paid plan during onboarding
|
||||
* - To know **which** plan was selected
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @jnsdls
|
||||
*
|
||||
*/
|
||||
export function reportOnboardingPlanSelected(properties: {
|
||||
plan: Team["billingPlan"];
|
||||
}) {
|
||||
posthog.capture("onboarding plan selected", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the number of teams that skip the plan-selection step during onboarding
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @jnsdls
|
||||
*
|
||||
*/
|
||||
export function reportOnboardingPlanSelectionSkipped() {
|
||||
posthog.capture("onboarding plan selection skipped");
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the number of teams that invite members during onboarding
|
||||
@@ -161,6 +134,18 @@ export function reportOnboardingMembersUpsellPlanSelected(properties: {
|
||||
posthog.capture("onboarding members upsell plan selected", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the number of teams that completed the team member step during onboarding
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @jnsdls
|
||||
*
|
||||
*/
|
||||
export function reportTeamMemberStepCompleted() {
|
||||
posthog.capture("onboarding members completed");
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the number of teams that completed onboarding
|
||||
@@ -250,6 +235,68 @@ export function reportAssetBuySuccessful(properties: {
|
||||
});
|
||||
}
|
||||
|
||||
type TokenSwapParams = {
|
||||
buyTokenChainId: number;
|
||||
buyTokenAddress: string;
|
||||
sellTokenChainId: number;
|
||||
sellTokenAddress: string;
|
||||
pageType: "asset" | "bridge" | "chain";
|
||||
};
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track number of successful token swaps from the token page
|
||||
* - To track which tokens are being swapped the most
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportTokenSwapSuccessful(properties: TokenSwapParams) {
|
||||
posthog.capture("token swap successful", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track impressions of the swap widget
|
||||
* - To create a funnel "swap widget shown" -> "swap widget successful" to understand the conversion rate
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportSwapWidgetShown(properties: {
|
||||
pageType: "asset" | "bridge" | "chain";
|
||||
}) {
|
||||
posthog.capture("swap widget shown", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track number of failed token swaps from the token page
|
||||
* - To track which tokens are being swapped the most
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportTokenSwapFailed(
|
||||
properties: TokenSwapParams & {
|
||||
errorMessage: string;
|
||||
},
|
||||
) {
|
||||
posthog.capture("token swap failed", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track number of cancelled token swaps from the token page
|
||||
* - To track which tokens are being swapped the most
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportTokenSwapCancelled(properties: TokenSwapParams) {
|
||||
posthog.capture("token swap cancelled", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track number of failed asset purchases from the token page
|
||||
@@ -272,6 +319,26 @@ export function reportAssetBuyFailed(properties: {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track number of cancelled asset purchases from the token page
|
||||
* - To track the errors that users encounter when trying to purchase an asset
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportAssetBuyCancelled(properties: {
|
||||
chainId: number;
|
||||
contractType: AssetContractType;
|
||||
assetType: "nft" | "coin";
|
||||
}) {
|
||||
posthog.capture("asset buy cancelled", {
|
||||
assetType: properties.assetType,
|
||||
chainId: properties.chainId,
|
||||
contractType: properties.contractType,
|
||||
});
|
||||
}
|
||||
|
||||
// Assets Landing Page ----------------------------
|
||||
|
||||
/**
|
||||
@@ -477,6 +544,17 @@ export function reportAssetPageview(properties: {
|
||||
posthog.capture("asset pageview", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To understand which chains are being viewed the most
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @MananTank
|
||||
*/
|
||||
export function reportChainPageview(properties: { chainId: number }) {
|
||||
posthog.capture("chain pageview", properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track the usage of fund wallet modal
|
||||
@@ -547,3 +625,27 @@ export function reportChainInfraRpcOmissionAgreed(properties: {
|
||||
}) {
|
||||
posthog.capture("chain infra checkout rpc omission agreed", properties);
|
||||
}
|
||||
|
||||
// ----------------------------
|
||||
// FEEDBACK
|
||||
// ----------------------------
|
||||
|
||||
/**
|
||||
* ### Why do we need to report this event?
|
||||
* - To track user feedback and sentiment about the product
|
||||
* - To identify common issues or feature requests
|
||||
* - To measure user satisfaction and engagement
|
||||
* - To prioritize product improvements based on user input
|
||||
*
|
||||
* ### Who is responsible for this event?
|
||||
* @gisellechacon
|
||||
*/
|
||||
export function reportProductFeedback(properties: {
|
||||
feedback: string;
|
||||
source: "desktop" | "mobile";
|
||||
}) {
|
||||
posthog.capture("product feedback submitted", {
|
||||
feedback: properties.feedback,
|
||||
source: properties.source,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -297,38 +297,53 @@ export type PaymentsResponse = {
|
||||
totalCount: number;
|
||||
};
|
||||
};
|
||||
|
||||
type BridgePaymentType = "buy" | "sell" | "transfer";
|
||||
type OnrampPaymentType = "onramp";
|
||||
|
||||
export type Payment = {
|
||||
// common
|
||||
id: string;
|
||||
blockNumber?: bigint;
|
||||
transactionId: string;
|
||||
createdAt: string;
|
||||
clientId: string;
|
||||
sender: string;
|
||||
receiver: string;
|
||||
developerFeeRecipient: string;
|
||||
developerFeeBps: number;
|
||||
transactions: Array<{
|
||||
chainId: number;
|
||||
transactionHash: string;
|
||||
}>;
|
||||
status: "PENDING" | "COMPLETED" | "FAILED" | "NOT_FOUND";
|
||||
type: "buy" | "sell" | "transfer";
|
||||
originAmount: bigint;
|
||||
destinationAmount: bigint;
|
||||
purchaseData: unknown;
|
||||
originToken: {
|
||||
address: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
chainId: number;
|
||||
};
|
||||
|
||||
destinationAmount: string;
|
||||
destinationToken: {
|
||||
address: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
chainId: number;
|
||||
};
|
||||
createdAt: string;
|
||||
};
|
||||
purchaseData: unknown;
|
||||
} & (
|
||||
| {
|
||||
type: BridgePaymentType;
|
||||
transactionId: string;
|
||||
blockNumber?: string;
|
||||
sender: string;
|
||||
developerFeeRecipient: string;
|
||||
developerFeeBps: number;
|
||||
originAmount: string;
|
||||
originToken: {
|
||||
address: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
chainId: number;
|
||||
};
|
||||
}
|
||||
| {
|
||||
onrampId: string;
|
||||
type: OnrampPaymentType;
|
||||
}
|
||||
);
|
||||
|
||||
export type BridgePayment = Extract<Payment, { type: BridgePaymentType }>;
|
||||
|
||||
export async function getPayments(props: {
|
||||
clientId: string;
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Chain, ThirdwebClient } from "thirdweb";
|
||||
import { BuyWidget, SwapWidget } from "thirdweb/react";
|
||||
import {
|
||||
reportAssetBuyCancelled,
|
||||
reportAssetBuyFailed,
|
||||
reportAssetBuySuccessful,
|
||||
reportSwapWidgetShown,
|
||||
reportTokenSwapCancelled,
|
||||
reportTokenSwapFailed,
|
||||
reportTokenSwapSuccessful,
|
||||
} from "@/analytics/report";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||
|
||||
export function BuyAndSwapEmbed(props: {
|
||||
client: ThirdwebClient;
|
||||
chain: Chain;
|
||||
tokenAddress: string | undefined;
|
||||
buyAmount: string | undefined;
|
||||
pageType: "asset" | "bridge" | "chain";
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
const [tab, setTab] = useState<"buy" | "swap">("swap");
|
||||
const themeObj = getSDKTheme(theme === "light" ? "light" : "dark");
|
||||
const isMounted = useRef(false);
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
useEffect(() => {
|
||||
if (isMounted.current) {
|
||||
return;
|
||||
}
|
||||
isMounted.current = true;
|
||||
reportSwapWidgetShown({
|
||||
pageType: props.pageType,
|
||||
});
|
||||
}, [props.pageType]);
|
||||
|
||||
return (
|
||||
<div className="bg-card rounded-2xl border overflow-hidden flex flex-col relative z-10">
|
||||
<div className="flex gap-2.5 p-4 border-b border-dashed">
|
||||
<TabButton
|
||||
label="Swap"
|
||||
onClick={() => setTab("swap")}
|
||||
isActive={tab === "swap"}
|
||||
/>
|
||||
<TabButton
|
||||
label="Buy"
|
||||
onClick={() => setTab("buy")}
|
||||
isActive={tab === "buy"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{tab === "buy" && (
|
||||
<BuyWidget
|
||||
amount={props.buyAmount || "1"}
|
||||
chain={props.chain}
|
||||
className="!rounded-2xl !w-full !border-none"
|
||||
title=""
|
||||
client={props.client}
|
||||
connectOptions={{
|
||||
autoConnect: false,
|
||||
}}
|
||||
onError={(e) => {
|
||||
const errorMessage = parseError(e);
|
||||
if (props.pageType === "asset") {
|
||||
reportAssetBuyFailed({
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: "DropERC20",
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
}}
|
||||
onCancel={() => {
|
||||
if (props.pageType === "asset") {
|
||||
reportAssetBuyCancelled({
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: "DropERC20",
|
||||
});
|
||||
}
|
||||
}}
|
||||
onSuccess={() => {
|
||||
if (props.pageType === "asset") {
|
||||
reportAssetBuySuccessful({
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: "DropERC20",
|
||||
});
|
||||
}
|
||||
}}
|
||||
theme={themeObj}
|
||||
tokenAddress={props.tokenAddress as `0x${string}`}
|
||||
paymentMethods={["card"]}
|
||||
/>
|
||||
)}
|
||||
|
||||
{tab === "swap" && (
|
||||
<SwapWidget
|
||||
client={props.client}
|
||||
theme={themeObj}
|
||||
className="!rounded-2xl !border-none !w-full"
|
||||
prefill={{
|
||||
// buy this token by default
|
||||
buyToken: {
|
||||
chainId: props.chain.id,
|
||||
tokenAddress: props.tokenAddress,
|
||||
},
|
||||
// sell the native token by default (but if buytoken is a native token, don't set)
|
||||
sellToken: props.tokenAddress
|
||||
? {
|
||||
chainId: props.chain.id,
|
||||
}
|
||||
: undefined,
|
||||
}}
|
||||
onError={(error, quote) => {
|
||||
const errorMessage = parseError(error);
|
||||
reportTokenSwapFailed({
|
||||
errorMessage: errorMessage,
|
||||
buyTokenChainId: quote.intent.destinationChainId,
|
||||
buyTokenAddress: quote.intent.destinationTokenAddress,
|
||||
sellTokenChainId: quote.intent.originChainId,
|
||||
sellTokenAddress: quote.intent.originTokenAddress,
|
||||
pageType: props.pageType,
|
||||
});
|
||||
}}
|
||||
onSuccess={(quote) => {
|
||||
reportTokenSwapSuccessful({
|
||||
buyTokenChainId: quote.intent.destinationChainId,
|
||||
buyTokenAddress: quote.intent.destinationTokenAddress,
|
||||
sellTokenChainId: quote.intent.originChainId,
|
||||
sellTokenAddress: quote.intent.originTokenAddress,
|
||||
pageType: props.pageType,
|
||||
});
|
||||
}}
|
||||
onCancel={(quote) => {
|
||||
reportTokenSwapCancelled({
|
||||
buyTokenChainId: quote.intent.destinationChainId,
|
||||
buyTokenAddress: quote.intent.destinationTokenAddress,
|
||||
sellTokenChainId: quote.intent.originChainId,
|
||||
sellTokenAddress: quote.intent.originTokenAddress,
|
||||
pageType: props.pageType,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TabButton(props: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
isActive: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
onClick={props.onClick}
|
||||
className={cn(
|
||||
"rounded-full text-muted-foreground px-5 text-base bg-accent",
|
||||
props.isActive && "text-foreground border-foreground",
|
||||
)}
|
||||
variant="outline"
|
||||
>
|
||||
{props.label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo } from "react";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { Bridge, ThirdwebClient } from "thirdweb";
|
||||
import { MultiSelect } from "@/components/blocks/multi-select";
|
||||
import { SelectWithSearch } from "@/components/blocks/select-with-search";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -296,3 +296,89 @@ export function SingleNetworkSelector(props: {
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type BridgeNetworkSelectorProps = {
|
||||
chainId: number | undefined;
|
||||
onChange: (chainId: number) => void;
|
||||
className?: string;
|
||||
popoverContentClassName?: string;
|
||||
side?: "left" | "right" | "top" | "bottom";
|
||||
align?: "center" | "start" | "end";
|
||||
placeholder?: string;
|
||||
client: ThirdwebClient;
|
||||
chains: Bridge.chains.Result;
|
||||
};
|
||||
|
||||
export function BridgeNetworkSelector(props: BridgeNetworkSelectorProps) {
|
||||
const options = useMemo(() => {
|
||||
return props.chains.map((chain) => {
|
||||
return {
|
||||
label: cleanChainName(chain.name),
|
||||
value: String(chain.chainId),
|
||||
};
|
||||
});
|
||||
}, [props.chains]);
|
||||
|
||||
const searchFn = useCallback(
|
||||
(option: Option, searchValue: string) => {
|
||||
const chain = props.chains.find(
|
||||
(chain) => chain.chainId === Number(option.value),
|
||||
);
|
||||
if (!chain) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Number.isInteger(Number.parseInt(searchValue))) {
|
||||
return String(chain.chainId).startsWith(searchValue);
|
||||
}
|
||||
return chain.name.toLowerCase().includes(searchValue.toLowerCase());
|
||||
},
|
||||
[props.chains],
|
||||
);
|
||||
|
||||
const renderOption = useCallback(
|
||||
(option: Option) => {
|
||||
const chain = props.chains.find(
|
||||
(chain) => chain.chainId === Number(option.value),
|
||||
);
|
||||
if (!chain) {
|
||||
return option.label;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex justify-between gap-4">
|
||||
<span className="flex grow gap-2 truncate text-left">
|
||||
<ChainIconClient
|
||||
className="size-5"
|
||||
client={props.client}
|
||||
src={chain.icon}
|
||||
loading="lazy"
|
||||
/>
|
||||
{cleanChainName(chain.name)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[props.chains, props.client],
|
||||
);
|
||||
|
||||
return (
|
||||
<SelectWithSearch
|
||||
align={props.align}
|
||||
className={props.className}
|
||||
closeOnSelect={true}
|
||||
onValueChange={(chainId) => {
|
||||
props.onChange(Number(chainId));
|
||||
}}
|
||||
options={options}
|
||||
overrideSearchFn={searchFn}
|
||||
placeholder={props.placeholder || "Select Chain"}
|
||||
popoverContentClassName={props.popoverContentClassName}
|
||||
renderOption={renderOption}
|
||||
searchPlaceholder="Search by Name or Chain ID"
|
||||
showCheck={false}
|
||||
side={props.side}
|
||||
value={props.chainId?.toString()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { type Dispatch, type SetStateAction, useMemo } from "react";
|
||||
import { CodeClient } from "@/components/ui/code/code.client";
|
||||
@@ -6,11 +7,14 @@ import { TabButtons } from "@/components/ui/tabs";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type CodeEnvironment =
|
||||
| "api"
|
||||
| "javascript"
|
||||
| "typescript"
|
||||
| "react"
|
||||
| "react-native"
|
||||
| "unity";
|
||||
| "dotnet"
|
||||
| "unity"
|
||||
| "curl";
|
||||
|
||||
type SupportedEnvironment = {
|
||||
environment: CodeEnvironment;
|
||||
@@ -20,6 +24,10 @@ type SupportedEnvironment = {
|
||||
type CodeSnippet = Partial<Record<CodeEnvironment, string>>;
|
||||
|
||||
const Environments: SupportedEnvironment[] = [
|
||||
{
|
||||
environment: "api",
|
||||
title: "API",
|
||||
},
|
||||
{
|
||||
environment: "javascript",
|
||||
title: "JavaScript",
|
||||
@@ -36,10 +44,18 @@ const Environments: SupportedEnvironment[] = [
|
||||
environment: "react-native",
|
||||
title: "React Native",
|
||||
},
|
||||
{
|
||||
environment: "dotnet",
|
||||
title: ".NET",
|
||||
},
|
||||
{
|
||||
environment: "unity",
|
||||
title: "Unity",
|
||||
},
|
||||
{
|
||||
environment: "curl",
|
||||
title: "cURL",
|
||||
},
|
||||
];
|
||||
|
||||
interface CodeSegmentProps {
|
||||
@@ -122,9 +138,14 @@ export const CodeSegment: React.FC<CodeSegmentProps> = ({
|
||||
: activeEnvironment === "react" ||
|
||||
activeEnvironment === "react-native"
|
||||
? "tsx"
|
||||
: activeEnvironment === "unity"
|
||||
: activeEnvironment === "unity" ||
|
||||
activeEnvironment === "dotnet"
|
||||
? "cpp"
|
||||
: activeEnvironment
|
||||
: activeEnvironment === "api"
|
||||
? "javascript"
|
||||
: activeEnvironment === "curl"
|
||||
? "bash"
|
||||
: activeEnvironment
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
import { AppFooter } from "@/components/footers/app-footer";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
@@ -91,7 +90,6 @@ export function FullWidthSidebarLayout(props: {
|
||||
<main className="flex min-w-0 grow flex-col max-sm:w-full">
|
||||
{children}
|
||||
</main>
|
||||
<AppFooter />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { GridPattern } from "@/components/ui/background-patterns";
|
||||
|
||||
export function GridPatternEmbedContainer(props: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className=" sm:flex sm:justify-center w-full sm:border sm:border-dashed sm:bg-accent/20 sm:py-12 rounded-lg overflow-hidden relative">
|
||||
<GridPattern
|
||||
width={30}
|
||||
height={30}
|
||||
x={-1}
|
||||
y={-1}
|
||||
strokeDasharray={"4 2"}
|
||||
className="text-border dark:text-border/70 hidden lg:block"
|
||||
style={{
|
||||
maskImage:
|
||||
"linear-gradient(to bottom right,white,transparent,transparent)",
|
||||
}}
|
||||
/>
|
||||
<div className="sm:w-[420px] z-10">{props.children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,7 @@ type Action =
|
||||
component: React.ReactNode;
|
||||
};
|
||||
|
||||
function Action(props: { action: Action; variant?: "default" | "secondary" }) {
|
||||
function Action(props: { action: Action; variant?: "default" | "outline" }) {
|
||||
const action = props.action;
|
||||
|
||||
return "component" in action ? (
|
||||
@@ -31,10 +31,7 @@ function Action(props: { action: Action; variant?: "default" | "secondary" }) {
|
||||
) : (
|
||||
<Button
|
||||
asChild
|
||||
className={cn(
|
||||
"rounded-full",
|
||||
props.variant === "secondary" && "border border-border",
|
||||
)}
|
||||
className={cn("rounded-full")}
|
||||
size="sm"
|
||||
variant={props.variant}
|
||||
>
|
||||
@@ -60,7 +57,7 @@ export type ProjectPageHeaderProps = {
|
||||
icon: React.FC<{ className?: string }>;
|
||||
isProjectIcon?: boolean;
|
||||
actions: {
|
||||
primary: Action;
|
||||
primary?: Action;
|
||||
secondary?: Action;
|
||||
} | null;
|
||||
|
||||
@@ -114,7 +111,7 @@ export function ProjectPageHeader(props: ProjectPageHeaderProps) {
|
||||
{props.actions && (
|
||||
<div className="hidden lg:flex items-center gap-3">
|
||||
{props.actions.secondary && (
|
||||
<Action action={props.actions.secondary} variant="secondary" />
|
||||
<Action action={props.actions.secondary} variant="outline" />
|
||||
)}
|
||||
|
||||
{props.actions.primary && (
|
||||
@@ -132,7 +129,7 @@ export function ProjectPageHeader(props: ProjectPageHeaderProps) {
|
||||
{props.title}
|
||||
</h2>
|
||||
{/* description */}
|
||||
<p className="text-sm text-muted-foreground line-clamp-3 md:line-clamp-2">
|
||||
<p className="text-sm text-muted-foreground text-pretty">
|
||||
{props.description}
|
||||
</p>
|
||||
</div>
|
||||
@@ -145,7 +142,7 @@ export function ProjectPageHeader(props: ProjectPageHeaderProps) {
|
||||
)}
|
||||
|
||||
{props.actions?.secondary && (
|
||||
<Action action={props.actions.secondary} variant="secondary" />
|
||||
<Action action={props.actions.secondary} variant="outline" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -87,7 +87,7 @@ export function ChatBar(props: {
|
||||
<PopoverContent className="w-72">
|
||||
<div>
|
||||
<p className="mb-3 text-muted-foreground text-sm">
|
||||
Get access to image uploads by signing in to Nebula
|
||||
Get access to image uploads by signing in to thirdweb
|
||||
</p>
|
||||
<Button
|
||||
className="w-full"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { MessageCircleIcon, XIcon } from "lucide-react";
|
||||
import { CircleQuestionMarkIcon, XIcon } from "lucide-react";
|
||||
import { useSelectedLayoutSegments } from "next/navigation";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { createThirdwebClient } from "thirdweb";
|
||||
@@ -16,7 +16,6 @@ const client = createThirdwebClient({
|
||||
});
|
||||
|
||||
export function CustomChatButton(props: {
|
||||
label: string;
|
||||
examplePrompts: string[];
|
||||
authToken: string;
|
||||
team: Team;
|
||||
@@ -28,7 +27,10 @@ export function CustomChatButton(props: {
|
||||
const closeModal = useCallback(() => setIsOpen(false), []);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
if (layoutSegments[0] === "~" && layoutSegments[1] === "support") {
|
||||
if (
|
||||
(layoutSegments[0] === "~" && layoutSegments[1] === "support") ||
|
||||
layoutSegments.includes("ai")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -36,21 +38,25 @@ export function CustomChatButton(props: {
|
||||
<>
|
||||
{/* Inline Button (not floating) */}
|
||||
<Button
|
||||
className="gap-2 rounded-full shadow-lg"
|
||||
className={cn(
|
||||
"gap-2 rounded-full shadow-lg fixed right-6 bottom-6 z-50 bg-card",
|
||||
isOpen && "opacity-0",
|
||||
)}
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setIsOpen(true);
|
||||
setHasBeenOpened(true);
|
||||
}}
|
||||
variant="default"
|
||||
variant="outline"
|
||||
>
|
||||
<MessageCircleIcon className="size-4" />
|
||||
{props.label}
|
||||
<CircleQuestionMarkIcon className="size-3.5 text-muted-foreground" />
|
||||
Need help?
|
||||
</Button>
|
||||
|
||||
{/* Popup/Modal */}
|
||||
<div
|
||||
className={cn(
|
||||
"slide-in-from-bottom-20 zoom-in-95 fade-in-0 fixed bottom-0 left-0 z-50 flex h-[80vh] w-[100vw] animate-in flex-col overflow-hidden rounded-t-2xl border bg-background shadow-2xl duration-200 lg:right-6 lg:bottom-6 lg:left-auto lg:h-[80vh] lg:max-w-xl lg:rounded-xl",
|
||||
"slide-in-from-bottom-20 zoom-in-95 fade-in-0 fixed bottom-0 left-0 z-50 flex h-[80vh] w-[100vw] animate-in flex-col overflow-hidden rounded-t-2xl border bg-background shadow-2xl duration-200 lg:right-6 lg:bottom-6 lg:left-auto lg:h-[80vh] lg:max-w-xl lg:rounded-2xl",
|
||||
!isOpen && "hidden",
|
||||
)}
|
||||
ref={ref}
|
||||
@@ -58,8 +64,7 @@ export function CustomChatButton(props: {
|
||||
{/* Header with close button */}
|
||||
<div className="flex items-center justify-between border-b px-4 py-4">
|
||||
<div className="flex items-center gap-2 font-semibold text-lg">
|
||||
<MessageCircleIcon className="size-5 text-muted-foreground" />
|
||||
{props.label}
|
||||
Need help?
|
||||
</div>
|
||||
<Button
|
||||
aria-label="Close chat"
|
||||
|
||||
@@ -65,6 +65,23 @@ export default function Component() {
|
||||
events: [preparedEvent]
|
||||
});
|
||||
}`,
|
||||
unity: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebManager.Instance.GetContract(
|
||||
address: "{{contract_address}}",
|
||||
chainId: {{chainId}},
|
||||
);
|
||||
|
||||
// Listen to contract events
|
||||
var events = await contract.Events("{{function}}");`,
|
||||
dotnet: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebContract.Create(client, "{{contract_address}}", {{chainId}});
|
||||
|
||||
// Listen to contract events
|
||||
var events = await contract.Events("{{function}}");`,
|
||||
},
|
||||
install: {
|
||||
javascript: "npm i thirdweb",
|
||||
@@ -73,6 +90,9 @@ export default function Component() {
|
||||
unity: `// Download the .unitypackage from the latest release:
|
||||
// https://github.com/thirdweb-dev/unity-sdk/releases
|
||||
// and drag it into your project`,
|
||||
dotnet: `// Install the thirdweb SDK via NuGet:
|
||||
// dotnet add package Thirdweb
|
||||
// Or search for "Thirdweb" in your NuGet package manager`,
|
||||
},
|
||||
read: {
|
||||
javascript: `import { readContract } from "thirdweb";
|
||||
@@ -100,6 +120,33 @@ export default function Component() {
|
||||
params: [{{args}}]
|
||||
});
|
||||
}`,
|
||||
unity: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebManager.Instance.GetContract(
|
||||
address: "{{contract_address}}",
|
||||
chainId: {{chainId}}
|
||||
);
|
||||
|
||||
// Read from the contract
|
||||
var result = await contract.Read<T>(
|
||||
"{{function}}",
|
||||
{{args}}
|
||||
);`,
|
||||
dotnet: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebContract.Create(
|
||||
client,
|
||||
"{{contract_address}}",
|
||||
{{chainId}}
|
||||
);
|
||||
|
||||
// Read from the contract
|
||||
var result = await contract.Read<T>(
|
||||
"{{function}}",
|
||||
{{args}}
|
||||
);`,
|
||||
},
|
||||
setup: {
|
||||
javascript: `import { createThirdwebClient, getContract } from "thirdweb";
|
||||
@@ -165,11 +212,19 @@ function App() {
|
||||
`,
|
||||
unity: `using Thirdweb;
|
||||
|
||||
// Reference the SDK
|
||||
var sdk = ThirdwebManager.Instance.SDK;
|
||||
// Get your contract
|
||||
var contract = await ThirdwebManager.Instance.GetContract(
|
||||
address: "{{contract_address}}",
|
||||
chainId: {{chainId}}
|
||||
);`,
|
||||
dotnet: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = sdk.GetContract("{{contract_address}}");`,
|
||||
var contract = await ThirdwebContract.Create(
|
||||
client,
|
||||
"{{contract_address}}",
|
||||
{{chainId}}
|
||||
);`,
|
||||
},
|
||||
write: {
|
||||
javascript: `import { prepareContractCall, sendTransaction } from "thirdweb";
|
||||
@@ -213,6 +268,123 @@ export default function Component() {
|
||||
sendTransaction(transaction);
|
||||
}
|
||||
}`,
|
||||
unity: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebManager.Instance.GetContract(
|
||||
address: "{{contract_address}}",
|
||||
chainId: {{chainId}}
|
||||
);
|
||||
|
||||
// Write to the contract
|
||||
var transactionReceipt = await contract.Write(
|
||||
wallet,
|
||||
contract,
|
||||
"{{function}}",
|
||||
weiValue,
|
||||
{{args}}
|
||||
);`,
|
||||
dotnet: `using Thirdweb;
|
||||
|
||||
// Get your contract
|
||||
var contract = await ThirdwebContract.Create(
|
||||
client,
|
||||
"{{contract_address}}",
|
||||
{{chainId}}
|
||||
);
|
||||
|
||||
// Write to the contract
|
||||
var transactionReceipt = await contract.Write(
|
||||
wallet,
|
||||
contract,
|
||||
"{{function}}",
|
||||
weiValue,
|
||||
{{args}}
|
||||
);`,
|
||||
},
|
||||
api: {
|
||||
read: `const response = await fetch('https://api.thirdweb.com/v1/contracts/read', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-secret-key': '<YOUR_SECRET_KEY>'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
calls: [
|
||||
{
|
||||
contractAddress: "{{contract_address}}",
|
||||
method: "{{function}}",
|
||||
params: [{{args}}]
|
||||
}
|
||||
],
|
||||
chainId: {{chainId}}
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();`,
|
||||
write: `const response = await fetch('https://api.thirdweb.com/v1/contracts/write', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-secret-key': '<YOUR_SECRET_KEY>'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
calls: [
|
||||
{
|
||||
contractAddress: "{{contract_address}}",
|
||||
method: "{{function}}",
|
||||
params: [{{args}}]
|
||||
}
|
||||
],
|
||||
chainId: {{chainId}},
|
||||
from: "<YOUR_WALLET_ADDRESS>"
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();`,
|
||||
events: `const response = await fetch('https://api.thirdweb.com/v1/contracts/{{chainId}}/{{contract_address}}/events?eventSignature={{function}}', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-secret-key': '<YOUR_SECRET_KEY>'
|
||||
}
|
||||
});
|
||||
|
||||
const data = await response.json();`,
|
||||
},
|
||||
curl: {
|
||||
read: `curl https://api.thirdweb.com/v1/contracts/read \\
|
||||
--request POST \\
|
||||
--header 'Content-Type: application/json' \\
|
||||
--header 'x-secret-key: <YOUR_SECRET_KEY>' \\
|
||||
--data '{
|
||||
"calls": [
|
||||
{
|
||||
"contractAddress": "{{contract_address}}",
|
||||
"method": "{{function}}",
|
||||
"params": [{{args}}]
|
||||
}
|
||||
],
|
||||
"chainId": {{chainId}}
|
||||
}'`,
|
||||
write: `curl -X POST https://api.thirdweb.com/v1/contracts/write \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-H "x-secret-key: <YOUR_SECRET_KEY>" \\
|
||||
-d '{
|
||||
"calls": [
|
||||
{
|
||||
"contractAddress": "{{contract_address}}",
|
||||
"method": "{{function}}",
|
||||
"params": [{{args}}]
|
||||
}
|
||||
],
|
||||
"chainId": {{chainId}},
|
||||
"from": "<YOUR_WALLET_ADDRESS>"
|
||||
}'`,
|
||||
events: `curl https://api.thirdweb.com/v1/contracts/{{chainId}}/{{contract_address}}/events?eventSignature={{function}} \\
|
||||
--request GET \\
|
||||
--header 'Content-Type: application/json' \\
|
||||
--header 'x-secret-key: <YOUR_SECRET_KEY>'`,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -269,20 +441,17 @@ return (
|
||||
|
||||
public async void ConnectWallet()
|
||||
{
|
||||
// Reference to your Thirdweb SDK
|
||||
var sdk = ThirdwebManager.Instance.SDK;
|
||||
|
||||
// Configure the connection
|
||||
var connection = new WalletConnection(
|
||||
provider: WalletProvider.SmartWallet, // The wallet provider you want to connect to (Required)
|
||||
chainId: 1, // The chain you want to connect to (Required)
|
||||
password: "myEpicPassword", // If using a local wallet as personal wallet (Optional)
|
||||
email: "[email protected]", // If using an email wallet as personal wallet (Optional)
|
||||
personalWallet: WalletProvider.LocalWallet // The personal wallet you want to use with your Account (Optional)
|
||||
var wallet = await ConnectWallet(
|
||||
new WalletOptions(
|
||||
provider: WalletProvider.InAppWallet,
|
||||
chainId: {{chainId}},
|
||||
inAppWalletOptions: new InAppWalletOptions(
|
||||
authprovider: AuthProvider.Google,
|
||||
executionMode: ExecutionMode.EIP7702Sponsored
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
// Connect the wallet
|
||||
string address = await sdk.wallet.Connect(connection);
|
||||
string address = await wallet.GetAddress();
|
||||
}`,
|
||||
},
|
||||
},
|
||||
@@ -490,6 +659,9 @@ export function formatSnippet(
|
||||
: "event",
|
||||
});
|
||||
break;
|
||||
case "api":
|
||||
// For API, we don't need special extension handling, just use the standard templates
|
||||
break;
|
||||
}
|
||||
}
|
||||
// end hacks on hacks on hacks -- now just hacks on hacks from here on out
|
||||
@@ -533,7 +705,7 @@ export function CodeOverview(props: {
|
||||
| undefined;
|
||||
|
||||
const [environment, setEnvironment] = useState<CodeEnvironment>(
|
||||
defaultEnvironment || "javascript",
|
||||
defaultEnvironment || "api",
|
||||
);
|
||||
|
||||
const [tab, setTab] = useState("write");
|
||||
@@ -677,7 +849,13 @@ export function CodeOverview(props: {
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-2">
|
||||
{environment === "react-native" || environment === "unity" ? (
|
||||
{environment === "api" || environment === "curl" ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No SDK install required for API/cURL. Call the HTTP endpoints
|
||||
directly. Keep your secret key server-side; use client IDs in
|
||||
frontends.
|
||||
</p>
|
||||
) : environment === "react-native" || environment === "unity" ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Install the latest version of the SDK.{" "}
|
||||
<UnderlineLink
|
||||
@@ -800,32 +978,76 @@ export function CodeOverview(props: {
|
||||
<CodeSegment
|
||||
environment={environment}
|
||||
setEnvironment={setEnvironment}
|
||||
snippet={formatSnippet(
|
||||
// biome-ignore lint/suspicious/noExplicitAny: FIXME
|
||||
COMMANDS[tab as keyof typeof COMMANDS] as any,
|
||||
{
|
||||
snippet={(() => {
|
||||
const selectedFn =
|
||||
tab === "read" ? read : tab === "write" ? write : event;
|
||||
const commandsKey = tab as "read" | "write" | "events";
|
||||
|
||||
const baseSnippet = formatSnippet(COMMANDS[commandsKey], {
|
||||
args:
|
||||
abi
|
||||
?.filter(
|
||||
(f) => f.type === "function" || f.type === "event",
|
||||
)
|
||||
?.find(
|
||||
(f) =>
|
||||
f.name ===
|
||||
(tab === "read"
|
||||
? read?.name
|
||||
: tab === "write"
|
||||
? write?.name
|
||||
: event?.name),
|
||||
)
|
||||
?.find((f) => f.name === selectedFn?.name)
|
||||
?.inputs.map((i) => i.name || "") || [],
|
||||
|
||||
chainId,
|
||||
contractAddress,
|
||||
extensionNamespace,
|
||||
fn: tab === "read" ? read : tab === "write" ? write : event,
|
||||
},
|
||||
)}
|
||||
fn: selectedFn,
|
||||
});
|
||||
|
||||
// Add API snippet if it exists
|
||||
const apiSnippet = COMMANDS.api[commandsKey]
|
||||
? formatSnippet(
|
||||
{ api: COMMANDS.api[commandsKey] },
|
||||
{
|
||||
args:
|
||||
abi
|
||||
?.filter(
|
||||
(f) =>
|
||||
f.type === "function" || f.type === "event",
|
||||
)
|
||||
?.find((f) => f.name === selectedFn?.name)
|
||||
?.inputs.map((i) => i.name || "") || [],
|
||||
|
||||
chainId,
|
||||
contractAddress,
|
||||
extensionNamespace,
|
||||
fn: selectedFn,
|
||||
},
|
||||
)
|
||||
: {};
|
||||
|
||||
// Add cURL snippet if it exists
|
||||
const curlSnippet = COMMANDS.curl[commandsKey]
|
||||
? formatSnippet(
|
||||
{ curl: COMMANDS.curl[commandsKey] },
|
||||
{
|
||||
args:
|
||||
abi
|
||||
?.filter(
|
||||
(f) =>
|
||||
f.type === "function" || f.type === "event",
|
||||
)
|
||||
?.find((f) => f.name === selectedFn?.name)
|
||||
?.inputs.map((i) => i.name || "") || [],
|
||||
|
||||
chainId,
|
||||
contractAddress,
|
||||
extensionNamespace,
|
||||
fn: selectedFn,
|
||||
},
|
||||
)
|
||||
: {};
|
||||
|
||||
return {
|
||||
...baseSnippet,
|
||||
...apiSnippet,
|
||||
...curlSnippet,
|
||||
};
|
||||
})()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -68,7 +68,7 @@ const ContractFunction: React.FC<{
|
||||
|
||||
function ContractFunctionInner(props: ContractFunctionProps) {
|
||||
const { contract, fn } = props;
|
||||
const [environment, setEnvironment] = useState<CodeEnvironment>("javascript");
|
||||
const [environment, setEnvironment] = useState<CodeEnvironment>("api");
|
||||
const functionSelectorQuery = useContractFunctionSelectors(contract);
|
||||
const functionSelectors = functionSelectorQuery.data || [];
|
||||
const isERC721Query = useReadContract(ERC721Ext.isERC721, { contract });
|
||||
@@ -112,7 +112,7 @@ function ContractFunctionInner(props: ContractFunctionProps) {
|
||||
: "write"
|
||||
: ("events" as const);
|
||||
|
||||
const codeSnippet = formatSnippet(COMMANDS[commandsKey], {
|
||||
const baseSnippet = formatSnippet(COMMANDS[commandsKey], {
|
||||
args: fn.inputs?.map((i) => i.name || ""),
|
||||
chainId: contract.chain.id,
|
||||
contractAddress: contract.address,
|
||||
@@ -120,6 +120,40 @@ function ContractFunctionInner(props: ContractFunctionProps) {
|
||||
fn,
|
||||
});
|
||||
|
||||
// Safety check: Only include API snippet if the command exists in COMMANDS.api
|
||||
const apiSnippet = COMMANDS.api[commandsKey]
|
||||
? formatSnippet(
|
||||
{ api: COMMANDS.api[commandsKey] },
|
||||
{
|
||||
args: fn.inputs?.map((i) => i.name || ""),
|
||||
chainId: contract.chain.id,
|
||||
contractAddress: contract.address,
|
||||
extensionNamespace,
|
||||
fn,
|
||||
},
|
||||
)
|
||||
: {};
|
||||
|
||||
// Safety check: Only include cURL snippet if the command exists in COMMANDS.curl
|
||||
const curlSnippet = COMMANDS.curl[commandsKey]
|
||||
? formatSnippet(
|
||||
{ curl: COMMANDS.curl[commandsKey] },
|
||||
{
|
||||
args: fn.inputs?.map((i) => i.name || ""),
|
||||
chainId: contract.chain.id,
|
||||
contractAddress: contract.address,
|
||||
extensionNamespace,
|
||||
fn,
|
||||
},
|
||||
)
|
||||
: {};
|
||||
|
||||
const codeSnippet = {
|
||||
...baseSnippet,
|
||||
...apiSnippet,
|
||||
...curlSnippet,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center flex-wrap gap-2 border-b pb-3 mb-3">
|
||||
|
||||
@@ -231,13 +231,13 @@ function ImportForm(props: {
|
||||
</Button>
|
||||
) : (
|
||||
<Button className="gap-2" type="submit">
|
||||
{addContractToProject.isPending ? (
|
||||
{form.formState.isSubmitting ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<ArrowDownToLineIcon className="size-4" />
|
||||
)}
|
||||
|
||||
{addContractToProject.isPending ? "Importing" : "Import"}
|
||||
{form.formState.isSubmitting ? "Importing" : "Import"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,79 @@
|
||||
import type {
|
||||
ListUserWalletsData,
|
||||
ListUserWalletsResponses,
|
||||
} from "@thirdweb-dev/api";
|
||||
import { configure, listUserWallets } from "@thirdweb-dev/api";
|
||||
import type { WalletUser } from "thirdweb/wallets";
|
||||
import { THIRDWEB_EWS_API_HOST } from "@/constants/urls";
|
||||
import { THIRDWEB_API_HOST } from "@/constants/urls";
|
||||
import type { SearchType } from "./types";
|
||||
|
||||
// Configure the API client to use the correct base URL
|
||||
configure({
|
||||
override: {
|
||||
baseUrl: THIRDWEB_API_HOST,
|
||||
},
|
||||
});
|
||||
|
||||
// Extract types from the generated API
|
||||
type APIWallet = ListUserWalletsResponses[200]["result"]["wallets"][0];
|
||||
type APIProfile = APIWallet["profiles"][0];
|
||||
|
||||
// Transform API response to match existing WalletUser format
|
||||
function transformToWalletUser(apiWallet: APIWallet): WalletUser {
|
||||
return {
|
||||
id: getProfileId(apiWallet.profiles[0]) || "",
|
||||
linkedAccounts: apiWallet.profiles.map((profile) => {
|
||||
// Create details object based on the profile data
|
||||
let details:
|
||||
| { email: string; [key: string]: string }
|
||||
| { phone: string; [key: string]: string }
|
||||
| { address: string; [key: string]: string }
|
||||
| { id: string; [key: string]: string };
|
||||
|
||||
const profileId = getProfileId(profile);
|
||||
|
||||
if ("email" in profile && profile.email) {
|
||||
details = { email: profile.email, id: profileId };
|
||||
} else if ("phone" in profile && profile.phone) {
|
||||
details = { phone: profile.phone, id: profileId };
|
||||
} else if ("walletAddress" in profile && profile.walletAddress) {
|
||||
details = { address: profile.walletAddress, id: profileId };
|
||||
} else {
|
||||
details = { id: profileId };
|
||||
}
|
||||
|
||||
return {
|
||||
type: profile.type,
|
||||
details,
|
||||
};
|
||||
}),
|
||||
wallets: apiWallet.address
|
||||
? [
|
||||
{
|
||||
address: apiWallet.address,
|
||||
createdAt: apiWallet.createdAt || new Date().toISOString(),
|
||||
type: "enclave" as const,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Helper function to safely get ID from any profile type
|
||||
function getProfileId(profile: APIProfile | undefined): string {
|
||||
if (!profile) return "";
|
||||
|
||||
if ("id" in profile) {
|
||||
return profile.id;
|
||||
} else if ("credentialId" in profile) {
|
||||
return profile.credentialId;
|
||||
} else if ("identifier" in profile) {
|
||||
return profile.identifier;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
export async function searchUsers(
|
||||
authToken: string,
|
||||
clientId: string | undefined,
|
||||
@@ -10,50 +82,57 @@ export async function searchUsers(
|
||||
searchType: SearchType,
|
||||
query: string,
|
||||
): Promise<WalletUser[]> {
|
||||
const url = new URL(`${THIRDWEB_EWS_API_HOST}/api/2024-05-05/account/list`);
|
||||
try {
|
||||
// Prepare query parameters
|
||||
const queryParams: ListUserWalletsData["query"] = {
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
// Add clientId or ecosystemSlug parameter
|
||||
if (ecosystemSlug) {
|
||||
url.searchParams.append("ecosystemSlug", `ecosystem.${ecosystemSlug}`);
|
||||
} else if (clientId) {
|
||||
url.searchParams.append("clientId", clientId);
|
||||
// Add search parameter based on search type
|
||||
switch (searchType) {
|
||||
case "email":
|
||||
queryParams.email = query;
|
||||
break;
|
||||
case "phone":
|
||||
queryParams.phone = query;
|
||||
break;
|
||||
case "id":
|
||||
queryParams.id = query;
|
||||
break;
|
||||
case "address":
|
||||
queryParams.address = query;
|
||||
break;
|
||||
case "externalWallet":
|
||||
queryParams.externalWalletAddress = query;
|
||||
break;
|
||||
}
|
||||
|
||||
// Use the generated API function with Bearer authentication
|
||||
const response = await listUserWallets({
|
||||
query: queryParams,
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json",
|
||||
"x-thirdweb-team-id": teamId,
|
||||
...(clientId && { "x-client-id": clientId }),
|
||||
...(ecosystemSlug && {
|
||||
"x-ecosystem-id": `ecosystem.${ecosystemSlug}`,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Handle response
|
||||
if (response.error || !response.data) {
|
||||
console.error(
|
||||
"Error searching users:",
|
||||
response.error || "No data returned",
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
return response.data.result.wallets.map(transformToWalletUser);
|
||||
} catch (error) {
|
||||
console.error("Error searching users:", error);
|
||||
return [];
|
||||
}
|
||||
|
||||
// Add search parameter based on search type
|
||||
switch (searchType) {
|
||||
case "email":
|
||||
url.searchParams.append("email", query);
|
||||
break;
|
||||
case "phone":
|
||||
url.searchParams.append("phone", query);
|
||||
break;
|
||||
case "id":
|
||||
url.searchParams.append("id", query);
|
||||
break;
|
||||
case "address":
|
||||
url.searchParams.append("address", query);
|
||||
break;
|
||||
case "externalWallet":
|
||||
url.searchParams.append("externalWalletAddress", query);
|
||||
break;
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json",
|
||||
"x-thirdweb-team-id": teamId,
|
||||
...(clientId && { "x-client-id": clientId }),
|
||||
},
|
||||
method: "GET",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to search users: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.users as WalletUser[];
|
||||
}
|
||||
|
||||
@@ -56,7 +56,8 @@ export function NotificationsButton(props: { accountId: string }) {
|
||||
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="max-h-[90vh] min-h-[500px] w-[400px] max-w-md p-0"
|
||||
sideOffset={8}
|
||||
className="max-h-[90vh] min-h-[550px] w-[450px] max-w-md p-0 flex flex-col rounded-xl overflow-hidden"
|
||||
>
|
||||
<NotificationList {...manager} />
|
||||
</PopoverContent>
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
parseISO,
|
||||
subDays,
|
||||
} from "date-fns";
|
||||
import { ArchiveIcon } from "lucide-react";
|
||||
import { ArchiveIcon, ArrowUpRightIcon, BellIcon } from "lucide-react";
|
||||
import { useMemo } from "react";
|
||||
import type { Notification } from "@/api/notifications";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -42,39 +42,48 @@ export function NotificationEntry({
|
||||
}, [notification.createdAt]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-row py-1.5">
|
||||
{onMarkAsRead && (
|
||||
<div className="min-h-full w-1 shrink-0 rounded-r-lg bg-primary" />
|
||||
)}
|
||||
<div className="flex w-full flex-row justify-between gap-2 border-b px-4 py-2 transition-colors last:border-b-0">
|
||||
<div className="flex items-start gap-3 p-4 border-b group hover:bg-card last:border-b-0">
|
||||
<div className="p-2.5 rounded-full border bg-card">
|
||||
<BellIcon className="size-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="flex w-full flex-row justify-between gap-2 transition-colors">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1 space-y-1">
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<p className="text-sm">{notification.description}</p>
|
||||
{timeAgo && (
|
||||
<p className="text-muted-foreground text-xs">{timeAgo}</p>
|
||||
)}
|
||||
<div className="flex flex-row justify-between gap-2 pt-1">
|
||||
<Button asChild className="px-0" size="sm" variant="link">
|
||||
<div className="flex flex-row justify-between gap-2 pt-2">
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="rounded-full bg-card gap-2"
|
||||
>
|
||||
<a
|
||||
href={notification.ctaUrl}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{notification.ctaText}
|
||||
<ArrowUpRightIcon className="size-4 text-muted-foreground" />
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{onMarkAsRead && (
|
||||
<Button
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onMarkAsRead(notification.id)}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
>
|
||||
<ArchiveIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
className="p-2 h-auto opacity-0 group-hover:opacity-100 rounded-full text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onMarkAsRead(notification.id)}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
aria-label="Archive notification"
|
||||
>
|
||||
<ArchiveIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -21,15 +21,15 @@ export function NotificationList(props: ReturnType<typeof useNotifications>) {
|
||||
const scrollContainerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-1 flex-col">
|
||||
<div className="flex flex-col overflow-hidden grow">
|
||||
<TabButtons
|
||||
tabClassName="!text-sm hover:!bg-transparent !px-0 !py-1"
|
||||
tabContainerClassName="space-x-6 px-4 pt-2"
|
||||
tabClassName="hover:bg-transparent"
|
||||
tabContainerClassName="pt-1.5 px-4"
|
||||
tabs={[
|
||||
{
|
||||
isActive: activeTab === "inbox",
|
||||
name: (
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
Inbox
|
||||
{props.unreadNotificationsCount > 0 && (
|
||||
<Badge variant="secondary">
|
||||
@@ -49,7 +49,7 @@ export function NotificationList(props: ReturnType<typeof useNotifications>) {
|
||||
/>
|
||||
|
||||
<div
|
||||
className="h-full w-full flex-1 overflow-y-auto"
|
||||
className="flex-1 overflow-y-auto overscroll-contain flex flex-col grow"
|
||||
ref={scrollContainerRef}
|
||||
>
|
||||
{activeTab === "inbox" ? (
|
||||
@@ -93,9 +93,9 @@ function InboxTab(
|
||||
},
|
||||
) {
|
||||
return props.unreadNotifications.length === 0 ? (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||
<BellIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex grow flex-col items-center justify-center gap-4 p-4 text-center">
|
||||
<div className="p-2 bg-card rounded-full border">
|
||||
<BellIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">No new notifications</p>
|
||||
</div>
|
||||
@@ -131,9 +131,9 @@ function ArchiveTab(
|
||||
},
|
||||
) {
|
||||
return props.archivedNotifications.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-4 p-8 text-center">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
|
||||
<ArchiveIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex grow flex-col items-center justify-center gap-4 p-4 text-center">
|
||||
<div className="p-2 bg-card rounded-full border">
|
||||
<ArchiveIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">No archived notifications</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface ImageUploadProps {
|
||||
value: File | undefined;
|
||||
onChange?: (files: File[]) => void;
|
||||
children?: React.ReactNode;
|
||||
variant?: React.ComponentProps<typeof Button>["variant"];
|
||||
className?: string;
|
||||
multiple?: boolean;
|
||||
accept: string;
|
||||
}
|
||||
|
||||
export function ImageUploadButton(props: ImageUploadProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
props.onChange?.(files);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
className={props.className}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
variant={props.variant}
|
||||
>
|
||||
{props.children}
|
||||
</Button>
|
||||
<input
|
||||
accept={props.accept}
|
||||
aria-label="Upload image"
|
||||
className="hidden"
|
||||
multiple={props.multiple}
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -29,3 +29,6 @@ export const NEXT_PUBLIC_THIRDWEB_ENGINE_FAUCET_WALLET =
|
||||
|
||||
export const NEXT_PUBLIC_DEMO_ENGINE_URL =
|
||||
process.env.NEXT_PUBLIC_DEMO_ENGINE_URL || "";
|
||||
|
||||
export const NEXT_PUBLIC_THIRDWEB_AI_HOST =
|
||||
process.env.NEXT_PUBLIC_THIRDWEB_AI_HOST || "https://nebula-api.thirdweb.com";
|
||||
|
||||
@@ -91,3 +91,8 @@ if (REDIS_URL) {
|
||||
REDIS_URL,
|
||||
);
|
||||
}
|
||||
|
||||
// DO NOT TAINT THESE VALUES (for now)
|
||||
export const GROWTH_PLAN_SKU = process.env.GROWTH_PLAN_SKU || "";
|
||||
export const PAYMENT_METHOD_CONFIGURATION =
|
||||
process.env.PAYMENT_METHOD_CONFIGURATION || "";
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export const THIRDWEB_EWS_API_HOST =
|
||||
process.env.NEXT_PUBLIC_THIRDWEB_EWS_API_HOST ||
|
||||
"https://in-app-wallet.thirdweb.com";
|
||||
export const THIRDWEB_API_HOST =
|
||||
process.env.NEXT_PUBLIC_THIRDWEB_API_HOST || "https://api.thirdweb-dev.com";
|
||||
|
||||
export const THIRDWEB_PAY_DOMAIN =
|
||||
process.env.NEXT_PUBLIC_PAY_URL || "pay.thirdweb-dev.com";
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
ListUserWalletsData,
|
||||
ListUserWalletsResponses,
|
||||
} from "@thirdweb-dev/api";
|
||||
import { configure, listUserWallets } from "@thirdweb-dev/api";
|
||||
import { useActiveAccount } from "thirdweb/react";
|
||||
import type { WalletUser } from "thirdweb/wallets";
|
||||
import { THIRDWEB_EWS_API_HOST } from "@/constants/urls";
|
||||
import { THIRDWEB_API_HOST } from "@/constants/urls";
|
||||
import { embeddedWalletsKeys } from "../query-keys/cache-keys";
|
||||
|
||||
// Configure the API client to use the correct base URL
|
||||
configure({
|
||||
override: {
|
||||
baseUrl: THIRDWEB_API_HOST,
|
||||
},
|
||||
});
|
||||
|
||||
// Extract types from the generated API
|
||||
type APIWallet = ListUserWalletsResponses[200]["result"]["wallets"][0];
|
||||
type APIProfile = APIWallet["profiles"][0];
|
||||
|
||||
const fetchAccountList = ({
|
||||
jwt,
|
||||
clientId,
|
||||
@@ -18,37 +34,104 @@ const fetchAccountList = ({
|
||||
pageNumber: number;
|
||||
}) => {
|
||||
return async () => {
|
||||
const url = new URL(`${THIRDWEB_EWS_API_HOST}/api/2024-05-05/account/list`);
|
||||
try {
|
||||
// Prepare query parameters for the new API
|
||||
const queryParams: ListUserWalletsData["query"] = {
|
||||
page: pageNumber,
|
||||
limit: 50, // Keep the same page size
|
||||
};
|
||||
|
||||
// Add clientId or ecosystemSlug parameter
|
||||
if (ecosystemSlug) {
|
||||
url.searchParams.append("ecosystemSlug", `ecosystem.${ecosystemSlug}`);
|
||||
} else if (clientId) {
|
||||
url.searchParams.append("clientId", clientId);
|
||||
// Use the generated API function with Bearer authentication
|
||||
const response = await listUserWallets({
|
||||
query: queryParams,
|
||||
headers: {
|
||||
Authorization: `Bearer ${jwt}`,
|
||||
"Content-Type": "application/json",
|
||||
"x-thirdweb-team-id": teamId,
|
||||
...(clientId && { "x-client-id": clientId }),
|
||||
...(ecosystemSlug && {
|
||||
"x-ecosystem-id": `ecosystem.${ecosystemSlug}`,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
// Handle response
|
||||
if (response.error || !response.data) {
|
||||
const errorMessage =
|
||||
typeof response.error === "string"
|
||||
? response.error
|
||||
: "No data returned";
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Transform the response to match the expected format
|
||||
return {
|
||||
users: response.data.result.wallets.map(transformToWalletUser),
|
||||
hasMore: response.data.result.pagination.hasMore ?? false,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch wallets:", error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
url.searchParams.append("page", pageNumber.toString());
|
||||
|
||||
const res = await fetch(url.href, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${jwt}`,
|
||||
"Content-Type": "application/json",
|
||||
"x-thirdweb-team-id": teamId,
|
||||
...(clientId && { "x-client-id": clientId }),
|
||||
},
|
||||
method: "GET",
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch wallets: ${await res.text()}`);
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
return json as {
|
||||
users: WalletUser[];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
// Transform API response to match existing WalletUser format
|
||||
function transformToWalletUser(apiWallet: APIWallet): WalletUser {
|
||||
return {
|
||||
id: getProfileId(apiWallet.profiles[0]) || "",
|
||||
linkedAccounts: apiWallet.profiles.map((profile) => {
|
||||
// Create details object based on the profile data
|
||||
let details:
|
||||
| { email: string; [key: string]: string }
|
||||
| { phone: string; [key: string]: string }
|
||||
| { address: string; [key: string]: string }
|
||||
| { id: string; [key: string]: string };
|
||||
|
||||
const profileId = getProfileId(profile);
|
||||
|
||||
if ("email" in profile && profile.email) {
|
||||
details = { email: profile.email, id: profileId };
|
||||
} else if ("phone" in profile && profile.phone) {
|
||||
details = { phone: profile.phone, id: profileId };
|
||||
} else if ("walletAddress" in profile && profile.walletAddress) {
|
||||
details = { address: profile.walletAddress, id: profileId };
|
||||
} else {
|
||||
details = { id: profileId };
|
||||
}
|
||||
|
||||
return {
|
||||
type: profile.type,
|
||||
details,
|
||||
};
|
||||
}),
|
||||
wallets: apiWallet.address
|
||||
? [
|
||||
{
|
||||
address: apiWallet.address,
|
||||
createdAt: apiWallet.createdAt || new Date().toISOString(),
|
||||
type: "enclave" as const,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
// Helper function to safely get ID from any profile type
|
||||
function getProfileId(profile: APIProfile | undefined): string {
|
||||
if (!profile) return "";
|
||||
|
||||
if ("id" in profile) {
|
||||
return profile.id;
|
||||
} else if ("credentialId" in profile) {
|
||||
return profile.credentialId;
|
||||
} else if ("identifier" in profile) {
|
||||
return profile.identifier;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
export function useEmbeddedWallets(params: {
|
||||
clientId?: string;
|
||||
ecosystemSlug?: string;
|
||||
@@ -98,6 +181,7 @@ export function useAllEmbeddedWallets(params: { authToken: string }) {
|
||||
while (true) {
|
||||
const res = await queryClient.fetchQuery<{
|
||||
users: WalletUser[];
|
||||
hasMore: boolean;
|
||||
}>({
|
||||
queryFn: fetchAccountList({
|
||||
clientId,
|
||||
@@ -113,12 +197,13 @@ export function useAllEmbeddedWallets(params: { authToken: string }) {
|
||||
),
|
||||
});
|
||||
|
||||
if (res.users.length === 0) {
|
||||
responses.push(...res.users);
|
||||
|
||||
if (!res.hasMore) {
|
||||
break;
|
||||
}
|
||||
|
||||
page++;
|
||||
responses.push(...res.users);
|
||||
}
|
||||
|
||||
return responses;
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export { BringToFrontIcon as BridgeIcon } from "lucide-react";
|
||||
@@ -17,18 +17,21 @@ export async function resolveEns(
|
||||
ensName: await resolveName({
|
||||
address: ensNameOrAddress,
|
||||
client,
|
||||
}),
|
||||
}).catch(() => null),
|
||||
};
|
||||
}
|
||||
|
||||
if (!isValidENSName(ensNameOrAddress)) {
|
||||
throw new Error("Invalid ENS name");
|
||||
return {
|
||||
address: null,
|
||||
ensName: null,
|
||||
};
|
||||
}
|
||||
|
||||
const address = await resolveAddress({
|
||||
client,
|
||||
name: ensNameOrAddress,
|
||||
});
|
||||
}).catch(() => null);
|
||||
|
||||
if (!address) {
|
||||
return {
|
||||
|
||||
@@ -184,7 +184,7 @@ async function fetchContractName(chainId: number, contractAddress: string) {
|
||||
return name;
|
||||
}
|
||||
|
||||
const formatNumber = (num: number) => {
|
||||
export const formatNumber = (num: number) => {
|
||||
if (num >= 1000000) {
|
||||
return `${(num / 1000000).toLocaleString(undefined, {
|
||||
maximumFractionDigits: 1,
|
||||
|
||||
@@ -147,4 +147,4 @@ export type ApiKeyPayConfigValidationSchema = z.infer<
|
||||
>;
|
||||
|
||||
// FIXME: Remove
|
||||
export const HIDDEN_SERVICES = ["relayer", "chainsaw"];
|
||||
export const HIDDEN_SERVICES = ["relayer", "chainsaw", "engineCloud"];
|
||||
|
||||
@@ -279,3 +279,32 @@ export function newAccountStub(overrides?: Partial<Account>): Account {
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function randomLorem(length: number) {
|
||||
const loremWords = [
|
||||
"lorem",
|
||||
"ipsum",
|
||||
"dolor",
|
||||
"sit",
|
||||
"amet",
|
||||
"consectetur",
|
||||
"adipiscing",
|
||||
"elit",
|
||||
"sed",
|
||||
"do",
|
||||
"eiusmod",
|
||||
"tempor",
|
||||
"incididunt",
|
||||
"ut",
|
||||
"labore",
|
||||
"et",
|
||||
"dolore",
|
||||
"magna",
|
||||
"aliqua",
|
||||
];
|
||||
|
||||
return Array.from({ length }, () => {
|
||||
const randomIndex = Math.floor(Math.random() * loremWords.length);
|
||||
return loremWords[randomIndex];
|
||||
}).join(" ");
|
||||
}
|
||||
|
||||
@@ -31,9 +31,9 @@ export function getSDKTheme(theme: "light" | "dark"): Theme {
|
||||
selectedTextBg: "hsl(var(--inverted))",
|
||||
selectedTextColor: "hsl(var(--inverted-foreground))",
|
||||
separatorLine: "hsl(var(--border))",
|
||||
skeletonBg: "hsl(var(--muted))",
|
||||
skeletonBg: "hsl(var(--secondary-foreground)/15%)",
|
||||
success: "hsl(var(--success-text))",
|
||||
tertiaryBg: "hsl(var(--muted)/50%)",
|
||||
tertiaryBg: "hsl(var(--muted)/30%)",
|
||||
tooltipBg: "hsl(var(--popover))",
|
||||
tooltipText: "hsl(var(--popover-foreground))",
|
||||
},
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { TeamHeader } from "../../team/components/TeamHeader/team-header";
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<div className="border-border border-b bg-card">
|
||||
<TeamHeader />
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 536 KiB |
-37
@@ -1,37 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useCallback } from "react";
|
||||
import { PaginationButtons } from "@/components/blocks/pagination-buttons";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
|
||||
type ChainlistPaginationProps = {
|
||||
totalPages: number;
|
||||
activePage: number;
|
||||
};
|
||||
|
||||
export const ChainlistPagination: React.FC<ChainlistPaginationProps> = ({
|
||||
activePage,
|
||||
totalPages,
|
||||
}) => {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useDashboardRouter();
|
||||
|
||||
const createPageURL = useCallback(
|
||||
(pageNumber: number) => {
|
||||
const params = new URLSearchParams(searchParams || undefined);
|
||||
params.set("page", pageNumber.toString());
|
||||
return `${pathname}?${params.toString()}`;
|
||||
},
|
||||
[pathname, searchParams],
|
||||
);
|
||||
|
||||
return (
|
||||
<PaginationButtons
|
||||
activePage={activePage}
|
||||
onPageClick={(page) => router.push(createPageURL(page))}
|
||||
totalPages={totalPages}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,74 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { SearchIcon, XCircleIcon } from "lucide-react";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useDebouncedCallback } from "use-debounce";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
|
||||
function cleanUrl(url: string) {
|
||||
if (url.endsWith("?")) {
|
||||
return url.slice(0, -1);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
export const SearchInput: React.FC = () => {
|
||||
const router = useDashboardRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
useEffect(() => {
|
||||
// reset the input if the query param is removed
|
||||
if (inputRef.current?.value && !searchParams?.get("query")) {
|
||||
inputRef.current.value = "";
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
const handleSearch = useDebouncedCallback((term: string) => {
|
||||
const params = new URLSearchParams(searchParams ?? undefined);
|
||||
if (term) {
|
||||
params.set("query", term);
|
||||
} else {
|
||||
params.delete("query");
|
||||
}
|
||||
// always delete the page number when searching
|
||||
params.delete("page");
|
||||
const url = cleanUrl(`${pathname}?${params.toString()}`);
|
||||
router.replace(url);
|
||||
}, 300);
|
||||
|
||||
return (
|
||||
<div className="group relative w-full">
|
||||
<SearchIcon className="-translate-y-1/2 absolute top-[50%] left-3 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
className="h-10 rounded-lg bg-card py-2 pl-9 lg:min-w-[300px]"
|
||||
defaultValue={searchParams?.get("query") || ""}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
placeholder="Search by token name or symbol"
|
||||
ref={inputRef}
|
||||
/>
|
||||
{searchParams?.has("query") && (
|
||||
<Button
|
||||
className="-translate-y-1/2 absolute top-[50%] right-0 bg-background text-muted-foreground opacity-0 transition duration-300 ease-in-out group-hover:opacity-100"
|
||||
onClick={() => {
|
||||
const params = new URLSearchParams(searchParams ?? undefined);
|
||||
params.delete("query");
|
||||
params.delete("page");
|
||||
const url = cleanUrl(`${pathname}?${params.toString()}`);
|
||||
router.replace(url);
|
||||
}}
|
||||
size="icon"
|
||||
variant="outline"
|
||||
>
|
||||
<XCircleIcon className="size-5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDownLeftIcon, ArrowUpRightIcon } from "lucide-react";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useCallback } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
|
||||
type QueryTypeProps = {
|
||||
activeType: "origin" | "destination";
|
||||
};
|
||||
|
||||
export const QueryType: React.FC<QueryTypeProps> = ({ activeType }) => {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useDashboardRouter();
|
||||
|
||||
const createPageURL = useCallback(
|
||||
(type: "origin" | "destination") => {
|
||||
const params = new URLSearchParams(searchParams || undefined);
|
||||
params.set("type", type);
|
||||
return `${pathname}?${params.toString()}`;
|
||||
},
|
||||
[pathname, searchParams],
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-row">
|
||||
<ToolTipLabel contentClassName="w-full" label="Origin">
|
||||
<Button
|
||||
className="rounded-r-none"
|
||||
onClick={() => {
|
||||
router.replace(createPageURL("origin"));
|
||||
}}
|
||||
size="icon"
|
||||
variant={activeType === "origin" ? "default" : "outline"}
|
||||
>
|
||||
<ArrowUpRightIcon strokeWidth={1} />
|
||||
</Button>
|
||||
</ToolTipLabel>
|
||||
<ToolTipLabel contentClassName="w-full" label="Destination">
|
||||
<Button
|
||||
className="rounded-l-none"
|
||||
onClick={() => {
|
||||
router.replace(createPageURL("destination"));
|
||||
}}
|
||||
size="icon"
|
||||
variant={activeType === "destination" ? "default" : "outline"}
|
||||
>
|
||||
<ArrowDownLeftIcon strokeWidth={1} />
|
||||
</Button>
|
||||
</ToolTipLabel>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,50 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Grid2X2Icon, ListIcon } from "lucide-react";
|
||||
import { usePathname, useSearchParams } from "next/navigation";
|
||||
import { useCallback } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
|
||||
type RouteListViewProps = {
|
||||
activeView: "grid" | "table";
|
||||
};
|
||||
|
||||
export const RouteListView: React.FC<RouteListViewProps> = ({ activeView }) => {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const router = useDashboardRouter();
|
||||
|
||||
const createPageURL = useCallback(
|
||||
(view: "grid" | "table") => {
|
||||
const params = new URLSearchParams(searchParams || undefined);
|
||||
params.set("view", view);
|
||||
return `${pathname}?${params.toString()}`;
|
||||
},
|
||||
[pathname, searchParams],
|
||||
);
|
||||
return (
|
||||
<div className="flex flex-row">
|
||||
<Button
|
||||
className="rounded-r-none"
|
||||
onClick={() => {
|
||||
router.replace(createPageURL("table"));
|
||||
}}
|
||||
size="icon"
|
||||
variant={activeView === "table" ? "default" : "outline"}
|
||||
>
|
||||
<ListIcon strokeWidth={1} />
|
||||
</Button>
|
||||
<Button
|
||||
className="rounded-l-none"
|
||||
onClick={() => {
|
||||
router.replace(createPageURL("grid"));
|
||||
}}
|
||||
size="icon"
|
||||
variant={activeView === "grid" ? "default" : "outline"}
|
||||
>
|
||||
<Grid2X2Icon strokeWidth={1} />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { defineChain, getAddress, NATIVE_TOKEN_ADDRESS } from "thirdweb";
|
||||
import { type ChainMetadata, getChainMetadata } from "thirdweb/chains";
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||
import { resolveSchemeWithErrorHandler } from "@/utils/resolveSchemeWithErrorHandler";
|
||||
|
||||
type RouteListCardProps = {
|
||||
originChainId: number;
|
||||
originTokenAddress: string;
|
||||
originTokenIconUri?: string | null;
|
||||
originTokenSymbol: string;
|
||||
originTokenName: string;
|
||||
destinationChainId: number;
|
||||
destinationTokenAddress: string;
|
||||
destinationTokenIconUri?: string | null;
|
||||
destinationTokenSymbol: string;
|
||||
destinationTokenName: string;
|
||||
};
|
||||
|
||||
export async function RouteListCard({
|
||||
originChainId,
|
||||
originTokenAddress,
|
||||
originTokenIconUri,
|
||||
originTokenName,
|
||||
destinationChainId,
|
||||
destinationTokenAddress,
|
||||
destinationTokenIconUri,
|
||||
destinationTokenName,
|
||||
}: RouteListCardProps) {
|
||||
const [
|
||||
originChain,
|
||||
destinationChain,
|
||||
resolvedOriginTokenIconUri,
|
||||
resolvedDestinationTokenIconUri,
|
||||
] = await Promise.all([
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
getChainMetadata(defineChain(originChainId)),
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
getChainMetadata(defineChain(destinationChainId)),
|
||||
originTokenIconUri
|
||||
? resolveSchemeWithErrorHandler({
|
||||
client: serverThirdwebClient,
|
||||
uri: originTokenIconUri,
|
||||
})
|
||||
: undefined,
|
||||
destinationTokenIconUri
|
||||
? resolveSchemeWithErrorHandler({
|
||||
client: serverThirdwebClient,
|
||||
uri: destinationTokenIconUri,
|
||||
})
|
||||
: undefined,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="relative h-full">
|
||||
<Card className="h-full w-full">
|
||||
<CardHeader className="flex flex-row items-center justify-between p-4">
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
{resolvedOriginTokenIconUri ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
alt={originTokenAddress}
|
||||
className="size-8 rounded-full border border-muted-foreground"
|
||||
src={resolvedOriginTokenIconUri}
|
||||
/>
|
||||
) : (
|
||||
<div className="size-8 rounded-full bg-muted-foreground" />
|
||||
)}
|
||||
{resolvedDestinationTokenIconUri ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
alt={destinationTokenAddress}
|
||||
className="-translate-x-4 size-8 rounded-full border border-muted-foreground ring-2 ring-card"
|
||||
src={resolvedDestinationTokenIconUri}
|
||||
/>
|
||||
) : (
|
||||
<div className="-translate-x-4 size-8 rounded-full bg-muted-foreground ring-2 ring-card" />
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="px-4 pt-0 pb-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between gap-2">
|
||||
<TokenName
|
||||
chainMetadata={originChain}
|
||||
tokenAddress={originTokenAddress}
|
||||
tokenName={originTokenName}
|
||||
/>
|
||||
<div className="text-right text-base text-muted-foreground">
|
||||
{originChain.name}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between gap-2">
|
||||
<TokenName
|
||||
chainMetadata={destinationChain}
|
||||
tokenAddress={destinationTokenAddress}
|
||||
tokenName={destinationTokenName}
|
||||
/>
|
||||
<div className="text-right text-base text-muted-foreground">
|
||||
{destinationChain.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const nativeTokenAddress = getAddress(NATIVE_TOKEN_ADDRESS);
|
||||
|
||||
function TokenName(props: {
|
||||
tokenAddress: string;
|
||||
tokenName: string;
|
||||
chainMetadata: ChainMetadata;
|
||||
}) {
|
||||
const isERC20 = getAddress(props.tokenAddress) !== nativeTokenAddress;
|
||||
|
||||
if (isERC20) {
|
||||
return (
|
||||
<Link
|
||||
className="flex items-center gap-1.5 font-normal text-base group/link hover:underline underline-offset-4 decoration-muted-foreground/50 decoration-dotted"
|
||||
href={`https://thirdweb.com/${props.chainMetadata.slug}/${props.tokenAddress}`}
|
||||
target="_blank"
|
||||
>
|
||||
{props.tokenName}
|
||||
<ExternalLinkIcon className="size-3.5 text-muted-foreground group-hover/link:text-foreground" />
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-left font-normal text-base">
|
||||
{props.chainMetadata.nativeCurrency.name}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
import { ExternalLinkIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { getAddress, NATIVE_TOKEN_ADDRESS } from "thirdweb";
|
||||
import {
|
||||
type ChainMetadata,
|
||||
defineChain,
|
||||
getChainMetadata,
|
||||
} from "thirdweb/chains";
|
||||
import { shortenAddress } from "thirdweb/utils";
|
||||
import { Img } from "@/components/blocks/Img";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { TableCell, TableRow } from "@/components/ui/table";
|
||||
import { serverThirdwebClient } from "@/constants/thirdweb-client.server";
|
||||
import { resolveSchemeWithErrorHandler } from "@/utils/resolveSchemeWithErrorHandler";
|
||||
|
||||
type RouteListRowProps = {
|
||||
originChainId: number;
|
||||
originTokenAddress: string;
|
||||
originTokenIconUri?: string | null;
|
||||
originTokenSymbol?: string;
|
||||
originTokenName?: string;
|
||||
destinationChainId: number;
|
||||
destinationTokenAddress: string;
|
||||
destinationTokenIconUri?: string | null;
|
||||
destinationTokenSymbol?: string;
|
||||
destinationTokenName?: string;
|
||||
};
|
||||
|
||||
export async function RouteListRow({
|
||||
originChainId,
|
||||
originTokenAddress,
|
||||
originTokenIconUri,
|
||||
originTokenSymbol,
|
||||
destinationChainId,
|
||||
destinationTokenAddress,
|
||||
destinationTokenIconUri,
|
||||
destinationTokenSymbol,
|
||||
}: RouteListRowProps) {
|
||||
const [
|
||||
originChain,
|
||||
destinationChain,
|
||||
resolvedOriginTokenIconUri,
|
||||
resolvedDestinationTokenIconUri,
|
||||
] = await Promise.all([
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
getChainMetadata(defineChain(originChainId)),
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
getChainMetadata(defineChain(destinationChainId)),
|
||||
originTokenIconUri
|
||||
? resolveSchemeWithErrorHandler({
|
||||
client: serverThirdwebClient,
|
||||
uri: originTokenIconUri,
|
||||
})
|
||||
: undefined,
|
||||
destinationTokenIconUri
|
||||
? resolveSchemeWithErrorHandler({
|
||||
client: serverThirdwebClient,
|
||||
uri: destinationTokenIconUri,
|
||||
})
|
||||
: undefined,
|
||||
]);
|
||||
|
||||
return (
|
||||
<TableRow className="group">
|
||||
<TableCell>
|
||||
<TokenInfo
|
||||
chainMetadata={originChain}
|
||||
tokenAddress={originTokenAddress}
|
||||
tokenIconUri={resolvedOriginTokenIconUri}
|
||||
tokenSymbol={originTokenSymbol}
|
||||
/>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="text-muted-foreground/90">
|
||||
<span className="font-medium">{originChain.name}</span>
|
||||
</TableCell>
|
||||
|
||||
<TableCell>
|
||||
<TokenInfo
|
||||
chainMetadata={destinationChain}
|
||||
tokenAddress={destinationTokenAddress}
|
||||
tokenIconUri={resolvedDestinationTokenIconUri}
|
||||
tokenSymbol={destinationTokenSymbol}
|
||||
/>
|
||||
</TableCell>
|
||||
|
||||
<TableCell className="text-muted-foreground/90">
|
||||
<span className="font-medium">{destinationChain.name}</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
||||
const nativeTokenAddress = getAddress(NATIVE_TOKEN_ADDRESS);
|
||||
|
||||
function TokenInfo(props: {
|
||||
tokenAddress: string;
|
||||
tokenSymbol: string | undefined;
|
||||
chainMetadata: ChainMetadata;
|
||||
tokenIconUri: string | undefined;
|
||||
}) {
|
||||
const isERC20 = getAddress(props.tokenAddress) !== nativeTokenAddress;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
{props.tokenIconUri ? (
|
||||
<Img
|
||||
alt={props.tokenAddress}
|
||||
className="size-7 rounded-full border border-border/50"
|
||||
src={props.tokenIconUri}
|
||||
/>
|
||||
) : (
|
||||
<div className="size-7 rounded-full bg-muted-foreground/20" />
|
||||
)}
|
||||
{isERC20 ? (
|
||||
<Button
|
||||
asChild
|
||||
className="h-auto w-auto py-1 px-1.5 gap-2"
|
||||
variant="ghost"
|
||||
>
|
||||
<Link
|
||||
href={`https://thirdweb.com/${props.chainMetadata.slug}/${props.tokenAddress}`}
|
||||
target="_blank"
|
||||
>
|
||||
{props.tokenSymbol || shortenAddress(props.tokenAddress)}
|
||||
<ExternalLinkIcon className="size-3.5 text-muted-foreground" />
|
||||
</Link>
|
||||
</Button>
|
||||
) : (
|
||||
<span className="font-medium text-sm px-1.5 py-1">
|
||||
{props.chainMetadata.nativeCurrency.symbol}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
-176
@@ -1,176 +0,0 @@
|
||||
import type { Address } from "thirdweb";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { getRoutes } from "../../../utils";
|
||||
import { ChainlistPagination } from "../client/pagination";
|
||||
import { RouteListCard } from "./routelist-card";
|
||||
import { RouteListRow } from "./routelist-row";
|
||||
|
||||
export type SearchParams = Partial<{
|
||||
includeDeprecated: boolean;
|
||||
query: string;
|
||||
page: number;
|
||||
type: "origin" | "destination";
|
||||
// maybe later we'll have a page size param?
|
||||
// pageSize: number;
|
||||
view: "table" | "grid";
|
||||
}>;
|
||||
|
||||
// 120 is divisible by 2, 3, and 4 so card layout looks nice
|
||||
const DEFAULT_PAGE_SIZE = 120;
|
||||
|
||||
async function getRoutesToRender(params: SearchParams) {
|
||||
const filters: Partial<{
|
||||
originQuery?: string;
|
||||
destinationQuery?: string;
|
||||
originChainId?: number;
|
||||
originTokenAddress?: Address;
|
||||
destinationChainId?: number;
|
||||
destinationTokenAddress?: Address;
|
||||
}> = {};
|
||||
|
||||
if (params.type === "origin" || typeof params.type === "undefined") {
|
||||
if (params.query?.startsWith("0x")) {
|
||||
filters.originTokenAddress = params.query as Address;
|
||||
} else if (Number.isInteger(Number(params.query))) {
|
||||
filters.originChainId = Number(params.query);
|
||||
} else if (params.query) {
|
||||
filters.originQuery = params.query;
|
||||
}
|
||||
} else if (params.type === "destination") {
|
||||
if (params.query?.startsWith("0x")) {
|
||||
filters.destinationTokenAddress = params.query as Address;
|
||||
} else if (Number.isInteger(Number(params.query))) {
|
||||
filters.destinationChainId = Number(params.query);
|
||||
} else if (params.query) {
|
||||
filters.destinationQuery = params.query;
|
||||
}
|
||||
}
|
||||
const routes = await getRoutes({
|
||||
destinationQuery: filters.destinationQuery,
|
||||
limit: DEFAULT_PAGE_SIZE,
|
||||
offset: DEFAULT_PAGE_SIZE * ((params.page || 1) - 1),
|
||||
originQuery: filters.originQuery,
|
||||
});
|
||||
|
||||
return {
|
||||
filteredCount: routes.meta.filteredCount,
|
||||
routesToRender: routes.data,
|
||||
totalCount: routes.meta.totalCount,
|
||||
};
|
||||
}
|
||||
|
||||
export async function RoutesData(props: {
|
||||
searchParams: SearchParams;
|
||||
activeView: "table" | "grid";
|
||||
isLoggedIn: boolean;
|
||||
}) {
|
||||
const { routesToRender, totalCount, filteredCount } = await getRoutesToRender(
|
||||
props.searchParams,
|
||||
);
|
||||
|
||||
const totalPages = Math.ceil(filteredCount / DEFAULT_PAGE_SIZE);
|
||||
|
||||
return (
|
||||
<>
|
||||
<main>
|
||||
{/* empty state */}
|
||||
{routesToRender.length === 0 ? (
|
||||
<div className="flex h-[300px] items-center justify-center rounded-lg border p-8 lg:h-[500px]">
|
||||
<p className="text-2xl">No Results found</p>
|
||||
</div>
|
||||
) : props.activeView === "table" ? (
|
||||
<TableContainer>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Origin Token</TableHead>
|
||||
<TableHead>Origin Chain</TableHead>
|
||||
<TableHead>Destination Token</TableHead>
|
||||
<TableHead>Destination Chain</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{routesToRender.map((route) => (
|
||||
<RouteListRow
|
||||
destinationChainId={route.destinationToken.chainId}
|
||||
destinationTokenAddress={route.destinationToken.address}
|
||||
destinationTokenIconUri={route.destinationToken.iconUri}
|
||||
destinationTokenName={route.destinationToken.name}
|
||||
destinationTokenSymbol={route.destinationToken.symbol}
|
||||
key={`${route.originToken.chainId}:${route.originToken.address}-${route.destinationToken.chainId}:${route.destinationToken.address}`}
|
||||
originChainId={route.originToken.chainId}
|
||||
originTokenAddress={route.originToken.address}
|
||||
originTokenIconUri={route.originToken.iconUri}
|
||||
originTokenName={route.originToken.name}
|
||||
originTokenSymbol={route.originToken.symbol}
|
||||
/>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
) : (
|
||||
<ul className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
{routesToRender.map((route) => (
|
||||
<li
|
||||
className="h-full"
|
||||
key={`${route.originToken.chainId}:${route.originToken.address}-${route.destinationToken.chainId}:${route.destinationToken.address}`}
|
||||
>
|
||||
<RouteListCard
|
||||
destinationChainId={route.destinationToken.chainId}
|
||||
destinationTokenAddress={route.destinationToken.address}
|
||||
destinationTokenIconUri={route.destinationToken.iconUri}
|
||||
destinationTokenName={route.destinationToken.name}
|
||||
destinationTokenSymbol={route.destinationToken.symbol}
|
||||
originChainId={route.originToken.chainId}
|
||||
originTokenAddress={route.originToken.address}
|
||||
originTokenIconUri={route.originToken.iconUri}
|
||||
originTokenName={route.originToken.name}
|
||||
originTokenSymbol={route.originToken.symbol}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</main>
|
||||
<div className="h-10" />
|
||||
{totalPages > 1 && (
|
||||
<ChainlistPagination
|
||||
activePage={Number(props.searchParams.page) || 1}
|
||||
totalPages={totalPages}
|
||||
/>
|
||||
)}
|
||||
<div className="h-4" />
|
||||
<p className="text-balance text-center text-muted-foreground text-sm">
|
||||
Showing{" "}
|
||||
<span className="text-accent-foreground">{routesToRender.length}</span>{" "}
|
||||
out of{" "}
|
||||
{filteredCount !== totalCount ? (
|
||||
<>
|
||||
<span className="text-accent-foreground">
|
||||
{filteredCount.toLocaleString()}
|
||||
</span>{" "}
|
||||
routes that match filters. (Total:{" "}
|
||||
<span className="text-accent-foreground">
|
||||
{totalCount.toLocaleString()}
|
||||
</span>
|
||||
)
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-accent-foreground">
|
||||
{totalCount.toLocaleString()}
|
||||
</span>{" "}
|
||||
routes.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { ArrowUpRightIcon } from "lucide-react";
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import { SearchInput } from "./components/client/search";
|
||||
import { QueryType } from "./components/client/type";
|
||||
import { RouteListView } from "./components/client/view";
|
||||
import {
|
||||
RoutesData,
|
||||
type SearchParams,
|
||||
} from "./components/server/routes-table";
|
||||
|
||||
const title = "Payments Routes: Swap, Bridge, and Onramp";
|
||||
const description =
|
||||
"A list of token routes for swapping, bridging, and on-ramping between EVM chains with thirdweb.";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
description,
|
||||
openGraph: {
|
||||
description,
|
||||
title,
|
||||
},
|
||||
title,
|
||||
};
|
||||
|
||||
export default async function RoutesPage(props: {
|
||||
searchParams: Promise<SearchParams>;
|
||||
}) {
|
||||
const authToken = await getAuthToken();
|
||||
const headersList = await headers();
|
||||
const viewportWithHint = Number(
|
||||
headersList.get("Sec-Ch-Viewport-Width") || 0,
|
||||
);
|
||||
const searchParams = await props.searchParams;
|
||||
|
||||
const activeType = searchParams.type ?? "origin";
|
||||
|
||||
// default is driven by viewport hint
|
||||
const activeView = searchParams.view
|
||||
? searchParams.view
|
||||
: viewportWithHint > 1000
|
||||
? "table"
|
||||
: "grid";
|
||||
|
||||
return (
|
||||
<section className="container mx-auto flex h-full flex-col px-4 py-10">
|
||||
<header className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-6 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div className="flex flex-col gap-2">
|
||||
<h1 className="font-semibold text-4xl tracking-tighter lg:text-5xl">
|
||||
Routes
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex flex-row items-end gap-4 lg:flex-col">
|
||||
<div className="flex w-full flex-row items-center gap-4">
|
||||
<SearchInput />
|
||||
<QueryType activeType={activeType} />
|
||||
<RouteListView activeView={activeView} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div className="h-10" />
|
||||
<div className="relative overflow-hidden rounded-lg border-2 border-green-500/20 bg-gradient-to-br from-card/80 to-card/50 p-4 shadow-[inset_0_1px_2px_0_rgba(0,0,0,0.02)]">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-green-500/5 to-transparent" />
|
||||
<div className="relative flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h3 className="font-medium text-lg">
|
||||
Get Started with thirdweb Payments
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Simple, instant, and secure payments across any token and chain.
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
className="inline-flex items-center gap-2 rounded-md bg-green-600 px-4 py-2 font-medium text-sm text-white transition-all hover:bg-green-600/90 hover:shadow-sm"
|
||||
href="https://portal.thirdweb.com/payments"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Learn More
|
||||
<ArrowUpRightIcon className="size-4" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-10" />
|
||||
<RoutesData
|
||||
activeView={activeView}
|
||||
isLoggedIn={!!authToken}
|
||||
searchParams={searchParams}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { Address } from "thirdweb";
|
||||
|
||||
export type Route = {
|
||||
originToken: {
|
||||
address: Address;
|
||||
chainId: number;
|
||||
iconUri?: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
};
|
||||
destinationToken: {
|
||||
address: Address;
|
||||
chainId: number;
|
||||
iconUri?: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
};
|
||||
};
|
||||
@@ -1,48 +0,0 @@
|
||||
import "server-only";
|
||||
|
||||
import { NEXT_PUBLIC_THIRDWEB_BRIDGE_HOST } from "@/constants/public-envs";
|
||||
import { DASHBOARD_THIRDWEB_SECRET_KEY } from "@/constants/server-envs";
|
||||
import type { Route } from "./types/route";
|
||||
|
||||
export async function getRoutes({
|
||||
limit,
|
||||
offset,
|
||||
originQuery,
|
||||
destinationQuery,
|
||||
}: {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
originQuery?: string;
|
||||
destinationQuery?: string;
|
||||
} = {}) {
|
||||
const url = new URL(`${NEXT_PUBLIC_THIRDWEB_BRIDGE_HOST}/v1/routes/search`);
|
||||
if (limit) {
|
||||
url.searchParams.set("limit", limit.toString());
|
||||
}
|
||||
if (offset) {
|
||||
url.searchParams.set("offset", offset.toString());
|
||||
}
|
||||
if (originQuery) {
|
||||
url.searchParams.set("originQuery", originQuery);
|
||||
}
|
||||
if (destinationQuery) {
|
||||
url.searchParams.set("destinationQuery", destinationQuery);
|
||||
}
|
||||
url.searchParams.set("sortBy", "popularity");
|
||||
const routesResponse = await fetch(url, {
|
||||
headers: {
|
||||
"x-secret-key": DASHBOARD_THIRDWEB_SECRET_KEY,
|
||||
},
|
||||
next: { revalidate: 60 * 60 },
|
||||
});
|
||||
|
||||
if (!routesResponse.ok) {
|
||||
throw new Error("Failed to fetch routes");
|
||||
}
|
||||
const routes: {
|
||||
data: Route[];
|
||||
meta: { totalCount: number; filteredCount: number };
|
||||
} = await routesResponse.json();
|
||||
|
||||
return routes;
|
||||
}
|
||||
+12
-12
@@ -1,24 +1,24 @@
|
||||
"use client";
|
||||
import { useTheme } from "next-themes";
|
||||
import { defineChain, type ThirdwebClient } from "thirdweb";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import type { ChainMetadata } from "thirdweb/chains";
|
||||
import { BuyWidget } from "thirdweb/react";
|
||||
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||
import { BuyAndSwapEmbed } from "@/components/blocks/BuyAndSwapEmbed";
|
||||
import { GridPatternEmbedContainer } from "@/components/blocks/grid-pattern-embed-container";
|
||||
import { defineDashboardChain } from "@/lib/defineDashboardChain";
|
||||
|
||||
export function BuyFundsSection(props: {
|
||||
chain: ChainMetadata;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
return (
|
||||
<section className="flex flex-col gap-4 items-center justify-center">
|
||||
<BuyWidget
|
||||
amount="0"
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
chain={defineChain(props.chain.chainId)}
|
||||
<GridPatternEmbedContainer>
|
||||
<BuyAndSwapEmbed
|
||||
client={props.client}
|
||||
theme={getSDKTheme(theme === "dark" ? "dark" : "light")}
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
chain={defineDashboardChain(props.chain.chainId, props.chain)}
|
||||
buyAmount={undefined}
|
||||
tokenAddress={undefined}
|
||||
pageType="chain"
|
||||
/>
|
||||
</section>
|
||||
</GridPatternEmbedContainer>
|
||||
);
|
||||
}
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
import { reportChainPageview } from "@/analytics/report";
|
||||
import { useEffectOnce } from "@/hooks/useEffectOnce";
|
||||
|
||||
export function ChainPageView(props: { chainId: number }) {
|
||||
useEffectOnce(() => {
|
||||
reportChainPageview({
|
||||
chainId: props.chainId,
|
||||
});
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
+94
-13
@@ -43,9 +43,7 @@ function useChainStatswithRPC(_rpcUrl: string) {
|
||||
const latency = (performance.now() - startTimeStamp).toFixed(0);
|
||||
|
||||
const blockNumber = Number.parseInt(json.result.number, 16);
|
||||
const blockGasLimit = Number.parseInt(json.result.gasLimit, 16);
|
||||
return {
|
||||
blockGasLimit,
|
||||
blockNumber,
|
||||
latency,
|
||||
};
|
||||
@@ -61,8 +59,70 @@ function useChainStatswithRPC(_rpcUrl: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function useEIP7702Support(_rpcUrl: string) {
|
||||
let rpcUrl = _rpcUrl.replace(
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
// biome-ignore lint/suspicious/noTemplateCurlyInString: this is expected in this case
|
||||
"${THIRDWEB_API_KEY}",
|
||||
NEXT_PUBLIC_DASHBOARD_CLIENT_ID,
|
||||
);
|
||||
|
||||
// based on the environment hit dev or production
|
||||
if (hostnameEndsWith(rpcUrl, "rpc.thirdweb.com")) {
|
||||
if (!isProd) {
|
||||
rpcUrl = rpcUrl.replace("rpc.thirdweb.com", "rpc.thirdweb-dev.com");
|
||||
}
|
||||
}
|
||||
|
||||
return useQuery({
|
||||
enabled: !!rpcUrl,
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const res = await fetch(rpcUrl, {
|
||||
body: JSON.stringify({
|
||||
id: 1,
|
||||
jsonrpc: "2.0",
|
||||
method: "eth_estimateGas",
|
||||
params: [
|
||||
{
|
||||
from: "0xdeadbeef00000000000000000000000000000000",
|
||||
to: "0xdeadbeef00000000000000000000000000000000",
|
||||
data: "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
value: "0x0",
|
||||
},
|
||||
"latest",
|
||||
{
|
||||
"0xdeadbeef00000000000000000000000000000000": {
|
||||
code: "0xef01000000000000000000000000000000000000000001",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
const json = await res.json();
|
||||
|
||||
// If the response has a valid result object, EIP-7702 is enabled
|
||||
return {
|
||||
isSupported: !!json.result,
|
||||
};
|
||||
} catch {
|
||||
// If the request fails or errors, EIP-7702 is not supported
|
||||
return {
|
||||
isSupported: false,
|
||||
};
|
||||
}
|
||||
},
|
||||
queryKey: ["eip-7702-support", { rpcUrl }],
|
||||
refetchInterval: false, // Don't refetch this as it's unlikely to change
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function ChainLiveStats(props: { rpc: string }) {
|
||||
const stats = useChainStatswithRPC(props.rpc);
|
||||
const eip7702Support = useEIP7702Support(props.rpc);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -107,8 +167,8 @@ export function ChainLiveStats(props: { rpc: string }) {
|
||||
)}
|
||||
</PrimaryInfoItem>
|
||||
|
||||
{/* Block Height */}
|
||||
<PrimaryInfoItem title="Block Height" titleIcon={<PulseDot />}>
|
||||
{/* Latest Block */}
|
||||
<PrimaryInfoItem title="Latest Block" titleIcon={<PulseDot />}>
|
||||
{stats.isError ? (
|
||||
<p className="fade-in-0 animate-in text-destructive-text">N/A</p>
|
||||
) : stats.data ? (
|
||||
@@ -120,16 +180,37 @@ export function ChainLiveStats(props: { rpc: string }) {
|
||||
)}
|
||||
</PrimaryInfoItem>
|
||||
|
||||
{/* Block Gas Limit */}
|
||||
<PrimaryInfoItem title="Block Gas Limit" titleIcon={<PulseDot />}>
|
||||
{stats.isError ? (
|
||||
<p className="fade-in-0 animate-in text-destructive-text">N/A</p>
|
||||
) : stats.data ? (
|
||||
<p className="fade-in-0 animate-in">
|
||||
{stats.data.blockGasLimit ?? "N/A"}
|
||||
</p>
|
||||
{/* EIP-7702 */}
|
||||
<PrimaryInfoItem
|
||||
title="EIP-7702"
|
||||
titleIcon={
|
||||
eip7702Support.data ? (
|
||||
eip7702Support.data.isSupported ? (
|
||||
<ToolTipLabel label="Enabled">
|
||||
<CircleCheckIcon className="size-4 text-success-text" />
|
||||
</ToolTipLabel>
|
||||
) : (
|
||||
<ToolTipLabel label="Disabled">
|
||||
<XIcon className="size-4 text-destructive-text" />
|
||||
</ToolTipLabel>
|
||||
)
|
||||
) : eip7702Support.isError ? (
|
||||
<ToolTipLabel label="Disabled">
|
||||
<XIcon className="size-4 text-destructive-text" />
|
||||
</ToolTipLabel>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{eip7702Support.data ? (
|
||||
eip7702Support.data.isSupported ? (
|
||||
"Available"
|
||||
) : (
|
||||
"Not Available"
|
||||
)
|
||||
) : eip7702Support.isError ? (
|
||||
"Not Available"
|
||||
) : (
|
||||
<div className="flex h-[28px] w-[140px] py-1">
|
||||
<div className="flex h-[28px] w-[80px] py-1">
|
||||
<Skeleton className="h-full w-full" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -24,6 +24,7 @@ import { TeamHeader } from "../../../../team/components/TeamHeader/team-header";
|
||||
import { StarButton } from "../../components/client/star-button";
|
||||
import { getChain, getChainMetadata } from "../../utils";
|
||||
import { AddChainToWallet } from "./components/client/add-chain-to-wallet";
|
||||
import { ChainPageView } from "./components/client/chain-pageview";
|
||||
import { ChainHeader } from "./components/server/chain-header";
|
||||
|
||||
// TODO: improve the behavior when clicking "Get started with thirdweb", currently just redirects to the dashboard
|
||||
@@ -71,6 +72,7 @@ export default async function ChainPageLayout(props: {
|
||||
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<ChainPageView chainId={chain.chainId} />
|
||||
<div className="border-border border-b bg-card">
|
||||
<TeamHeader />
|
||||
</div>
|
||||
|
||||
+43
-3
@@ -1,4 +1,6 @@
|
||||
import { UploadIcon } from "lucide-react";
|
||||
import { ArrowDownToLineIcon, UploadIcon } from "lucide-react";
|
||||
import Papa from "papaparse";
|
||||
import { handleDownload } from "@/components/blocks/download-file-button";
|
||||
import { FormFieldSetup } from "@/components/blocks/FormFieldSetup";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -9,6 +11,7 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { SnapshotEntry } from "../../legacy-zod-schema";
|
||||
import { useClaimConditionsFormContext } from "../index";
|
||||
|
||||
/**
|
||||
@@ -118,10 +121,10 @@ export const ClaimerSelection = () => {
|
||||
|
||||
{/* Edit or See Snapshot */}
|
||||
{snapshot ? (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex flex-col md:flex-row md:items-center gap-3">
|
||||
{/* disable the "Edit" button when form is disabled, but not when it's a "See" button */}
|
||||
<Button
|
||||
className="gap-2 rounded-md"
|
||||
className="gap-2"
|
||||
disabled={disabledSnapshotButton}
|
||||
onClick={() => setOpenIndex(phaseIndex)}
|
||||
size="sm"
|
||||
@@ -130,6 +133,21 @@ export const ClaimerSelection = () => {
|
||||
<UploadIcon className="size-4" />
|
||||
</Button>
|
||||
|
||||
{snapshot && snapshot.length > 0 && (
|
||||
<Button
|
||||
className="gap-2 rounded bg-background"
|
||||
variant="outline"
|
||||
disabled={disabledSnapshotButton}
|
||||
onClick={() => {
|
||||
downloadSnapshotAsCSV(snapshot);
|
||||
}}
|
||||
size="sm"
|
||||
>
|
||||
<ArrowDownToLineIcon className="size-4" />
|
||||
Download
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"flex gap-2 items-center",
|
||||
@@ -151,3 +169,25 @@ export const ClaimerSelection = () => {
|
||||
</FormFieldSetup>
|
||||
);
|
||||
};
|
||||
|
||||
function downloadSnapshotAsCSV(snapshot: SnapshotEntry[]) {
|
||||
const csvData = snapshot.map((entry) => ({
|
||||
address: entry.address,
|
||||
maxClaimable:
|
||||
entry.maxClaimable === "0" ? "" : entry.maxClaimable?.toString() || "",
|
||||
price: entry.price?.toString() || "",
|
||||
currencyAddress: entry.currencyAddress || "",
|
||||
}));
|
||||
|
||||
const csvContent = Papa.unparse(csvData, {
|
||||
header: true,
|
||||
delimiter: ",",
|
||||
quotes: false,
|
||||
});
|
||||
|
||||
handleDownload({
|
||||
fileContent: csvContent,
|
||||
fileNameWithExtension: "snapshot.csv",
|
||||
fileFormat: "text/csv",
|
||||
});
|
||||
}
|
||||
|
||||
+1
-7
@@ -1,11 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ArrowDownToLineIcon,
|
||||
CircleAlertIcon,
|
||||
CircleHelpIcon,
|
||||
PlusIcon,
|
||||
} from "lucide-react";
|
||||
import { CircleAlertIcon, CircleHelpIcon, PlusIcon } from "lucide-react";
|
||||
import {
|
||||
createContext,
|
||||
Fragment,
|
||||
@@ -652,7 +647,6 @@ export const ClaimConditionsForm: React.FC<ClaimConditionsFormProps> = ({
|
||||
txChainID={contract.chain.id}
|
||||
type="submit"
|
||||
>
|
||||
<ArrowDownToLineIcon className="size-3.5" />
|
||||
{claimConditionsQuery.isPending
|
||||
? "Saving Phases"
|
||||
: "Save Phases"}
|
||||
|
||||
+6
@@ -19,6 +19,12 @@ export async function isInsightSupportedForChain(
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
console.error(
|
||||
"failed to fetch chain services for chain",
|
||||
chainId,
|
||||
errorText,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -10,6 +10,7 @@ import {
|
||||
} from "@/components/analytics/date-range-selector";
|
||||
import { ThirdwebBarChart } from "@/components/blocks/charts/bar-chart";
|
||||
import { SkeletonContainer } from "@/components/ui/skeleton";
|
||||
import { formatNumber } from "@/lib/search";
|
||||
import {
|
||||
type AnalyticsQueryParams,
|
||||
type TotalQueryResult,
|
||||
@@ -376,7 +377,7 @@ function AnalyticsStatUI(props: { label: string; data: number | undefined }) {
|
||||
<SkeletonContainer
|
||||
loadedData={props.data}
|
||||
render={(v) => {
|
||||
return <dd className="font-normal text-xl">{v.toLocaleString()}</dd>;
|
||||
return <dd className="font-normal text-xl">{formatNumber(v)}</dd>;
|
||||
}}
|
||||
skeletonData={10000}
|
||||
/>
|
||||
|
||||
+28
-24
@@ -3,8 +3,8 @@ import { NEXT_PUBLIC_DASHBOARD_CLIENT_ID } from "@/constants/public-envs";
|
||||
import { getVercelEnv } from "@/utils/vercel";
|
||||
|
||||
type InsightAggregationEntry = {
|
||||
event_signature: string;
|
||||
time: string;
|
||||
topic_0: string;
|
||||
day: string;
|
||||
count: number;
|
||||
};
|
||||
|
||||
@@ -26,12 +26,18 @@ export async function getContractEventBreakdown(params: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}): Promise<EventBreakdownEntry[]> {
|
||||
const daysDifference =
|
||||
params.startDate && params.endDate
|
||||
? Math.ceil(
|
||||
(params.endDate.getTime() - params.startDate.getTime()) /
|
||||
(1000 * 60 * 60 * 24),
|
||||
)
|
||||
: 30;
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"group_by=time",
|
||||
"group_by=topic_0 as event_signature",
|
||||
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
|
||||
"aggregate=count(*) as count",
|
||||
"group_by=day",
|
||||
"group_by=topic_0",
|
||||
`limit=${daysDifference * 10}`, // at most 10 topics per day
|
||||
params.startDate
|
||||
? `filter_block_timestamp_gte=${getUnixTime(params.startDate)}`
|
||||
: "",
|
||||
@@ -42,14 +48,13 @@ export async function getContractEventBreakdown(params: {
|
||||
.filter(Boolean)
|
||||
.join("&");
|
||||
|
||||
const res = await fetch(
|
||||
`https://insight.${thirdwebDomain}.com/v1/events/${params.contractAddress}?${queryParams}`,
|
||||
{
|
||||
headers: {
|
||||
"x-client-id": NEXT_PUBLIC_DASHBOARD_CLIENT_ID,
|
||||
},
|
||||
const url = `https://insight.${thirdwebDomain}.com/v1/events/${params.contractAddress}?${queryParams}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"x-client-id": NEXT_PUBLIC_DASHBOARD_CLIENT_ID,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
@@ -63,17 +68,16 @@ export async function getContractEventBreakdown(params: {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"time" in value &&
|
||||
"day" in value &&
|
||||
"count" in value &&
|
||||
"event_signature" in value &&
|
||||
typeof value.event_signature === "string" &&
|
||||
typeof value.time === "string" &&
|
||||
typeof value.count === "number"
|
||||
"topic_0" in value &&
|
||||
typeof value.topic_0 === "string" &&
|
||||
typeof value.day === "string"
|
||||
) {
|
||||
collectedAggregations.push({
|
||||
count: value.count,
|
||||
event_signature: value.event_signature,
|
||||
time: value.time,
|
||||
count: Number(value.count),
|
||||
topic_0: value.topic_0,
|
||||
day: value.day,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -84,15 +88,15 @@ export async function getContractEventBreakdown(params: {
|
||||
> = new Map();
|
||||
|
||||
for (const value of collectedAggregations) {
|
||||
const mapKey = value.time;
|
||||
const mapKey = value.day;
|
||||
let valueForDay = dayToFunctionBreakdownMap.get(mapKey);
|
||||
if (!valueForDay) {
|
||||
valueForDay = {};
|
||||
dayToFunctionBreakdownMap.set(mapKey, valueForDay);
|
||||
}
|
||||
|
||||
valueForDay[value.event_signature] =
|
||||
(valueForDay[value.event_signature] || 0) + value.count;
|
||||
valueForDay[value.topic_0] =
|
||||
(valueForDay[value.topic_0] || 0) + value.count;
|
||||
}
|
||||
|
||||
const values: EventBreakdownEntry[] = [];
|
||||
|
||||
+21
-16
@@ -30,11 +30,17 @@ export async function getContractEventAnalytics(params: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}): Promise<AnalyticsEntry[]> {
|
||||
const daysDifference =
|
||||
params.startDate && params.endDate
|
||||
? Math.ceil(
|
||||
(params.endDate.getTime() - params.startDate.getTime()) /
|
||||
(1000 * 60 * 60 * 24),
|
||||
)
|
||||
: 30;
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"group_by=time",
|
||||
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
|
||||
"aggregate=count(block_timestamp) as count",
|
||||
"group_by=day",
|
||||
`limit=${daysDifference}`,
|
||||
params.startDate
|
||||
? `filter_block_timestamp_gte=${getUnixTime(params.startDate)}`
|
||||
: "",
|
||||
@@ -45,17 +51,17 @@ export async function getContractEventAnalytics(params: {
|
||||
.filter(Boolean)
|
||||
.join("&");
|
||||
|
||||
const res = await fetch(
|
||||
`https://insight.${thirdwebDomain}.com/v1/events/${params.contractAddress}?${queryParams}`,
|
||||
{
|
||||
headers: {
|
||||
"x-client-id": NEXT_PUBLIC_DASHBOARD_CLIENT_ID,
|
||||
},
|
||||
const url = `https://insight.${thirdwebDomain}.com/v1/events/${params.contractAddress}?${queryParams}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"x-client-id": NEXT_PUBLIC_DASHBOARD_CLIENT_ID,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(`Failed to fetch events analytics data: ${errorText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
@@ -67,14 +73,13 @@ export async function getContractEventAnalytics(params: {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"time" in value &&
|
||||
"day" in value &&
|
||||
"count" in value &&
|
||||
typeof value.time === "string" &&
|
||||
typeof value.count === "number"
|
||||
typeof value.day === "string"
|
||||
) {
|
||||
values.push({
|
||||
count: value.count,
|
||||
time: new Date(value.time),
|
||||
count: Number(value.count),
|
||||
time: new Date(value.day),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+13
-8
@@ -26,12 +26,18 @@ export async function getContractFunctionBreakdown(params: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}): Promise<FunctionBreakdownEntry[]> {
|
||||
const daysDifference =
|
||||
params.startDate && params.endDate
|
||||
? Math.ceil(
|
||||
(params.endDate.getTime() - params.startDate.getTime()) /
|
||||
(1000 * 60 * 60 * 24),
|
||||
)
|
||||
: 30;
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"group_by=time",
|
||||
"group_by=day",
|
||||
"group_by=function_selector",
|
||||
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
|
||||
"aggregate=count(*) as count",
|
||||
`limit=${daysDifference * 10}`, // at most 10 functions per day
|
||||
params.startDate
|
||||
? `filter_block_timestamp_gte=${getUnixTime(params.startDate)}`
|
||||
: "",
|
||||
@@ -68,17 +74,16 @@ export async function getContractFunctionBreakdown(params: {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"time" in value &&
|
||||
"day" in value &&
|
||||
"count" in value &&
|
||||
"function_selector" in value &&
|
||||
typeof value.function_selector === "string" &&
|
||||
typeof value.time === "string" &&
|
||||
typeof value.count === "number"
|
||||
typeof value.day === "string"
|
||||
) {
|
||||
collectedAggregations.push({
|
||||
count: value.count,
|
||||
count: Number(value.count),
|
||||
function_selector: value.function_selector,
|
||||
time: value.time,
|
||||
time: value.day,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+15
-9
@@ -30,11 +30,17 @@ export async function getContractTransactionAnalytics(params: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}): Promise<TransactionAnalyticsEntry[]> {
|
||||
const daysDifference =
|
||||
params.startDate && params.endDate
|
||||
? Math.ceil(
|
||||
(params.endDate.getTime() - params.startDate.getTime()) /
|
||||
(1000 * 60 * 60 * 24),
|
||||
)
|
||||
: 30;
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"group_by=time",
|
||||
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
|
||||
"aggregate=count(block_timestamp) as count",
|
||||
"group_by=day",
|
||||
`limit=${daysDifference}`,
|
||||
params.startDate
|
||||
? `filter_block_timestamp_gte=${getUnixTime(params.startDate)}`
|
||||
: "",
|
||||
@@ -55,7 +61,8 @@ export async function getContractTransactionAnalytics(params: {
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(`Failed to fetch transaction analytics data: ${errorText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
@@ -67,14 +74,13 @@ export async function getContractTransactionAnalytics(params: {
|
||||
if (
|
||||
typeof tx === "object" &&
|
||||
tx !== null &&
|
||||
"time" in tx &&
|
||||
"day" in tx &&
|
||||
"count" in tx &&
|
||||
typeof tx.time === "string" &&
|
||||
typeof tx.count === "number"
|
||||
typeof tx.day === "string"
|
||||
) {
|
||||
returnValue.push({
|
||||
count: tx.count,
|
||||
time: new Date(tx.time),
|
||||
count: Number(tx.count),
|
||||
time: new Date(tx.day),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+17
-9
@@ -30,11 +30,18 @@ export async function getContractUniqueWalletAnalytics(params: {
|
||||
startDate?: Date;
|
||||
endDate?: Date;
|
||||
}): Promise<TransactionAnalyticsEntry[]> {
|
||||
const daysDifference =
|
||||
params.startDate && params.endDate
|
||||
? Math.ceil(
|
||||
(params.endDate.getTime() - params.startDate.getTime()) /
|
||||
(1000 * 60 * 60 * 24),
|
||||
)
|
||||
: 30;
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"group_by=time",
|
||||
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
|
||||
"aggregate=count(distinct from_address) as count",
|
||||
"group_by=day",
|
||||
"aggregate=count(distinct from_address)",
|
||||
`limit=${daysDifference}`,
|
||||
params.startDate
|
||||
? `filter_block_timestamp_gte=${getUnixTime(params.startDate)}`
|
||||
: "",
|
||||
@@ -55,10 +62,12 @@ export async function getContractUniqueWalletAnalytics(params: {
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(`Failed to fetch wallet analytics data: ${errorText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
console.log("wallet analytics json", json);
|
||||
const aggregations = Object.values(json.aggregations[0]);
|
||||
|
||||
const returnValue: TransactionAnalyticsEntry[] = [];
|
||||
@@ -67,14 +76,13 @@ export async function getContractUniqueWalletAnalytics(params: {
|
||||
if (
|
||||
typeof tx === "object" &&
|
||||
tx !== null &&
|
||||
"time" in tx &&
|
||||
"day" in tx &&
|
||||
"count" in tx &&
|
||||
typeof tx.time === "string" &&
|
||||
typeof tx.count === "number"
|
||||
typeof tx.day === "string"
|
||||
) {
|
||||
returnValue.push({
|
||||
count: tx.count,
|
||||
time: new Date(tx.time),
|
||||
count: Number(tx.count),
|
||||
time: new Date(tx.day),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -6,7 +6,7 @@ type InsightResponse = {
|
||||
aggregations: [
|
||||
{
|
||||
0: {
|
||||
total: number;
|
||||
count: number;
|
||||
};
|
||||
},
|
||||
];
|
||||
@@ -19,10 +19,9 @@ export async function getTotalContractEvents(params: {
|
||||
contractAddress: string;
|
||||
chainId: number;
|
||||
}): Promise<{ count: number }> {
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"aggregate=count(block_number) as total",
|
||||
].join("&");
|
||||
const queryParams = [`chain=${params.chainId}`, "aggregate=count()"].join(
|
||||
"&",
|
||||
);
|
||||
|
||||
const res = await fetch(
|
||||
`https://insight.${thirdwebDomain}.com/v1/events/${params.contractAddress}?${queryParams}`,
|
||||
@@ -34,12 +33,13 @@ export async function getTotalContractEvents(params: {
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(`Failed to fetch events analytics data: ${errorText}`);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
|
||||
return {
|
||||
count: json.aggregations[0][0].total,
|
||||
count: json.aggregations[0][0].count,
|
||||
};
|
||||
}
|
||||
|
||||
+9
-7
@@ -6,7 +6,7 @@ type InsightResponse = {
|
||||
aggregations: [
|
||||
{
|
||||
0: {
|
||||
total: number;
|
||||
count: number;
|
||||
};
|
||||
},
|
||||
];
|
||||
@@ -19,10 +19,9 @@ export async function getTotalContractTransactions(params: {
|
||||
contractAddress: string;
|
||||
chainId: number;
|
||||
}): Promise<{ count: number }> {
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"aggregate=count(block_number) as total",
|
||||
].join("&");
|
||||
const queryParams = [`chain=${params.chainId}`, "aggregate=count()"].join(
|
||||
"&",
|
||||
);
|
||||
|
||||
const res = await fetch(
|
||||
`https://insight.${thirdwebDomain}.com/v1/transactions/${params.contractAddress}?${queryParams}`,
|
||||
@@ -34,12 +33,15 @@ export async function getTotalContractTransactions(params: {
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(
|
||||
`Failed to fetch transactions analytics data: ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
|
||||
return {
|
||||
count: json.aggregations[0][0].total,
|
||||
count: json.aggregations[0][0].count,
|
||||
};
|
||||
}
|
||||
|
||||
+7
-4
@@ -6,7 +6,7 @@ type InsightResponse = {
|
||||
aggregations: [
|
||||
{
|
||||
0: {
|
||||
total: number;
|
||||
count: number;
|
||||
};
|
||||
},
|
||||
];
|
||||
@@ -21,7 +21,7 @@ export async function getTotalContractUniqueWallets(params: {
|
||||
}): Promise<{ count: number }> {
|
||||
const queryParams = [
|
||||
`chain=${params.chainId}`,
|
||||
"aggregate=count(distinct from_address) as total",
|
||||
"aggregate=count(distinct from_address)",
|
||||
].join("&");
|
||||
|
||||
const res = await fetch(
|
||||
@@ -34,12 +34,15 @@ export async function getTotalContractUniqueWallets(params: {
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to fetch analytics data");
|
||||
const errorText = await res.text();
|
||||
throw new Error(
|
||||
`Failed to fetch unique wallets analytics data: ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const json = (await res.json()) as InsightResponse;
|
||||
|
||||
return {
|
||||
count: json.aggregations[0][0].total,
|
||||
count: json.aggregations[0][0].count,
|
||||
};
|
||||
}
|
||||
|
||||
+3
@@ -28,6 +28,9 @@ export function PublicPageConnectButton(props: {
|
||||
connectButton={{
|
||||
className: props.connectButtonClassName,
|
||||
}}
|
||||
detailsButton={{
|
||||
className: props.connectButtonClassName,
|
||||
}}
|
||||
connectModal={{
|
||||
privacyPolicyUrl: "/privacy-policy",
|
||||
showThirdwebBranding: false,
|
||||
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
import "server-only";
|
||||
import { isProd } from "@/constants/env-utils";
|
||||
import { DASHBOARD_THIRDWEB_SECRET_KEY } from "@/constants/server-envs";
|
||||
|
||||
export type TokenPriceData = {
|
||||
price_usd: number;
|
||||
price_usd_cents: number;
|
||||
percent_change_24h: number;
|
||||
market_cap_usd: number;
|
||||
volume_24h_usd: number;
|
||||
volume_change_24h: number;
|
||||
holders: number;
|
||||
historical_prices: Array<{
|
||||
date: string;
|
||||
price_usd: number;
|
||||
price_usd_cents: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
export async function getTokenPriceData(params: {
|
||||
chainId: number;
|
||||
contractAddress: string;
|
||||
}) {
|
||||
try {
|
||||
const url = new URL(
|
||||
`https://insight.${isProd ? "thirdweb" : "thirdweb-dev"}.com/v1/tokens/price`,
|
||||
);
|
||||
|
||||
url.searchParams.set("include_historical_prices", "true");
|
||||
url.searchParams.set("chain_id", params.chainId.toString());
|
||||
url.searchParams.set("address", params.contractAddress);
|
||||
url.searchParams.set("include_holders", "true");
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"x-secret-key": DASHBOARD_THIRDWEB_SECRET_KEY,
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
console.error("Failed to fetch token price data", await res.text());
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const json = await res.json();
|
||||
const priceData = json.data[0] as TokenPriceData | undefined;
|
||||
|
||||
return priceData;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useTheme } from "next-themes";
|
||||
import type { Chain, ThirdwebClient } from "thirdweb";
|
||||
import { BuyWidget } from "thirdweb/react";
|
||||
import {
|
||||
reportAssetBuyFailed,
|
||||
reportAssetBuySuccessful,
|
||||
} from "@/analytics/report";
|
||||
import { parseError } from "@/utils/errorParser";
|
||||
import { getSDKTheme } from "@/utils/sdk-component-theme";
|
||||
|
||||
export function BuyTokenEmbed(props: {
|
||||
client: ThirdwebClient;
|
||||
chain: Chain;
|
||||
tokenAddress: string;
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
return (
|
||||
<BuyWidget
|
||||
amount="1"
|
||||
chain={props.chain}
|
||||
className="!rounded-xl !w-full"
|
||||
client={props.client}
|
||||
connectOptions={{
|
||||
autoConnect: false,
|
||||
}}
|
||||
onError={(e) => {
|
||||
const errorMessage = parseError(e);
|
||||
reportAssetBuyFailed({
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: "DropERC20",
|
||||
error: errorMessage,
|
||||
});
|
||||
}}
|
||||
onSuccess={() => {
|
||||
reportAssetBuySuccessful({
|
||||
assetType: "coin",
|
||||
chainId: props.chain.id,
|
||||
contractType: "DropERC20",
|
||||
});
|
||||
}}
|
||||
theme={getSDKTheme(theme === "light" ? "light" : "dark")}
|
||||
tokenAddress={props.tokenAddress as `0x${string}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
-264
@@ -1,264 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { differenceInCalendarDays, format } from "date-fns";
|
||||
import { ArrowDownIcon, ArrowUpIcon, InfoIcon } from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ThirdwebAreaChart } from "@/components/blocks/charts/area-chart";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ToolTipLabel } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { TokenPriceData } from "../_apis/token-price-data";
|
||||
|
||||
function PriceChartUI(props: {
|
||||
showTimeOfDay: boolean;
|
||||
data: Array<{
|
||||
date: string;
|
||||
price_usd: number;
|
||||
price_usd_cents: number;
|
||||
}>;
|
||||
}) {
|
||||
const data = props.data.map((item) => ({
|
||||
price: item.price_usd,
|
||||
time: new Date(item.date).getTime(),
|
||||
}));
|
||||
|
||||
return (
|
||||
<ThirdwebAreaChart
|
||||
cardContentClassName="p-0"
|
||||
chartClassName="aspect-[1.5] lg:aspect-[3]"
|
||||
className="border-none bg-transparent p-0"
|
||||
config={{
|
||||
price: {
|
||||
color: "hsl(var(--chart-1))",
|
||||
label: "Price",
|
||||
},
|
||||
}}
|
||||
data={data}
|
||||
hideLabel={false}
|
||||
isPending={false}
|
||||
toolTipLabelFormatter={getTooltipLabelFormatter(props.showTimeOfDay)}
|
||||
toolTipValueFormatter={(value) => {
|
||||
return tokenPriceUSDFormatter.format(value as number);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const tokenPriceUSDFormatter = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
maximumFractionDigits: 8,
|
||||
minimumFractionDigits: 0,
|
||||
notation: "compact",
|
||||
roundingMode: "halfEven",
|
||||
style: "currency",
|
||||
});
|
||||
|
||||
const marketCapFormatter = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
maximumFractionDigits: 0,
|
||||
minimumFractionDigits: 0,
|
||||
notation: "compact",
|
||||
roundingMode: "halfEven",
|
||||
style: "currency",
|
||||
});
|
||||
|
||||
const holdersFormatter = new Intl.NumberFormat("en-US", {
|
||||
maximumFractionDigits: 0,
|
||||
minimumFractionDigits: 0,
|
||||
notation: "compact",
|
||||
});
|
||||
|
||||
const percentChangeFormatter = new Intl.NumberFormat("en-US", {
|
||||
maximumFractionDigits: 2,
|
||||
minimumFractionDigits: 0,
|
||||
});
|
||||
|
||||
function getTooltipLabelFormatter(includeTimeOfDay: boolean) {
|
||||
return (_v: string, item: unknown) => {
|
||||
if (Array.isArray(item)) {
|
||||
const time = item[0].payload.time as number;
|
||||
return format(
|
||||
new Date(time),
|
||||
includeTimeOfDay ? "MMM d, yyyy hh:mm a" : "MMM d, yyyy",
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export function TokenStats(params: {
|
||||
chainId: number;
|
||||
contractAddress: string;
|
||||
tokenPriceData: TokenPriceData;
|
||||
}) {
|
||||
const [interval, setInterval] = useState<Interval>("max");
|
||||
|
||||
const filteredHistoricalPrices = useMemo(() => {
|
||||
const currentDate = new Date();
|
||||
|
||||
return params.tokenPriceData.historical_prices.filter((item) => {
|
||||
const date = new Date(item.date);
|
||||
const maxDiff =
|
||||
interval === "24h"
|
||||
? 1
|
||||
: interval === "7d"
|
||||
? 7
|
||||
: interval === "30d"
|
||||
? 30
|
||||
: interval === "1y"
|
||||
? 365
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
|
||||
return differenceInCalendarDays(currentDate, date) <= maxDiff;
|
||||
});
|
||||
}, [params.tokenPriceData, interval]);
|
||||
|
||||
const priceUsd = params.tokenPriceData.price_usd;
|
||||
const percentChange24h = params.tokenPriceData.percent_change_24h;
|
||||
const marketCap = params.tokenPriceData.market_cap_usd;
|
||||
const holders = params.tokenPriceData.holders;
|
||||
|
||||
const formattedAbsChange = percentChangeFormatter.format(
|
||||
Math.abs(percentChange24h),
|
||||
);
|
||||
|
||||
const isAlmostZeroChange =
|
||||
formattedAbsChange === percentChangeFormatter.format(0);
|
||||
|
||||
const formattedPriceUSD = tokenPriceUSDFormatter.format(priceUsd);
|
||||
|
||||
return (
|
||||
<div className="bg-card rounded-lg border">
|
||||
{/* price and change */}
|
||||
<div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between p-4 lg:p-6">
|
||||
<div>
|
||||
<p className="mb-1 text-muted-foreground text-sm">Current Price</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<p
|
||||
className={cn(
|
||||
"font-bold text-3xl lg:text-4xl tracking-tight",
|
||||
formattedPriceUSD.length > 8 && "text-2xl lg:text-4xl",
|
||||
)}
|
||||
>
|
||||
{typeof priceUsd === "number" ? formattedPriceUSD : priceUsd}
|
||||
</p>
|
||||
<Badge
|
||||
className="gap-2 lg:text-sm text-xs px-1.5"
|
||||
variant={
|
||||
isAlmostZeroChange
|
||||
? "default"
|
||||
: percentChange24h > 0
|
||||
? "success"
|
||||
: "destructive"
|
||||
}
|
||||
>
|
||||
<div className="flex items-center gap-0.5">
|
||||
{isAlmostZeroChange ? null : percentChange24h > 0 ? (
|
||||
<ArrowUpIcon className="size-3" />
|
||||
) : (
|
||||
<ArrowDownIcon className="size-3" />
|
||||
)}
|
||||
<span>
|
||||
{isAlmostZeroChange ? "~0%" : `${formattedAbsChange}%`}
|
||||
</span>
|
||||
</div>
|
||||
<span>(1d)</span>
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<IntervalSelector interval={interval} setInterval={setInterval} />
|
||||
</div>
|
||||
|
||||
<div className="px-0">
|
||||
<PriceChartUI
|
||||
data={filteredHistoricalPrices || []}
|
||||
showTimeOfDay={interval === "24h"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="px-4 lg:px-6 py-4 mt-6 border-t border-dashed flex gap-6 [&>*:not(:first-child)]:border-l [&>*:not(:first-child)]:pl-5 [&>*]:grow">
|
||||
<TokenStat
|
||||
label="Market Cap"
|
||||
tooltip="Market capitalization is the total value of all tokens in circulation, calculated by multiplying the current price by the circulating supply"
|
||||
value={
|
||||
typeof marketCap === "number"
|
||||
? marketCapFormatter.format(marketCap)
|
||||
: marketCap
|
||||
}
|
||||
/>
|
||||
|
||||
<TokenStat
|
||||
label="Number of Holders"
|
||||
tooltip="The total number of unique wallet addresses that currently hold this token on the blockchain"
|
||||
value={
|
||||
// show 0 value as N/A
|
||||
holders === 0
|
||||
? "N/A"
|
||||
: typeof holders === "number"
|
||||
? holdersFormatter.format(holders)
|
||||
: holders
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TokenStat(props: {
|
||||
value: string | number;
|
||||
label: string;
|
||||
tooltip: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-muted-foreground text-sm">{props.label}</p>
|
||||
<ToolTipLabel label={props.tooltip}>
|
||||
<InfoIcon className="size-3.5 text-muted-foreground" />
|
||||
</ToolTipLabel>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<p className="font-semibold text-foreground text-xl tracking-tight">
|
||||
{props.value}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type Interval = "24h" | "7d" | "30d" | "1y" | "max";
|
||||
|
||||
function IntervalSelector(props: {
|
||||
interval: Interval;
|
||||
setInterval: (timeframe: Interval) => void;
|
||||
}) {
|
||||
const intervals: Record<Interval, string> = {
|
||||
"1y": "1Y",
|
||||
"7d": "1W",
|
||||
"24h": "1D",
|
||||
"30d": "1M",
|
||||
max: "MAX",
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
{Object.entries(intervals).map(([key, value]) => (
|
||||
<Button
|
||||
className={cn(
|
||||
"rounded-full px-2.5 py-1.5 h-auto bg-background text-xs lg:text-sm",
|
||||
props.interval === key && "border-active-border bg-accent",
|
||||
)}
|
||||
key={key}
|
||||
onClick={() => props.setInterval(key as Interval)}
|
||||
size="sm"
|
||||
tabIndex={0}
|
||||
variant="outline"
|
||||
>
|
||||
{value}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
export const mapChainIdToDexScreenerChainSlug = {
|
||||
8453: "base",
|
||||
1: "ethereum",
|
||||
56: "bsc",
|
||||
369: "pulsechain",
|
||||
137: "polygon",
|
||||
2741: "abstract",
|
||||
43114: "avalanche",
|
||||
999: "hyperliquid",
|
||||
480: "worldchain",
|
||||
42161: "arbitrum",
|
||||
388: "cronos",
|
||||
59144: "linea",
|
||||
1514: "story",
|
||||
397: "near",
|
||||
295: "hedera",
|
||||
146: "sonic",
|
||||
10: "optimism",
|
||||
80094: "berachain",
|
||||
57073: "ink",
|
||||
130: "unichain",
|
||||
5000: "mantle",
|
||||
324: "zksync",
|
||||
466: "apechain",
|
||||
1116: "core",
|
||||
250: "fantom",
|
||||
1868: "soneium",
|
||||
81457: "blast",
|
||||
2000: "dogechain",
|
||||
14: "flare",
|
||||
2040: "vana",
|
||||
4337: "beam",
|
||||
109: "shibarium",
|
||||
747: "flowevm",
|
||||
1088: "metis",
|
||||
1030: "conflux",
|
||||
43113: "avalanchedfk",
|
||||
534352: "scroll",
|
||||
747474: "katana",
|
||||
42220: "celo",
|
||||
1284: "moonbeam",
|
||||
4200: "merlinchain",
|
||||
2222: "kava",
|
||||
39797: "energi",
|
||||
34443: "mode",
|
||||
252: "fraxtal",
|
||||
48900: "zircuit",
|
||||
20: "elastos",
|
||||
100: "gnosischain",
|
||||
204: "opbnb",
|
||||
169: "manta",
|
||||
1313161554: "aurora",
|
||||
3073: "movement",
|
||||
4689: "iotex",
|
||||
23294: "oasissapphire",
|
||||
6001: "bouncebit",
|
||||
42170: "arbitrumnova",
|
||||
1101: "polygonzkevm",
|
||||
40: "telos",
|
||||
592: "astar",
|
||||
42262: "oasisemerald",
|
||||
1285: "moonriver",
|
||||
245022934: "neonevm",
|
||||
7777777: "zora",
|
||||
122: "fuse",
|
||||
321: "kcc",
|
||||
1234: "stepnetwork",
|
||||
106: "velas",
|
||||
167000: "taiko",
|
||||
288: "boba",
|
||||
42766: "zkfair",
|
||||
32520: "bitgert",
|
||||
82: "meter",
|
||||
} as const;
|
||||
|
||||
export type DexScreenerChainSlug =
|
||||
(typeof mapChainIdToDexScreenerChainSlug)[keyof typeof mapChainIdToDexScreenerChainSlug];
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
import { Spinner } from "@workspace/ui/components/spinner";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useMemo } from "react";
|
||||
import { ClientOnly } from "@/components/blocks/client-only";
|
||||
import type { DexScreenerChainSlug } from "./dex-screener-chains";
|
||||
|
||||
function DexScreenerIframe(props: {
|
||||
chain: DexScreenerChainSlug;
|
||||
contractAddress: string;
|
||||
}) {
|
||||
const { theme } = useTheme();
|
||||
|
||||
const iframeUrl = useMemo(() => {
|
||||
const resolvedTheme = theme === "light" ? "light" : "dark";
|
||||
const url = new URL("https://dexscreener.com");
|
||||
url.pathname = `${props.chain}/${props.contractAddress}`;
|
||||
url.searchParams.set("embed", "1");
|
||||
url.searchParams.set("loadChartSettings", "0");
|
||||
url.searchParams.set("chartTheme", resolvedTheme);
|
||||
url.searchParams.set("theme", resolvedTheme);
|
||||
url.searchParams.set("trades", "1");
|
||||
url.searchParams.set("chartStyle", "1");
|
||||
url.searchParams.set("chartLeftToolbar", "0");
|
||||
url.searchParams.set("chartType", "usd");
|
||||
url.searchParams.set("interval", "15");
|
||||
url.searchParams.set("chartDefaultOnMobile", "1");
|
||||
return url.toString();
|
||||
}, [theme, props.chain, props.contractAddress]);
|
||||
|
||||
return (
|
||||
<iframe
|
||||
className="w-full h-[500px] lg:h-[1000px] rounded-lg overflow-hidden border bg-card"
|
||||
src={iframeUrl}
|
||||
title="DexScreener"
|
||||
></iframe>
|
||||
);
|
||||
}
|
||||
|
||||
export function DexScreener(props: {
|
||||
chain: DexScreenerChainSlug;
|
||||
contractAddress: string;
|
||||
}) {
|
||||
return (
|
||||
<ClientOnly
|
||||
ssr={
|
||||
<div className="w-full h-[500px] lg:h-[1000px] rounded-lg border bg-card items-center justify-center flex">
|
||||
<Spinner className="size-10" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<DexScreenerIframe
|
||||
chain={props.chain}
|
||||
contractAddress={props.contractAddress}
|
||||
/>
|
||||
</ClientOnly>
|
||||
);
|
||||
}
|
||||
+59
-71
@@ -3,18 +3,18 @@ import type { ThirdwebContract } from "thirdweb";
|
||||
import type { ChainMetadata } from "thirdweb/chains";
|
||||
import { getContractMetadata } from "thirdweb/extensions/common";
|
||||
import { decimals, getActiveClaimCondition } from "thirdweb/extensions/erc20";
|
||||
import { GridPattern } from "@/components/ui/background-patterns";
|
||||
import { BuyAndSwapEmbed } from "@/components/blocks/BuyAndSwapEmbed";
|
||||
import { GridPatternEmbedContainer } from "@/components/blocks/grid-pattern-embed-container";
|
||||
import { HAS_USED_DASHBOARD } from "@/constants/cookie";
|
||||
import { resolveFunctionSelectors } from "@/lib/selectors";
|
||||
import { AssetPageView } from "../_components/asset-page-view";
|
||||
import { getContractCreator } from "../_components/getContractCreator";
|
||||
import { PageHeader } from "../_components/PageHeader";
|
||||
import { getTokenPriceData } from "./_apis/token-price-data";
|
||||
import { ContractHeaderUI } from "./_components/ContractHeader";
|
||||
import { TokenDropClaim } from "./_components/claim-tokens/claim-tokens-ui";
|
||||
import { ContractAnalyticsOverview } from "./_components/contract-analytics/contract-analytics";
|
||||
import { BuyTokenEmbed } from "./_components/PayEmbedSection";
|
||||
import { TokenStats } from "./_components/PriceChart";
|
||||
import { DexScreener } from "./_components/dex-screener";
|
||||
import { mapChainIdToDexScreenerChainSlug } from "./_components/dex-screener-chains";
|
||||
import { RecentTransfers } from "./_components/RecentTransfers";
|
||||
import { fetchTokenInfoFromBridge } from "./_utils/fetch-coin-info";
|
||||
import { getCurrencyMeta } from "./_utils/getCurrencyMeta";
|
||||
@@ -28,9 +28,8 @@ export async function ERC20PublicPage(props: {
|
||||
contractMetadata,
|
||||
activeClaimCondition,
|
||||
tokenDecimals,
|
||||
tokenInfo,
|
||||
tokenInfoFromUB,
|
||||
functionSelectors,
|
||||
tokenPriceData,
|
||||
] = await Promise.all([
|
||||
getContractMetadata({
|
||||
contract: props.serverContract,
|
||||
@@ -45,14 +44,10 @@ export async function ERC20PublicPage(props: {
|
||||
tokenAddress: props.serverContract.address,
|
||||
}),
|
||||
resolveFunctionSelectors(props.serverContract),
|
||||
getTokenPriceData({
|
||||
chainId: props.serverContract.chain.id,
|
||||
contractAddress: props.serverContract.address,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!contractMetadata.image && tokenInfo) {
|
||||
contractMetadata.image = tokenInfo.iconUri;
|
||||
if (!contractMetadata.image && tokenInfoFromUB) {
|
||||
contractMetadata.image = tokenInfoFromUB.iconUri;
|
||||
}
|
||||
|
||||
const [contractCreator, claimConditionCurrencyMeta] = await Promise.all([
|
||||
@@ -70,32 +65,23 @@ export async function ERC20PublicPage(props: {
|
||||
const cookieStore = await cookies();
|
||||
const isDashboardUser = cookieStore.has(HAS_USED_DASHBOARD);
|
||||
|
||||
const buyEmbed = (
|
||||
<BuyEmbed
|
||||
chainMetadata={props.chainMetadata}
|
||||
claimConditionMeta={
|
||||
activeClaimCondition && claimConditionCurrencyMeta
|
||||
? {
|
||||
activeClaimCondition,
|
||||
claimConditionCurrency: claimConditionCurrencyMeta,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
clientContract={props.clientContract}
|
||||
tokenAddress={props.clientContract.address}
|
||||
tokenDecimals={tokenDecimals}
|
||||
tokenName={contractMetadata.name}
|
||||
tokenSymbol={contractMetadata.symbol}
|
||||
/>
|
||||
);
|
||||
const claimConditionMeta =
|
||||
activeClaimCondition && claimConditionCurrencyMeta
|
||||
? {
|
||||
activeClaimCondition,
|
||||
claimConditionCurrency: claimConditionCurrencyMeta,
|
||||
}
|
||||
: undefined;
|
||||
const isUBSupported = !!tokenInfoFromUB;
|
||||
const showBuyEmbed = isUBSupported || claimConditionMeta;
|
||||
|
||||
return (
|
||||
<div className="flex grow flex-col">
|
||||
<AssetPageView assetType="coin" chainId={props.chainMetadata.chainId} />
|
||||
<PageHeader containerClassName="max-w-5xl" />
|
||||
<PageHeader containerClassName="max-w-7xl" />
|
||||
|
||||
<div className="border-b">
|
||||
<div className="container max-w-5xl">
|
||||
<div className="container max-w-7xl">
|
||||
<ContractHeaderUI
|
||||
chainMetadata={props.chainMetadata}
|
||||
clientContract={props.clientContract}
|
||||
@@ -114,45 +100,45 @@ export async function ERC20PublicPage(props: {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="container flex max-w-5xl grow flex-col pt-8 pb-10">
|
||||
<div className="h-8" />
|
||||
|
||||
{showBuyEmbed && (
|
||||
<div className="container max-w-7xl pb-10">
|
||||
<GridPatternEmbedContainer>
|
||||
<BuyEmbed
|
||||
chainMetadata={props.chainMetadata}
|
||||
claimConditionMeta={claimConditionMeta}
|
||||
clientContract={props.clientContract}
|
||||
tokenAddress={props.clientContract.address}
|
||||
tokenDecimals={tokenDecimals}
|
||||
tokenName={contractMetadata.name}
|
||||
tokenSymbol={contractMetadata.symbol}
|
||||
/>
|
||||
</GridPatternEmbedContainer>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{props.chainMetadata.chainId in mapChainIdToDexScreenerChainSlug && (
|
||||
<div className="container max-w-7xl pb-10">
|
||||
<DexScreener
|
||||
chain={
|
||||
mapChainIdToDexScreenerChainSlug[
|
||||
props.chainMetadata
|
||||
.chainId as keyof typeof mapChainIdToDexScreenerChainSlug
|
||||
]
|
||||
}
|
||||
contractAddress={props.clientContract.address}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="container flex max-w-7xl grow flex-col pb-10">
|
||||
<div className="flex grow flex-col gap-8">
|
||||
<div className="sm:flex sm:justify-center w-full sm:border sm:border-dashed sm:bg-accent/20 sm:py-12 rounded-lg overflow-hidden relative">
|
||||
<GridPattern
|
||||
width={30}
|
||||
height={30}
|
||||
x={-1}
|
||||
y={-1}
|
||||
strokeDasharray={"4 2"}
|
||||
className="text-border dark:text-border/70"
|
||||
style={{
|
||||
maskImage:
|
||||
"linear-gradient(to bottom right,white,transparent,transparent)",
|
||||
}}
|
||||
/>
|
||||
<div className="sm:w-[420px] z-10">{buyEmbed}</div>
|
||||
</div>
|
||||
|
||||
{tokenPriceData ? (
|
||||
<>
|
||||
<TokenStats
|
||||
chainId={props.chainMetadata.chainId}
|
||||
contractAddress={props.clientContract.address}
|
||||
tokenPriceData={tokenPriceData}
|
||||
/>
|
||||
|
||||
<ContractAnalyticsOverview
|
||||
chainId={props.chainMetadata.chainId}
|
||||
chainSlug={props.chainMetadata.slug}
|
||||
contractAddress={props.clientContract.address}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<ContractAnalyticsOverview
|
||||
chainId={props.chainMetadata.chainId}
|
||||
chainSlug={props.chainMetadata.slug}
|
||||
contractAddress={props.clientContract.address}
|
||||
/>
|
||||
)}
|
||||
<ContractAnalyticsOverview
|
||||
chainId={props.chainMetadata.chainId}
|
||||
chainSlug={props.chainMetadata.slug}
|
||||
contractAddress={props.clientContract.address}
|
||||
/>
|
||||
|
||||
<RecentTransfers
|
||||
chainMetadata={props.chainMetadata}
|
||||
@@ -185,10 +171,12 @@ function BuyEmbed(props: {
|
||||
}) {
|
||||
if (!props.claimConditionMeta) {
|
||||
return (
|
||||
<BuyTokenEmbed
|
||||
<BuyAndSwapEmbed
|
||||
chain={props.clientContract.chain}
|
||||
client={props.clientContract.client}
|
||||
tokenAddress={props.clientContract.address}
|
||||
buyAmount={undefined}
|
||||
pageType="asset"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -62,8 +62,8 @@ export const products = [
|
||||
description: "The most powerful AI for interacting with the blockchain",
|
||||
icon: NebulaIcon,
|
||||
id: "nebula",
|
||||
link: "https://thirdweb.com/nebula",
|
||||
name: "Nebula",
|
||||
link: "https://thirdweb.com/ai",
|
||||
name: "thirdweb AI",
|
||||
},
|
||||
] satisfies Array<{
|
||||
name: string;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Link from "next/link";
|
||||
import { ToggleThemeButton } from "@/components/blocks/color-mode-toggle";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ThirdwebMiniLogo } from "../../../components/ThirdwebMiniLogo";
|
||||
import { PublicPageConnectButton } from "../../(chain)/[chain_id]/[contractAddress]/public-pages/_components/PublicPageConnectButton";
|
||||
|
||||
export function PageHeader(props: { containerClassName?: string }) {
|
||||
return (
|
||||
<div className="border-b">
|
||||
<header
|
||||
className={cn(
|
||||
"container flex max-w-7xl justify-between py-3",
|
||||
props.containerClassName,
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<Link className="flex items-center gap-2" href="/team">
|
||||
<ThirdwebMiniLogo className="h-5" />
|
||||
<span className="hidden font-bold text-2xl tracking-tight lg:block">
|
||||
thirdweb
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-5">
|
||||
<Link
|
||||
href="https://portal.thirdweb.com/bridge"
|
||||
target="_blank"
|
||||
className="text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Docs
|
||||
</Link>
|
||||
<ToggleThemeButton />
|
||||
<PublicPageConnectButton connectButtonClassName="!rounded-full" />
|
||||
</div>
|
||||
</header>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Input } from "@workspace/ui/components/input";
|
||||
import { cn } from "@workspace/ui/lib/utils";
|
||||
import { ActivityIcon, SearchIcon, TrendingUpIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Bridge } from "thirdweb";
|
||||
import { BridgeNetworkSelector } from "@/components/blocks/NetworkSelectors";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { TokensTable } from "./tokens-table";
|
||||
|
||||
const client = getClientThirdwebClient();
|
||||
|
||||
const pageSize = 20;
|
||||
|
||||
export function TokenPage(props: { chains: Bridge.chains.Result }) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [chainId, setChainId] = useState(1);
|
||||
const [search, setSearch] = useState("");
|
||||
const [sortBy, setSortBy] = useState<"volume" | "market_cap">("volume");
|
||||
|
||||
const tokensQuery = useQuery({
|
||||
queryKey: [
|
||||
"tokens",
|
||||
{
|
||||
page,
|
||||
chainId,
|
||||
sortBy,
|
||||
search,
|
||||
},
|
||||
],
|
||||
queryFn: () => {
|
||||
return Bridge.tokens({
|
||||
client: client,
|
||||
chainId: chainId,
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize,
|
||||
sortBy: search ? undefined : sortBy,
|
||||
query: search ? search : undefined,
|
||||
});
|
||||
},
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="pb-20 pt-8">
|
||||
<div className="container max-w-7xl">
|
||||
<div className="mb-4 flex gap-4 lg:gap-3 flex-col lg:flex-row">
|
||||
<BridgeNetworkSelector
|
||||
client={client}
|
||||
chainId={chainId}
|
||||
onChange={setChainId}
|
||||
className="rounded-xl bg-card lg:w-fit min-w-[280px]"
|
||||
popoverContentClassName="!w-[300px] rounded-xl overflow-hidden"
|
||||
chains={props.chains}
|
||||
/>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<SortButton
|
||||
label="Popular"
|
||||
onClick={() => {
|
||||
setSortBy("market_cap");
|
||||
setSearch("");
|
||||
}}
|
||||
isSelected={sortBy === "market_cap" && !search}
|
||||
icon={ActivityIcon}
|
||||
/>
|
||||
<SortButton
|
||||
label="Trending"
|
||||
onClick={() => {
|
||||
setSortBy("volume");
|
||||
setSearch("");
|
||||
}}
|
||||
isSelected={sortBy === "volume" && !search}
|
||||
icon={TrendingUpIcon}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="relative w-full lg:w-[420px] ml-auto">
|
||||
<SearchIcon className="size-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search Tokens"
|
||||
value={search}
|
||||
className="rounded-xl bg-card flex-1 pl-9"
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TokensTable
|
||||
pageSize={pageSize}
|
||||
tokens={tokensQuery.data ?? []}
|
||||
isFetching={tokensQuery.isFetching}
|
||||
pagination={{
|
||||
onNext: () => setPage(page + 1),
|
||||
onPrevious: () => setPage(page - 1),
|
||||
nextDisabled: !!(
|
||||
tokensQuery.data && tokensQuery.data.length < pageSize
|
||||
),
|
||||
previousDisabled: page === 1,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SortButton(props: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
isSelected: boolean;
|
||||
icon: React.FC<{ className?: string }>;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={props.onClick}
|
||||
className={cn(
|
||||
"rounded-xl gap-2 bg-card",
|
||||
props.isSelected && "bg-accent border-active-border",
|
||||
)}
|
||||
>
|
||||
<props.icon className="size-3.5" />
|
||||
{props.label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { type Bridge, NATIVE_TOKEN_ADDRESS } from "thirdweb";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableContainer,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
|
||||
export function TokensTable(props: {
|
||||
tokens: Bridge.TokenWithPrices[];
|
||||
pageSize: number;
|
||||
isFetching: boolean;
|
||||
pagination: {
|
||||
onNext: () => void;
|
||||
onPrevious: () => void;
|
||||
nextDisabled: boolean;
|
||||
previousDisabled: boolean;
|
||||
};
|
||||
}) {
|
||||
const { tokens, isFetching } = props;
|
||||
|
||||
return (
|
||||
<div className="border rounded-xl overflow-hidden">
|
||||
<TableContainer className="border-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Token</TableHead>
|
||||
<TableHead>Price</TableHead>
|
||||
<TableHead>Market cap</TableHead>
|
||||
<TableHead>Volume (24h)</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isFetching
|
||||
? new Array(props.pageSize).fill(0).map((_, i) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: ok
|
||||
<TableRow key={i}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<Skeleton className="size-10 rounded-full" />
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Skeleton className="h-4 w-16" />
|
||||
<Skeleton className="h-3 w-36" />
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Skeleton className="ml-auto h-4 w-16" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Skeleton className="ml-auto h-4 w-20" />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Skeleton className="ml-auto h-4 w-20" />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
: tokens.length > 0
|
||||
? tokens.map((token) => {
|
||||
const price = token.prices.USD;
|
||||
return (
|
||||
<TableRow
|
||||
key={`${token.chainId}-${token.address}`}
|
||||
className="hover:bg-accent/50"
|
||||
linkBox
|
||||
>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="size-10">
|
||||
<AvatarImage
|
||||
src={token.iconUri ?? undefined}
|
||||
alt={token.symbol}
|
||||
/>
|
||||
<AvatarFallback>
|
||||
{token.symbol?.slice(0, 2)?.toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="font-medium leading-none text-base">
|
||||
{token.symbol}
|
||||
</span>
|
||||
<Link
|
||||
href={
|
||||
token.address.toLowerCase() ===
|
||||
NATIVE_TOKEN_ADDRESS.toLowerCase()
|
||||
? `/${token.chainId}`
|
||||
: `/${token.chainId}/${token.address}`
|
||||
}
|
||||
prefetch={false}
|
||||
className="before:absolute before:inset-0"
|
||||
>
|
||||
<span className="text-sm text-muted-foreground leading-none">
|
||||
{token.name}
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{price ? formatPrice(price) : "N/A"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{token.marketCapUsd
|
||||
? formatUsdCompact(token.marketCapUsd)
|
||||
: "N/A"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{token.volume24hUsd
|
||||
? formatUsdCompact(token.volume24hUsd)
|
||||
: "N/A"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
: null}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</TableContainer>
|
||||
|
||||
{tokens.length === 0 && !isFetching && (
|
||||
<div className="flex items-center justify-center py-20 text-muted-foreground w-full text-sm ">
|
||||
No tokens found
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end p-4 gap-3 border-t bg-card">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2 rounded-full"
|
||||
size="sm"
|
||||
onClick={() => props.pagination.onPrevious()}
|
||||
disabled={props.pagination.previousDisabled || isFetching}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
Previous
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-2 rounded-full"
|
||||
size="sm"
|
||||
onClick={() => props.pagination.onNext()}
|
||||
disabled={props.pagination.nextDisabled || isFetching}
|
||||
>
|
||||
Next
|
||||
<ArrowRightIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatPrice(value: number): string {
|
||||
if (value < 100) {
|
||||
return smallValueUSDFormatter.format(value);
|
||||
}
|
||||
return largeValueUSDFormatter.format(value);
|
||||
}
|
||||
|
||||
const smallValueUSDFormatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
maximumFractionDigits: 6,
|
||||
roundingMode: "halfEven",
|
||||
});
|
||||
|
||||
const largeValueUSDFormatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
maximumFractionDigits: 2,
|
||||
roundingMode: "halfEven",
|
||||
});
|
||||
|
||||
const compactValueUSDFormatter = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 2,
|
||||
roundingMode: "halfEven",
|
||||
});
|
||||
|
||||
function formatUsdCompact(value: number): string {
|
||||
return compactValueUSDFormatter.format(value);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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";
|
||||
import { TokenPage } from "./components/token-page";
|
||||
|
||||
const title = "Tokens | thirdweb";
|
||||
const description = "Discover and swap any tokens on any chain, instantly";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
description,
|
||||
openGraph: {
|
||||
description,
|
||||
title,
|
||||
},
|
||||
title,
|
||||
};
|
||||
|
||||
export default async function Page() {
|
||||
const chains = await getBridgeSupportedChains();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<PageHeader />
|
||||
<div className="border-b py-10 ">
|
||||
<div className="container max-w-7xl">
|
||||
<div className="flex mb-4">
|
||||
<div className="rounded-full bg-card p-2.5 border">
|
||||
<BringToFrontIcon className="size-6 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
<TokenPage chains={chains} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const getBridgeSupportedChains = unstable_cache(
|
||||
async () => {
|
||||
const chains = await Bridge.chains({ client: serverThirdwebClient });
|
||||
return chains;
|
||||
},
|
||||
["bridge-supported-chains"],
|
||||
{
|
||||
revalidate: 60 * 60, // 1 hour
|
||||
},
|
||||
);
|
||||
@@ -1,7 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import type React from "react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { reportProductFeedback } from "@/analytics/report";
|
||||
import { NotificationsButton } from "@/components/notifications/notification-button";
|
||||
import { NavLink } from "@/components/ui/NavLink";
|
||||
import type { Account } from "@/hooks/useApi";
|
||||
import { AccountButton } from "./account-button.client";
|
||||
import { ResourcesDropdownButton } from "./ResourcesDropdownButton";
|
||||
@@ -31,6 +37,32 @@ export function SecondaryNav(props: {
|
||||
}
|
||||
|
||||
export function SecondaryNavLinks() {
|
||||
const [showFeedbackDropdown, setShowFeedbackDropdown] = useState(false);
|
||||
const [modalFeedback, setModalFeedback] = useState("");
|
||||
|
||||
const handleModalSubmit = (e?: React.FormEvent) => {
|
||||
e?.preventDefault();
|
||||
|
||||
// Report feedback to PostHog
|
||||
reportProductFeedback({
|
||||
feedback: modalFeedback,
|
||||
source: "desktop",
|
||||
});
|
||||
|
||||
// Show success notification
|
||||
toast.success("Feedback submitted successfully!", {
|
||||
description: "Thank you for your feedback. We'll review it shortly.",
|
||||
});
|
||||
|
||||
setModalFeedback("");
|
||||
setShowFeedbackDropdown(false);
|
||||
};
|
||||
|
||||
const handleModalCancel = () => {
|
||||
setModalFeedback("");
|
||||
setShowFeedbackDropdown(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-6">
|
||||
<ResourcesDropdownButton />
|
||||
@@ -44,14 +76,77 @@ export function SecondaryNavLinks() {
|
||||
Docs
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
className="text-muted-foreground text-sm hover:text-foreground"
|
||||
href="https://feedback.thirdweb.com"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Feedback
|
||||
</Link>
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowFeedbackDropdown(!showFeedbackDropdown)}
|
||||
className="text-muted-foreground text-sm hover:text-foreground border border-border px-3 py-1.5 rounded-full hover:bg-muted transition-colors"
|
||||
>
|
||||
Feedback
|
||||
</button>
|
||||
|
||||
{showFeedbackDropdown && (
|
||||
<div
|
||||
id="feedback-dropdown"
|
||||
role="dialog"
|
||||
aria-labelledby="feedback-heading"
|
||||
className="absolute top-full right-0 mt-2 bg-background border border-border rounded-2xl p-3 w-96 z-50"
|
||||
>
|
||||
<h2
|
||||
id="feedback-heading"
|
||||
className="text-foreground text-base font-sans mb-2"
|
||||
>
|
||||
Share your feedback with us:
|
||||
</h2>
|
||||
<form onSubmit={handleModalSubmit} className="contents">
|
||||
<label htmlFor="feedback-text" className="sr-only">
|
||||
Feedback
|
||||
</label>
|
||||
<textarea
|
||||
id="feedback-text"
|
||||
value={modalFeedback}
|
||||
onChange={(e) => setModalFeedback(e.target.value)}
|
||||
maxLength={1000}
|
||||
aria-describedby="feedback-help"
|
||||
className="w-full bg-background text-foreground rounded-lg p-4 min-h-[120px] resize-none border border-border focus:border-border focus:outline-none placeholder-muted-foreground font-sans mb-4 text-sm"
|
||||
placeholder="Tell us what you think..."
|
||||
/>
|
||||
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="text-muted-foreground text-xs font-sans">
|
||||
<div>Have a technical issue?</div>
|
||||
<div>
|
||||
<NavLink
|
||||
href="/team/~/support"
|
||||
className="underline hover:text-foreground transition-colors"
|
||||
>
|
||||
Contact support
|
||||
</NavLink>
|
||||
.
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 flex-shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleModalCancel}
|
||||
className="bg-transparent text-foreground px-4 py-1.5 rounded-full font-sans text-sm border border-border hover:bg-muted transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!modalFeedback.trim()}
|
||||
aria-disabled={!modalFeedback.trim()}
|
||||
className="bg-primary text-primary-foreground px-4 py-1.5 rounded-full font-sans text-sm hover:bg-primary/90 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronUpIcon,
|
||||
LogOutIcon,
|
||||
MenuIcon,
|
||||
MoonIcon,
|
||||
@@ -12,8 +14,11 @@ import {
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useLayoutEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { ThirdwebClient } from "thirdweb";
|
||||
import { reportProductFeedback } from "@/analytics/report";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { NavLink } from "@/components/ui/NavLink";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { SkeletonContainer } from "@/components/ui/skeleton";
|
||||
import { useEns } from "@/hooks/contract-hooks";
|
||||
@@ -36,6 +41,8 @@ export function MobileBurgerMenuButton(
|
||||
},
|
||||
) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const [showFeedbackSection, setShowFeedbackSection] = useState(false);
|
||||
const [modalFeedback, setModalFeedback] = useState("");
|
||||
const { setTheme, theme } = useTheme();
|
||||
const ensQuery = useEns({
|
||||
addressOrEnsName:
|
||||
@@ -44,6 +51,29 @@ export function MobileBurgerMenuButton(
|
||||
});
|
||||
// const [isCMDSearchModalOpen, setIsCMDSearchModalOpen] = useState(false);
|
||||
|
||||
const handleModalSubmit = (e?: React.FormEvent) => {
|
||||
e?.preventDefault();
|
||||
|
||||
// Report feedback to PostHog
|
||||
reportProductFeedback({
|
||||
feedback: modalFeedback,
|
||||
source: "mobile",
|
||||
});
|
||||
|
||||
// Show success notification
|
||||
toast.success("Feedback submitted successfully!", {
|
||||
description: "Thank you for your feedback. We'll review it shortly.",
|
||||
});
|
||||
|
||||
setModalFeedback("");
|
||||
setShowFeedbackSection(false);
|
||||
};
|
||||
|
||||
const handleModalCancel = () => {
|
||||
setModalFeedback("");
|
||||
setShowFeedbackSection(false);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (isMenuOpen) {
|
||||
document.body.style.overflow = "hidden";
|
||||
@@ -71,7 +101,7 @@ export function MobileBurgerMenuButton(
|
||||
</Button>
|
||||
|
||||
{isMenuOpen && (
|
||||
<div className="fade-in-0 fixed inset-0 z-50 flex animate-in flex-col bg-background p-6 duration-200">
|
||||
<div className="fade-in-0 fixed inset-0 z-50 flex animate-in flex-col bg-background p-6 duration-200 overflow-y-auto">
|
||||
<Button
|
||||
className="!h-auto absolute top-4 right-4 p-1"
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
@@ -191,14 +221,78 @@ export function MobileBurgerMenuButton(
|
||||
Docs
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
href="https://feedback.thirdweb.com"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Feedback
|
||||
</Link>
|
||||
<div className="flex flex-col gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center justify-between text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setShowFeedbackSection(!showFeedbackSection)}
|
||||
>
|
||||
<span>Feedback</span>
|
||||
{showFeedbackSection ? (
|
||||
<ChevronUpIcon className="size-4" />
|
||||
) : (
|
||||
<ChevronDownIcon className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{showFeedbackSection && (
|
||||
<div className="pl-0 pr-4 space-y-4 mb-6">
|
||||
<h3
|
||||
id="mobile-feedback-heading"
|
||||
className="text-sm font-medium text-foreground mb-2"
|
||||
>
|
||||
Share your feedback with us:
|
||||
</h3>
|
||||
<form onSubmit={handleModalSubmit} className="contents">
|
||||
<label htmlFor="mobile-feedback-text" className="sr-only">
|
||||
Feedback
|
||||
</label>
|
||||
<textarea
|
||||
id="mobile-feedback-text"
|
||||
value={modalFeedback}
|
||||
onChange={(e) => setModalFeedback(e.target.value)}
|
||||
maxLength={1000}
|
||||
aria-describedby="mobile-feedback-help"
|
||||
className="w-full bg-background text-foreground rounded-lg p-3 min-h-[100px] resize-none border border-border focus:border-border focus:outline-none placeholder-muted-foreground font-sans text-sm"
|
||||
placeholder="Tell us what you think..."
|
||||
/>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<p
|
||||
id="mobile-feedback-help"
|
||||
className="text-muted-foreground text-xs"
|
||||
>
|
||||
Have a technical issue?{" "}
|
||||
<NavLink
|
||||
href="/team/~/support"
|
||||
className="underline hover:text-foreground transition-colors"
|
||||
>
|
||||
Contact support
|
||||
</NavLink>
|
||||
.
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleModalCancel}
|
||||
className="flex-1 bg-transparent text-foreground px-3 py-2 rounded-full font-sans text-sm border border-border hover:bg-muted transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!modalFeedback.trim()}
|
||||
aria-disabled={!modalFeedback.trim()}
|
||||
className="flex-1 bg-primary text-primary-foreground px-3 py-2 rounded-full font-sans text-sm hover:bg-primary/90 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-6" />
|
||||
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
"use client";
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { type ProjectService, SERVICES } from "@thirdweb-dev/service-utils";
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
import { reportOnboardingCompleted } from "@/analytics/report";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import type { CreateProjectPrefillOptions } from "@/components/project/create-project-modal";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CopyTextButton } from "@/components/ui/CopyTextButton";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Checkbox, CheckboxWithLabel } from "@/components/ui/checkbox";
|
||||
import { DynamicHeight } from "@/components/ui/DynamicHeight";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/Spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { createProjectClient } from "@/hooks/useApi";
|
||||
import { useDashboardRouter } from "@/lib/DashboardRouter";
|
||||
import { projectDomainsSchema, projectNameSchema } from "@/schema/validations";
|
||||
import { toArrFromList } from "@/utils/string";
|
||||
import { createVaultAccountAndAccessToken } from "../../../../../team/[team_slug]/[project_slug]/(sidebar)/transactions/lib/vault.client";
|
||||
|
||||
const ALL_PROJECT_SERVICES = SERVICES.filter(
|
||||
(srv) => srv.name !== "relayer" && srv.name !== "chainsaw",
|
||||
);
|
||||
|
||||
export function CreateProjectFormOnboarding(props: {
|
||||
prefill?: CreateProjectPrefillOptions;
|
||||
enableNebulaServiceByDefault: boolean;
|
||||
teamSlug: string;
|
||||
teamId: string;
|
||||
}) {
|
||||
const [screen, setScreen] = useState<
|
||||
{ id: "create" } | { id: "api-details"; project: Project; secret: string }
|
||||
>({ id: "create" });
|
||||
return (
|
||||
<Card>
|
||||
<DynamicHeight>
|
||||
{screen.id === "create" && (
|
||||
<CreateProjectForm
|
||||
createProject={async (params) => {
|
||||
const res = await createProjectClient(props.teamId, params);
|
||||
await createVaultAccountAndAccessToken({
|
||||
project: res.project,
|
||||
projectSecretKey: res.secret,
|
||||
}).catch((error) => {
|
||||
console.error(
|
||||
"Failed to create vault account and access token",
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
});
|
||||
return {
|
||||
project: res.project,
|
||||
secret: res.secret,
|
||||
};
|
||||
}}
|
||||
enableNebulaServiceByDefault={props.enableNebulaServiceByDefault}
|
||||
onProjectCreated={(params) => {
|
||||
setScreen({
|
||||
id: "api-details",
|
||||
project: params.project,
|
||||
secret: params.secret,
|
||||
});
|
||||
}}
|
||||
prefill={props.prefill}
|
||||
/>
|
||||
)}
|
||||
|
||||
{screen.id === "api-details" && (
|
||||
<CreatedProjectDetails
|
||||
onComplete={() => {
|
||||
setScreen({ id: "create" });
|
||||
}}
|
||||
project={screen.project}
|
||||
secret={screen.secret}
|
||||
teamSlug={props.teamSlug}
|
||||
/>
|
||||
)}
|
||||
</DynamicHeight>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const createProjectFormSchema = z.object({
|
||||
domains: projectDomainsSchema,
|
||||
name: projectNameSchema,
|
||||
});
|
||||
|
||||
type CreateProjectFormSchema = z.infer<typeof createProjectFormSchema>;
|
||||
|
||||
function CreateProjectForm(props: {
|
||||
createProject: (param: Partial<Project>) => Promise<{
|
||||
project: Project;
|
||||
secret: string;
|
||||
}>;
|
||||
prefill?: CreateProjectPrefillOptions;
|
||||
enableNebulaServiceByDefault: boolean;
|
||||
onProjectCreated: (params: { project: Project; secret: string }) => void;
|
||||
}) {
|
||||
const [showAlert, setShowAlert] = useState<"no-domain" | "any-domain">();
|
||||
|
||||
const createProject = useMutation({
|
||||
mutationFn: props.createProject,
|
||||
});
|
||||
|
||||
const form = useForm<CreateProjectFormSchema>({
|
||||
defaultValues: {
|
||||
domains: props.prefill?.domains || "",
|
||||
name: props.prefill?.name || "",
|
||||
},
|
||||
resolver: zodResolver(createProjectFormSchema),
|
||||
});
|
||||
|
||||
function handleAPICreation(values: { name: string; domains: string }) {
|
||||
const servicesToEnableByDefault = props.enableNebulaServiceByDefault
|
||||
? ALL_PROJECT_SERVICES
|
||||
: ALL_PROJECT_SERVICES.filter((srv) => srv.name !== "nebula");
|
||||
|
||||
const formattedValues: Partial<Project> = {
|
||||
domains: toArrFromList(values.domains),
|
||||
name: values.name,
|
||||
// enable all services
|
||||
services: servicesToEnableByDefault.map((srv) => {
|
||||
if (srv.name === "storage") {
|
||||
return {
|
||||
actions: srv.actions.map((sa) => sa.name),
|
||||
name: srv.name,
|
||||
} satisfies ProjectService;
|
||||
}
|
||||
|
||||
if (srv.name === "pay") {
|
||||
return {
|
||||
actions: [],
|
||||
name: "pay",
|
||||
payoutAddress: null,
|
||||
} satisfies ProjectService;
|
||||
}
|
||||
|
||||
return {
|
||||
actions: [],
|
||||
name: srv.name,
|
||||
} satisfies ProjectService;
|
||||
}),
|
||||
};
|
||||
|
||||
createProject.mutate(formattedValues, {
|
||||
onError: () => {
|
||||
toast.error("Failed to create a project");
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
props.onProjectCreated(data);
|
||||
toast.success("Project created successfully");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
if (!values.domains) {
|
||||
setShowAlert("no-domain");
|
||||
} else if (values.domains === "*") {
|
||||
setShowAlert("any-domain");
|
||||
} else {
|
||||
handleAPICreation({
|
||||
domains: values.domains,
|
||||
name: values.name,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (showAlert) {
|
||||
return (
|
||||
<DomainsAlert
|
||||
isCreating={createProject.isPending}
|
||||
onGoBack={() => setShowAlert(undefined)}
|
||||
onProceed={() => {
|
||||
handleAPICreation({
|
||||
domains: form.getValues("domains"),
|
||||
name: form.getValues("name"),
|
||||
});
|
||||
}}
|
||||
type={showAlert}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form autoComplete="off" onSubmit={handleSubmit}>
|
||||
<div className="p-6">
|
||||
<header className="mb-4">
|
||||
<h2 className="text-2xl">Create Project</h2>
|
||||
</header>
|
||||
|
||||
<div className="flex flex-col gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Project Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
className="bg-card"
|
||||
placeholder="My Project"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="relative">
|
||||
<CheckboxWithLabel className="absolute top-0 right-0 text-foreground">
|
||||
<Checkbox
|
||||
checked={form.watch("domains") === "*"}
|
||||
onCheckedChange={(checked) => {
|
||||
form.setValue("domains", checked ? "*" : "", {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
Allow all domains
|
||||
</CheckboxWithLabel>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="domains"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Allowed Domains</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="bg-card"
|
||||
placeholder="thirdweb.com, *.example.com, localhost:3000"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
<div className="pt-1">
|
||||
<FormDescription className="mb-2 text-sm leading-relaxed">
|
||||
Prevent third-parties from using your Client ID by
|
||||
restricting access to allowed domains. Highly
|
||||
recommended for frontend applications.
|
||||
</FormDescription>
|
||||
|
||||
<ul className="flex list-disc flex-col gap-2 pl-3 text-muted-foreground text-sm [&>li]:pl-1 ">
|
||||
<li>
|
||||
Authorize all domains with{" "}
|
||||
<span className="inline-block rounded bg-muted px-2 font-mono text-xs">
|
||||
*
|
||||
</span>
|
||||
<br />
|
||||
<span>
|
||||
Example:{" "}
|
||||
<span className="inline-block rounded bg-muted px-2 font-mono text-xs">
|
||||
*.thirdweb.com
|
||||
</span>{" "}
|
||||
accepts all{" "}
|
||||
<span className="inline-block rounded bg-muted px-2 font-mono text-xs">
|
||||
.thirdweb.com
|
||||
</span>{" "}
|
||||
sites
|
||||
</span>
|
||||
</li>
|
||||
<li>
|
||||
Authorize local URLs with{" "}
|
||||
<span className="inline-block rounded bg-muted px-2 font-mono text-xs">
|
||||
{"localhost:<port>"}
|
||||
</span>
|
||||
</li>
|
||||
<li>Separate domains by commas or new lines</li>
|
||||
</ul>
|
||||
</div>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer className="flex gap-4 border-border border-t p-6 md:gap-2">
|
||||
<Button
|
||||
className="min-w-28 gap-2 ml-auto"
|
||||
disabled={createProject.isPending}
|
||||
type="submit"
|
||||
>
|
||||
{createProject.isPending && <Spinner className="size-4" />}
|
||||
Create Projecct
|
||||
</Button>
|
||||
</footer>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
function DomainsAlert(props: {
|
||||
type: "no-domain" | "any-domain";
|
||||
isCreating: boolean;
|
||||
onProceed: () => void;
|
||||
onGoBack: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-4 p-6">
|
||||
<header>
|
||||
<h2 className="text-2xl">
|
||||
{props.type === "no-domain" && "No Domains Configured"}
|
||||
{props.type === "any-domain" && "Unrestricted Web Access"}
|
||||
</h2>
|
||||
<p>
|
||||
{props.type === "no-domain" &&
|
||||
"This will deny requests from all origins, rendering the key unusable in frontend applications. Proceed only if you intend to use this key in server or native apps environments."}
|
||||
{props.type === "any-domain" &&
|
||||
"Requests from all origins will be authorized. Your key can be used by any website without restriction"}
|
||||
</p>
|
||||
</header>
|
||||
</div>
|
||||
|
||||
<footer className="!justify-between flex gap-4 border-border border-t bg-card p-6">
|
||||
<Button
|
||||
className="min-w-28 gap-2"
|
||||
onClick={props.onGoBack}
|
||||
variant="outline"
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
Update Domains
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
className="min-w-28 gap-2"
|
||||
disabled={props.isCreating}
|
||||
onClick={props.onProceed}
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
{props.isCreating && <Spinner className="size-4" />}
|
||||
Proceed
|
||||
</Button>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CreatedProjectDetails(props: {
|
||||
project: Project;
|
||||
secret: string;
|
||||
onComplete: () => void;
|
||||
teamSlug: string | undefined;
|
||||
}) {
|
||||
const [secretStored, setSecretStored] = useState(false);
|
||||
const router = useDashboardRouter();
|
||||
|
||||
const clientId = props.project.publishableKey;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="p-6">
|
||||
<header>
|
||||
<h2 className="text-2xl">{props.project.name}</h2>
|
||||
</header>
|
||||
|
||||
<div className="h-3" />
|
||||
|
||||
<section>
|
||||
<h3>Client ID</h3>
|
||||
<p className="mb-2 text-muted-foreground text-sm">
|
||||
Identifies your application.
|
||||
</p>
|
||||
|
||||
<CopyTextButton
|
||||
className="!h-auto w-full justify-between truncate bg-card px-3 py-3 font-mono"
|
||||
copyIconPosition="right"
|
||||
textToCopy={clientId}
|
||||
textToShow={clientId}
|
||||
tooltip="Copy Client ID"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div className="h-6" />
|
||||
|
||||
<section>
|
||||
<h3>Secret Key</h3>
|
||||
<p className="mb-2 text-muted-foreground text-sm">
|
||||
Identifies and authenticates your application from a backend.
|
||||
</p>
|
||||
|
||||
<CopyTextButton
|
||||
className="!h-auto w-full justify-between truncate bg-card px-3 py-3 font-mono"
|
||||
copyIconPosition="right"
|
||||
textToCopy={props.secret || ""}
|
||||
textToShow={props.secret || ""}
|
||||
tooltip="Copy Secret Key"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div className="h-3" />
|
||||
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>Do not share or expose your secret key</AlertTitle>
|
||||
<AlertDescription>
|
||||
<div className="mb-5">
|
||||
Secret keys cannot be recovered. If you lose your secret key, you
|
||||
will need to rotate the secret key or create a new Project.
|
||||
</div>
|
||||
<CheckboxWithLabel className="text-foreground">
|
||||
<Checkbox
|
||||
checked={secretStored}
|
||||
onCheckedChange={(v) => {
|
||||
setSecretStored(!!v);
|
||||
}}
|
||||
/>
|
||||
I confirm that I've securely stored my secret key
|
||||
</CheckboxWithLabel>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
|
||||
<footer className="flex border-border border-t bg-card p-6">
|
||||
{props.teamSlug && (
|
||||
<Button
|
||||
className="min-w-28 gap-2 ml-auto"
|
||||
disabled={!secretStored}
|
||||
onClick={() => {
|
||||
reportOnboardingCompleted();
|
||||
router.push(`/team/${props.teamSlug}/${props.project.slug}`);
|
||||
}}
|
||||
>
|
||||
View Project
|
||||
<ArrowRightIcon className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import { getTeamBySlug } from "@/api/team/get-team";
|
||||
import { TeamOnboardingLayout } from "../../../../../login/onboarding/onboarding-layout";
|
||||
import { CreateProjectFormOnboarding } from "./_components/create-project-form";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{ team_slug: string }>;
|
||||
}) {
|
||||
const params = await props.params;
|
||||
const [team, authToken] = await Promise.all([
|
||||
getTeamBySlug(params.team_slug),
|
||||
getAuthToken(),
|
||||
]);
|
||||
|
||||
if (!team || !authToken) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<TeamOnboardingLayout currentStep={4}>
|
||||
<CreateProjectFormOnboarding
|
||||
enableNebulaServiceByDefault={true}
|
||||
teamSlug={team.slug}
|
||||
teamId={team.id}
|
||||
/>
|
||||
</TeamOnboardingLayout>
|
||||
);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
EmbeddedCheckout,
|
||||
EmbeddedCheckoutProvider,
|
||||
} from "@stripe/react-stripe-js";
|
||||
import { loadStripe } from "@stripe/stripe-js";
|
||||
import type { Team } from "@/api/team/get-team";
|
||||
|
||||
const stripePromise = loadStripe(
|
||||
// biome-ignore lint/style/noNonNullAssertion: TODO: fix this later
|
||||
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!,
|
||||
);
|
||||
|
||||
export function GrowthPlanCheckout(props: {
|
||||
team: Team;
|
||||
fetchClientSecret: (team: Team) => Promise<string>;
|
||||
}) {
|
||||
return (
|
||||
<div id="checkout">
|
||||
<EmbeddedCheckoutProvider
|
||||
stripe={stripePromise}
|
||||
options={{
|
||||
fetchClientSecret: () => props.fetchClientSecret(props.team),
|
||||
}}
|
||||
>
|
||||
<EmbeddedCheckout />
|
||||
</EmbeddedCheckoutProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import {
|
||||
fetchClientSecret,
|
||||
getStripeSessionById,
|
||||
} from "@/actions/stripe-actions";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import { getTeamBySlug, type Team } from "@/api/team/get-team";
|
||||
import { getTeamBySlug } from "@/api/team/get-team";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { pollWithTimeout } from "@/utils/pollWithTimeout";
|
||||
import { TeamOnboardingLayout } from "../../../../../login/onboarding/onboarding-layout";
|
||||
import { PlanSelector } from "./_components/plan-selector";
|
||||
import { GrowthPlanCheckout } from "./_components/stripe-checkout";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{ team_slug: string }>;
|
||||
searchParams: Promise<{ session_id?: string }>;
|
||||
}) {
|
||||
const params = await props.params;
|
||||
const [params, searchParams] = await Promise.all([
|
||||
props.params,
|
||||
props.searchParams,
|
||||
]);
|
||||
const [team, authToken] = await Promise.all([
|
||||
getTeamBySlug(params.team_slug),
|
||||
getAuthToken(),
|
||||
@@ -17,18 +27,47 @@ export default async function Page(props: {
|
||||
notFound();
|
||||
}
|
||||
|
||||
async function getTeam() {
|
||||
"use server";
|
||||
const resolvedTeam = await getTeamBySlug(params.team_slug);
|
||||
if (!resolvedTeam) {
|
||||
return team as Team;
|
||||
// IF we have a session id, check if the session was completed successfully
|
||||
let error: string | null = null;
|
||||
if (searchParams.session_id) {
|
||||
const session = await getStripeSessionById(searchParams.session_id);
|
||||
|
||||
switch (session.status) {
|
||||
case "complete": {
|
||||
// poll the team until it shows as "growth" plan (to handle race condition with stripe webhook)
|
||||
await pollWithTimeout({
|
||||
shouldStop: async () => {
|
||||
const refreshedTeam = await getTeamBySlug(team.slug);
|
||||
return refreshedTeam?.billingPlan === "growth";
|
||||
},
|
||||
timeoutMs: 5000,
|
||||
});
|
||||
redirect(`/get-started/team/${team.slug}/add-members`);
|
||||
break;
|
||||
}
|
||||
case "open": {
|
||||
error =
|
||||
"Something went wrong when trying to process your payment method. Please try again.";
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
error = "Please try again later.";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return resolvedTeam;
|
||||
}
|
||||
|
||||
return (
|
||||
<TeamOnboardingLayout currentStep={2}>
|
||||
<PlanSelector getTeam={getTeam} team={team} />
|
||||
<div className="rounded-lg border bg-card overflow-hidden py-4 md:py-8">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>Failed to proces subscription</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<GrowthPlanCheckout team={team} fetchClientSecret={fetchClientSecret} />
|
||||
</div>
|
||||
</TeamOnboardingLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ThemeProvider } from "next-themes";
|
||||
import { NuqsAdapter } from "nuqs/adapters/next/app";
|
||||
import { useEffect, useMemo } from "react";
|
||||
@@ -24,6 +25,9 @@ export function AppRouterProviders(props: {
|
||||
children: React.ReactNode;
|
||||
autoConnect: boolean;
|
||||
}) {
|
||||
// get the current pathname
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<NuqsAdapter>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
@@ -36,6 +40,9 @@ export function AppRouterProviders(props: {
|
||||
defaultTheme="dark"
|
||||
disableTransitionOnChange
|
||||
enableSystem={false}
|
||||
forcedTheme={
|
||||
pathname.startsWith("/get-started") ? "dark" : undefined
|
||||
}
|
||||
>
|
||||
<Toaster richColors />
|
||||
<SanctionedAddressesChecker>
|
||||
|
||||
@@ -103,15 +103,12 @@ export default async function TeamLayout(props: {
|
||||
>
|
||||
{props.children}
|
||||
</TeamSidebarLayout>
|
||||
<div className="fixed right-4 bottom-4 z-50">
|
||||
<CustomChatButton
|
||||
authToken={authToken}
|
||||
clientId={undefined}
|
||||
examplePrompts={siwaExamplePrompts}
|
||||
label="Get Help"
|
||||
team={team}
|
||||
/>
|
||||
</div>
|
||||
<CustomChatButton
|
||||
authToken={authToken}
|
||||
clientId={undefined}
|
||||
examplePrompts={siwaExamplePrompts}
|
||||
team={team}
|
||||
/>
|
||||
</div>
|
||||
</SidebarProvider>
|
||||
);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { getInAppWalletUsage } from "@/api/analytics";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import { getProjects, type Project } from "@/api/project/projects";
|
||||
import { getTeamBySlug } from "@/api/team/get-team";
|
||||
import { DismissibleAlert } from "@/components/blocks/dismissible-alert";
|
||||
import { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { Changelog } from "./_components/Changelog";
|
||||
@@ -63,15 +62,8 @@ export default async function Page(props: {
|
||||
team={team}
|
||||
/>
|
||||
|
||||
{team.billingPlan === "free" ? (
|
||||
{team.billingPlan === "free" && (
|
||||
<FreePlanUpsellBannerUI highlightPlan="growth" teamSlug={team.slug} />
|
||||
) : (
|
||||
<DismissibleAlert
|
||||
preserveState={true}
|
||||
description="Engines, contracts, project settings, and more are now managed within projects. Open or create a project to access them."
|
||||
localStorageId={`${team.id}-engines-alert`}
|
||||
title="Looking for Engines?"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Changelog />
|
||||
|
||||
+97
-68
@@ -34,7 +34,7 @@ interface SupportCaseDetailsProps {
|
||||
team: Team;
|
||||
}
|
||||
|
||||
export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
const [replyMessage, setReplyMessage] = useState("");
|
||||
const [isSubmittingReply, setIsSubmittingReply] = useState(false);
|
||||
const [localMessages, setLocalMessages] = useState(ticket.messages || []);
|
||||
@@ -42,6 +42,15 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
// rating/feedback
|
||||
const [rating, setRating] = useState(0);
|
||||
const [feedback, setFeedback] = useState("");
|
||||
// non-blocking warning when status check fails
|
||||
const [statusCheckFailed, setStatusCheckFailed] = useState(false);
|
||||
|
||||
// Helper function to handle status check errors consistently
|
||||
const handleStatusCheckError = (_error: unknown) => {
|
||||
// Set degraded state for warning banner
|
||||
setStatusCheckFailed(true);
|
||||
return;
|
||||
};
|
||||
|
||||
// Check if feedback has already been submitted for this ticket
|
||||
const feedbackStatusQuery = useQuery({
|
||||
@@ -49,18 +58,25 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
queryFn: async () => {
|
||||
const result = await checkFeedbackStatus(ticket.id);
|
||||
if ("error" in result) {
|
||||
throw new Error(result.error);
|
||||
handleStatusCheckError(result.error);
|
||||
return false; // Non-blocking: allow feedback submission despite status check failure
|
||||
}
|
||||
|
||||
// Clear degraded state on success
|
||||
if (statusCheckFailed) setStatusCheckFailed(false);
|
||||
|
||||
return result.hasFeedback;
|
||||
},
|
||||
enabled: ticket.status === "closed",
|
||||
staleTime: 60_000,
|
||||
gcTime: 5 * 60_000,
|
||||
retry: 1, // Reduce retries since we want non-blocking behavior
|
||||
});
|
||||
|
||||
const feedbackSubmitted = feedbackStatusQuery.data ?? false;
|
||||
const isLoading = feedbackStatusQuery.isLoading;
|
||||
const hasError = feedbackStatusQuery.isError;
|
||||
// query never throws; use local degraded flag for the inline warning
|
||||
const hasError = statusCheckFailed;
|
||||
|
||||
const handleStarClick = (starIndex: number) => {
|
||||
setRating(starIndex + 1);
|
||||
@@ -70,29 +86,36 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
const submitFeedbackMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (rating === 0) {
|
||||
throw new Error("Please select a rating");
|
||||
const error = "Please select a rating";
|
||||
throw new Error(error);
|
||||
}
|
||||
const result = await submitSupportFeedback({
|
||||
rating,
|
||||
feedback,
|
||||
ticketId: ticket.id,
|
||||
});
|
||||
|
||||
if ("error" in result) {
|
||||
// Add more specific error information
|
||||
|
||||
throw new Error(result.error);
|
||||
}
|
||||
|
||||
return result;
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success("Thank you for your feedback!");
|
||||
|
||||
setRating(0);
|
||||
setFeedback("");
|
||||
|
||||
// mark as submitted immediately
|
||||
queryClient.setQueryData(["feedbackStatus", ticket.id], true);
|
||||
},
|
||||
onError: (err) => {
|
||||
console.error("Failed to submit feedback:", err);
|
||||
const msg = err instanceof Error ? err.message : String(err ?? "");
|
||||
let message = "Failed to submit feedback. Please try again.";
|
||||
|
||||
if (/network|fetch/i.test(msg)) {
|
||||
message = "Network error. Please check your connection and try again.";
|
||||
} else if (
|
||||
@@ -102,6 +125,7 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
} else if (/API Server error/i.test(msg)) {
|
||||
message = "Server error. Please try again later.";
|
||||
}
|
||||
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
@@ -157,8 +181,7 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
}
|
||||
|
||||
setReplyMessage("");
|
||||
} catch (error) {
|
||||
console.error("Failed to send reply:", error);
|
||||
} catch {
|
||||
toast.error("Failed to send Message. Please try again.");
|
||||
|
||||
// Remove the optimistic message on error
|
||||
@@ -233,73 +256,77 @@ export function SupportCaseDetails({ ticket, team }: SupportCaseDetailsProps) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ticket.status === "closed" && !isLoading && !feedbackSubmitted && (
|
||||
<div className="border-t p-6">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
This ticket is closed. Give us a quick rating to let us know how
|
||||
we did!
|
||||
</p>
|
||||
{hasError && (
|
||||
<p className="text-destructive text-xs mt-2">
|
||||
Couldn't verify prior feedback right now — you can still submit
|
||||
a rating.
|
||||
{ticket.status === "closed" &&
|
||||
!isLoading &&
|
||||
(!feedbackSubmitted || hasError) && (
|
||||
<div className="border-t p-6">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
This ticket is closed. Give us a quick rating to let us know how
|
||||
we did!
|
||||
</p>
|
||||
)}
|
||||
{hasError && (
|
||||
<div className="mt-2">
|
||||
<p className="text-destructive text-xs">
|
||||
Couldn't verify prior feedback right now — you can still
|
||||
submit a rating.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 mb-6 mt-4">
|
||||
{[1, 2, 3, 4, 5].map((starValue) => (
|
||||
<button
|
||||
key={`star-${starValue}`}
|
||||
<div className="flex gap-2 mb-6 mt-4">
|
||||
{[1, 2, 3, 4, 5].map((starValue) => (
|
||||
<button
|
||||
key={`star-${starValue}`}
|
||||
type="button"
|
||||
onClick={() => handleStarClick(starValue - 1)}
|
||||
className="transition-colors"
|
||||
aria-label={`Rate ${starValue} out of 5 stars`}
|
||||
>
|
||||
<StarIcon
|
||||
size={32}
|
||||
className={cn(
|
||||
"transition-colors",
|
||||
starValue <= rating
|
||||
? "text-pink-500 fill-current stroke-current"
|
||||
: "text-muted-foreground fill-current stroke-current",
|
||||
"hover:text-pink-500",
|
||||
)}
|
||||
strokeWidth={starValue <= rating ? 2 : 1}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<AutoResizeTextarea
|
||||
value={feedback}
|
||||
onChange={(e) => setFeedback(e.target.value)}
|
||||
placeholder="Optional: Tell us how we can improve."
|
||||
maxLength={1000}
|
||||
className="text-sm w-full bg-card text-foreground rounded-lg p-4 pr-28 min-h-[100px] resize-none border border-border focus:outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => handleStarClick(starValue - 1)}
|
||||
className="transition-colors"
|
||||
aria-label={`Rate ${starValue} out of 5 stars`}
|
||||
onClick={handleSendFeedback}
|
||||
disabled={submitFeedbackMutation.isPending || rating === 0}
|
||||
className="absolute bottom-3 right-3 rounded-full h-auto py-2 px-4"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
<StarIcon
|
||||
size={32}
|
||||
className={cn(
|
||||
"transition-colors",
|
||||
starValue <= rating
|
||||
? "text-pink-500 fill-current stroke-current"
|
||||
: "text-muted-foreground fill-current stroke-current",
|
||||
"hover:text-pink-500",
|
||||
)}
|
||||
strokeWidth={starValue <= rating ? 2 : 1}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
{submitFeedbackMutation.isPending ? (
|
||||
<>
|
||||
<Spinner className="size-4 mr-2" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
"Send Feedback"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
<AutoResizeTextarea
|
||||
value={feedback}
|
||||
onChange={(e) => setFeedback(e.target.value)}
|
||||
placeholder="Optional: Tell us how we can improve."
|
||||
maxLength={1000}
|
||||
className="text-sm w-full bg-card text-foreground rounded-lg p-4 pr-28 min-h-[100px] resize-none border border-border focus:outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSendFeedback}
|
||||
disabled={submitFeedbackMutation.isPending || rating === 0}
|
||||
className="absolute bottom-3 right-3 rounded-full h-auto py-2 px-4"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
{submitFeedbackMutation.isPending ? (
|
||||
<>
|
||||
<Spinner className="size-4 mr-2" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
"Send Feedback"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{ticket.status === "closed" && feedbackSubmitted && (
|
||||
{ticket.status === "closed" && feedbackSubmitted && !hasError && (
|
||||
<div className="border-t p-6">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Thank you for your feedback! We appreciate your input and will use
|
||||
@@ -455,3 +482,5 @@ function TicketMessage(props: { message: SupportMessage }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { SupportCaseDetails };
|
||||
|
||||
@@ -13,7 +13,16 @@ export async function submitSupportFeedback({
|
||||
ticketId: string;
|
||||
}): Promise<FeedbackSubmitResult> {
|
||||
try {
|
||||
// Fail fast on missing configuration
|
||||
// Basic input validation first - fail fast on invalid input
|
||||
if (!ticketId?.trim()) {
|
||||
return { error: "ticketId is required." };
|
||||
}
|
||||
|
||||
if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
|
||||
return { error: "Rating must be an integer between 1 and 5." };
|
||||
}
|
||||
|
||||
// Configuration validation after input validation
|
||||
const siwaUrl =
|
||||
process.env.SIWA_URL ?? process.env.NEXT_PUBLIC_SIWA_URL ?? "";
|
||||
|
||||
@@ -27,15 +36,6 @@ export async function submitSupportFeedback({
|
||||
throw new Error("SERVICE_AUTH_KEY_SIWA not configured");
|
||||
}
|
||||
|
||||
// Basic input validation/normalization
|
||||
if (!ticketId?.trim()) {
|
||||
return { error: "ticketId is required." };
|
||||
}
|
||||
|
||||
if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
|
||||
return { error: "Rating must be an integer between 1 and 5." };
|
||||
}
|
||||
|
||||
const normalizedFeedback = (feedback ?? "")
|
||||
.toString()
|
||||
.trim()
|
||||
@@ -49,6 +49,7 @@ export async function submitSupportFeedback({
|
||||
|
||||
const ac = new AbortController();
|
||||
const t = setTimeout(() => ac.abort(), 10_000);
|
||||
|
||||
const response = await fetch(`${siwaUrl}/v1/csat/saveCSATFeedback`, {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
@@ -62,13 +63,33 @@ export async function submitSupportFeedback({
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
return { error: `API Server error: ${response.status} - ${errorText}` };
|
||||
const error = `API Server error: ${response.status} - ${errorText}`;
|
||||
return { error };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
try {
|
||||
const data = await response.json();
|
||||
|
||||
// Validate response structure
|
||||
if (typeof data !== "object" || data === null) {
|
||||
return { error: "Invalid response format from API" };
|
||||
}
|
||||
|
||||
if (!data.success) {
|
||||
return { error: "API returned unsuccessful response" };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (_jsonError) {
|
||||
return { error: "Invalid JSON response from API" };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Feedback submission error:", error);
|
||||
return { error: "Internal server error" };
|
||||
if (error instanceof Error) {
|
||||
if (error.name === "AbortError") return { error: "Request timeout" };
|
||||
if (error instanceof TypeError) return { error: "Network error" };
|
||||
return { error: error.message };
|
||||
}
|
||||
return { error: "Unknown error occurred" };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,12 +97,12 @@ export async function checkFeedbackStatus(
|
||||
ticketId: string,
|
||||
): Promise<FeedbackStatusResult> {
|
||||
try {
|
||||
// Basic input validation
|
||||
// Basic input validation first - fail fast on invalid input
|
||||
if (!ticketId?.trim()) {
|
||||
return { error: "ticketId is required." };
|
||||
}
|
||||
|
||||
// Fail fast on missing configuration
|
||||
// Configuration validation after input validation
|
||||
const siwaUrl =
|
||||
process.env.SIWA_URL ?? process.env.NEXT_PUBLIC_SIWA_URL ?? "";
|
||||
|
||||
@@ -95,29 +116,71 @@ export async function checkFeedbackStatus(
|
||||
throw new Error("SERVICE_AUTH_KEY_SIWA not configured");
|
||||
}
|
||||
|
||||
const fullUrl = `${siwaUrl}/v1/csat/getCSATFeedback?ticket_id=${encodeURIComponent(ticketId)}`;
|
||||
|
||||
const ac = new AbortController();
|
||||
const t = setTimeout(() => ac.abort(), 10_000);
|
||||
const response = await fetch(fullUrl, {
|
||||
method: "GET",
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-service-api-key": apiKey,
|
||||
|
||||
const response = await fetch(
|
||||
`${siwaUrl}/v1/csat/getCSATFeedback?ticket_id=${encodeURIComponent(
|
||||
ticketId.trim(),
|
||||
)}`,
|
||||
{
|
||||
method: "GET",
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-service-api-key": apiKey,
|
||||
},
|
||||
signal: ac.signal,
|
||||
},
|
||||
signal: ac.signal,
|
||||
}).finally(() => clearTimeout(t));
|
||||
).finally(() => clearTimeout(t));
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
return { error: `API Server error: ${response.status} - ${errorText}` };
|
||||
const error = `API Server error: ${response.status} - ${errorText}`;
|
||||
return { error };
|
||||
}
|
||||
|
||||
let data: {
|
||||
has_feedback: boolean;
|
||||
feedback_data: {
|
||||
id: string;
|
||||
rating: number | null;
|
||||
feedback: string | null;
|
||||
ticket_id: string | null;
|
||||
created_at: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch (_jsonError) {
|
||||
return { error: "Invalid JSON response from API" };
|
||||
}
|
||||
|
||||
// Comprehensive validation of the API response structure
|
||||
if (
|
||||
typeof data.has_feedback !== "boolean" ||
|
||||
(data.feedback_data != null &&
|
||||
(typeof data.feedback_data !== "object" ||
|
||||
typeof data.feedback_data.id !== "string" ||
|
||||
(data.feedback_data.rating != null &&
|
||||
typeof data.feedback_data.rating !== "number") ||
|
||||
(data.feedback_data.feedback != null &&
|
||||
typeof data.feedback_data.feedback !== "string") ||
|
||||
(data.feedback_data.ticket_id != null &&
|
||||
typeof data.feedback_data.ticket_id !== "string") ||
|
||||
typeof data.feedback_data.created_at !== "string"))
|
||||
) {
|
||||
return { error: "Invalid response format from API" };
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return { hasFeedback: data.has_feedback };
|
||||
} catch (error) {
|
||||
console.error("Feedback status check error:", error);
|
||||
return { error: "Internal server error" };
|
||||
if (error instanceof Error) {
|
||||
if (error.name === "AbortError") return { error: "Request timeout" };
|
||||
if (error instanceof TypeError) return { error: "Network error" };
|
||||
return { error: error.message };
|
||||
}
|
||||
return { error: "Unknown error occurred" };
|
||||
}
|
||||
}
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { ResponsiveSearchParamsProvider } from "responsive-rsc";
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import { getProject } from "@/api/project/projects";
|
||||
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 { getClientThirdwebClient } from "@/constants/thirdweb-client.client";
|
||||
import { NebulaIcon } from "@/icons/NebulaIcon";
|
||||
import { getFiltersFromSearchParams } from "@/lib/time";
|
||||
import { loginRedirect } from "@/utils/redirects";
|
||||
import { AiAnalytics } from "./chart";
|
||||
import { AiSummary } from "./chart/Summary";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{ team_slug: string; project_slug: string }>;
|
||||
searchParams: Promise<{
|
||||
from?: string;
|
||||
to?: string;
|
||||
type?: string;
|
||||
interval?: string;
|
||||
}>;
|
||||
}) {
|
||||
const [searchParams, params] = await Promise.all([
|
||||
props.searchParams,
|
||||
props.params,
|
||||
]);
|
||||
|
||||
const { team_slug, project_slug } = params;
|
||||
|
||||
const [project, authToken] = await Promise.all([
|
||||
getProject(team_slug, project_slug),
|
||||
getAuthToken(),
|
||||
]);
|
||||
|
||||
if (!authToken) {
|
||||
loginRedirect(`/team/${team_slug}/${project_slug}/ai`);
|
||||
}
|
||||
|
||||
if (!project) {
|
||||
redirect(`/team/${team_slug}`);
|
||||
}
|
||||
|
||||
const client = getClientThirdwebClient({
|
||||
jwt: authToken,
|
||||
teamId: project.teamId,
|
||||
});
|
||||
|
||||
const defaultRange = "last-30" as DurationId;
|
||||
const { range, interval } = getFiltersFromSearchParams({
|
||||
defaultRange,
|
||||
from: searchParams.from,
|
||||
interval: searchParams.interval,
|
||||
to: searchParams.to,
|
||||
});
|
||||
|
||||
return (
|
||||
<ResponsiveSearchParamsProvider value={searchParams}>
|
||||
<ProjectPage
|
||||
header={{
|
||||
icon: NebulaIcon,
|
||||
client,
|
||||
title: "AI Analytics",
|
||||
description: "Track your AI app usage and performance",
|
||||
actions: null,
|
||||
links: [
|
||||
{
|
||||
href: "https://portal.thirdweb.com/ai/chat",
|
||||
type: "docs",
|
||||
},
|
||||
{
|
||||
href: "https://api.thirdweb.com/reference#tag/ai/post/ai/chat",
|
||||
type: "api",
|
||||
},
|
||||
{
|
||||
href: "https://playground.thirdweb.com/ai/chat",
|
||||
type: "playground",
|
||||
},
|
||||
],
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col gap-4 md:gap-6">
|
||||
<ResponsiveTimeFilters defaultRange={defaultRange} />
|
||||
<AiSummary
|
||||
projectId={project.id}
|
||||
teamId={project.teamId}
|
||||
authToken={authToken}
|
||||
range={range}
|
||||
/>
|
||||
|
||||
<AiAnalytics
|
||||
interval={interval}
|
||||
projectId={project.id}
|
||||
range={range}
|
||||
teamId={project.teamId}
|
||||
authToken={authToken}
|
||||
/>
|
||||
</div>
|
||||
</ProjectPage>
|
||||
</ResponsiveSearchParamsProvider>
|
||||
);
|
||||
}
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
import { stream } from "fetch-event-stream";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { NEXT_PUBLIC_THIRDWEB_AI_HOST } from "@/constants/public-envs";
|
||||
import type {
|
||||
NebulaContext,
|
||||
NebulaSwapData,
|
||||
NebulaTxData,
|
||||
NebulaUserMessage,
|
||||
} from "./types";
|
||||
|
||||
export async function promptNebula(params: {
|
||||
message: NebulaUserMessage;
|
||||
sessionId: string;
|
||||
authToken: string;
|
||||
handleStream: (res: ChatStreamedResponse) => void;
|
||||
abortController: AbortController;
|
||||
context: undefined | NebulaContext;
|
||||
project: Project;
|
||||
}) {
|
||||
const body: Record<string, string | boolean | object> = {
|
||||
messages: [params.message],
|
||||
session_id: params.sessionId,
|
||||
stream: true,
|
||||
};
|
||||
|
||||
if (params.context) {
|
||||
body.context = {
|
||||
chain_ids: params.context.chainIds || [],
|
||||
networks: params.context.networks,
|
||||
wallet_address: params.context.walletAddress,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const events = await stream(`${NEXT_PUBLIC_THIRDWEB_AI_HOST}/chat`, {
|
||||
body: JSON.stringify(body),
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.authToken}`,
|
||||
"x-team-id": params.project.teamId,
|
||||
"x-client-id": params.project.publishableKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
signal: params.abortController.signal,
|
||||
});
|
||||
|
||||
for await (const _event of events) {
|
||||
if (!_event.data) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const event = _event as ChatStreamedEvent;
|
||||
|
||||
switch (event.event) {
|
||||
case "delta": {
|
||||
params.handleStream({
|
||||
data: {
|
||||
v: JSON.parse(event.data).v,
|
||||
},
|
||||
event: "delta",
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "presence": {
|
||||
params.handleStream({
|
||||
data: JSON.parse(event.data),
|
||||
event: "presence",
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "image": {
|
||||
const data = JSON.parse(event.data) as {
|
||||
data: {
|
||||
width: number;
|
||||
height: number;
|
||||
url: string;
|
||||
};
|
||||
request_id: string;
|
||||
};
|
||||
|
||||
params.handleStream({
|
||||
data: data.data,
|
||||
event: "image",
|
||||
request_id: data.request_id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "action": {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.type === "sign_transaction") {
|
||||
try {
|
||||
const parsedTxData = data.data as NebulaTxData;
|
||||
params.handleStream({
|
||||
data: parsedTxData,
|
||||
event: "action",
|
||||
request_id: data.request_id,
|
||||
type: "sign_transaction",
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("failed to parse action data", e, { event });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.type === "sign_swap") {
|
||||
try {
|
||||
const swapData = data.data as NebulaSwapData;
|
||||
params.handleStream({
|
||||
data: swapData,
|
||||
event: "action",
|
||||
request_id: data.request_id,
|
||||
type: "sign_swap",
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("failed to parse action data", e, { event });
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
case "error": {
|
||||
const data = JSON.parse(event.data) as {
|
||||
code: number;
|
||||
error: {
|
||||
message: string;
|
||||
};
|
||||
};
|
||||
|
||||
params.handleStream({
|
||||
data: {
|
||||
code: data.code,
|
||||
errorMessage: data.error.message,
|
||||
},
|
||||
event: "error",
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "init": {
|
||||
const data = JSON.parse(event.data);
|
||||
params.handleStream({
|
||||
data: {
|
||||
request_id: data.request_id,
|
||||
session_id: data.session_id,
|
||||
},
|
||||
event: "init",
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "context": {
|
||||
const data = JSON.parse(event.data) as {
|
||||
data: string;
|
||||
request_id: string;
|
||||
session_id: string;
|
||||
};
|
||||
|
||||
const contextData = JSON.parse(data.data) as {
|
||||
wallet_address: string;
|
||||
chain_ids: number[];
|
||||
networks: NebulaContext["networks"];
|
||||
};
|
||||
|
||||
params.handleStream({
|
||||
data: contextData,
|
||||
event: "context",
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "ping": {
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
console.warn("unhandled event", event);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("failed to stream events", error);
|
||||
params.handleStream({
|
||||
data: {
|
||||
code: 500,
|
||||
errorMessage: `Failed to stream events: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
},
|
||||
event: "error",
|
||||
});
|
||||
params.abortController.abort();
|
||||
}
|
||||
}
|
||||
|
||||
type ChatStreamedResponse =
|
||||
| {
|
||||
event: "init";
|
||||
data: {
|
||||
session_id: string;
|
||||
request_id: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
event: "presence";
|
||||
data: {
|
||||
session_id: string;
|
||||
request_id: string;
|
||||
source: "user" | "reviewer" | (string & {});
|
||||
data: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
event: "delta";
|
||||
data: {
|
||||
v: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
event: "action";
|
||||
type: "sign_transaction";
|
||||
data: NebulaTxData;
|
||||
request_id: string;
|
||||
}
|
||||
| {
|
||||
event: "action";
|
||||
type: "sign_swap";
|
||||
data: NebulaSwapData;
|
||||
request_id: string;
|
||||
}
|
||||
| {
|
||||
event: "image";
|
||||
data: {
|
||||
width: number;
|
||||
height: number;
|
||||
url: string;
|
||||
};
|
||||
request_id: string;
|
||||
}
|
||||
| {
|
||||
event: "context";
|
||||
data: {
|
||||
wallet_address: string;
|
||||
chain_ids: number[];
|
||||
networks: NebulaContext["networks"];
|
||||
};
|
||||
}
|
||||
| {
|
||||
event: "error";
|
||||
data: {
|
||||
code: number;
|
||||
errorMessage: string;
|
||||
};
|
||||
};
|
||||
|
||||
type ChatStreamedEvent =
|
||||
| {
|
||||
event: "init";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "presence";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "delta";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "image";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "action";
|
||||
type: "sign_transaction" | "sign_swap";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "context";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "error";
|
||||
data: string;
|
||||
}
|
||||
| {
|
||||
event: "ping";
|
||||
data: string;
|
||||
};
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use server";
|
||||
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { NEXT_PUBLIC_THIRDWEB_AI_HOST } from "@/constants/public-envs";
|
||||
import { fetchWithAuthToken } from "./fetchWithAuthToken";
|
||||
|
||||
export async function submitFeedback(params: {
|
||||
project: Project;
|
||||
sessionId: string;
|
||||
requestId: string;
|
||||
rating: "good" | "bad" | "neutral";
|
||||
}) {
|
||||
const res = await fetchWithAuthToken({
|
||||
body: {
|
||||
feedback_rating:
|
||||
params.rating === "good" ? 1 : params.rating === "bad" ? -1 : 0,
|
||||
request_id: params.requestId,
|
||||
session_id: params.sessionId,
|
||||
},
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/feedback`,
|
||||
method: "POST",
|
||||
project: params.project,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to submit feedback");
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
"use server";
|
||||
|
||||
import { getAuthToken } from "@/api/auth-token";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
|
||||
type FetchWithKeyOptions = {
|
||||
endpoint: string;
|
||||
project: Project;
|
||||
timeout?: number;
|
||||
} & (
|
||||
| {
|
||||
method: "POST" | "PUT";
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
method: "GET" | "DELETE";
|
||||
}
|
||||
);
|
||||
|
||||
export async function fetchWithAuthToken(options: FetchWithKeyOptions) {
|
||||
const timeout = options.timeout || 30000;
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
try {
|
||||
const authToken = await getAuthToken();
|
||||
if (!authToken) {
|
||||
throw new Error("No auth token found");
|
||||
}
|
||||
const response = await fetch(options.endpoint, {
|
||||
body: "body" in options ? JSON.stringify(options.body) : undefined,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
"x-team-id": options.project.teamId,
|
||||
"x-client-id": options.project.publishableKey,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method: options.method,
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 504) {
|
||||
throw new Error("Request timed out. Please try again.");
|
||||
}
|
||||
|
||||
const data = await response.text();
|
||||
throw new Error(`HTTP error! status: ${response.status}: ${data}`);
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
throw new Error("Request timed out. Please try again.");
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
"use server";
|
||||
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { NEXT_PUBLIC_THIRDWEB_AI_HOST } from "@/constants/public-envs";
|
||||
import { fetchWithAuthToken } from "./fetchWithAuthToken";
|
||||
import type {
|
||||
DeletedSessionInfo,
|
||||
NebulaContext,
|
||||
SessionInfo,
|
||||
TruncatedSessionInfo,
|
||||
UpdatedSessionInfo,
|
||||
} from "./types";
|
||||
|
||||
export async function createSession(params: {
|
||||
project: Project;
|
||||
context: NebulaContext | undefined;
|
||||
}) {
|
||||
const body: Record<string, string | boolean | object> = {};
|
||||
|
||||
if (params.context) {
|
||||
body.context = {
|
||||
chain_ids: params.context.chainIds || [],
|
||||
networks: params.context.networks,
|
||||
wallet_address: params.context.walletAddress,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await fetchWithAuthToken({
|
||||
project: params.project,
|
||||
body: body,
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/session`,
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.text();
|
||||
throw new Error(`Failed to create session: ${error}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
|
||||
return data.result as SessionInfo;
|
||||
}
|
||||
|
||||
export async function updateSession(params: {
|
||||
project: Project;
|
||||
sessionId: string;
|
||||
contextFilters: NebulaContext | undefined;
|
||||
}) {
|
||||
const body: Record<string, string | boolean | object> = {};
|
||||
|
||||
if (params.contextFilters) {
|
||||
body.context = {
|
||||
chain_ids: params.contextFilters.chainIds || [],
|
||||
networks: params.contextFilters.networks,
|
||||
wallet_address: params.contextFilters.walletAddress,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await fetchWithAuthToken({
|
||||
body: body,
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/session/${params.sessionId}`,
|
||||
method: "PUT",
|
||||
project: params.project,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to update session");
|
||||
}
|
||||
const data = await res.json();
|
||||
|
||||
return data.result as UpdatedSessionInfo;
|
||||
}
|
||||
|
||||
export async function deleteSession(params: {
|
||||
project: Project;
|
||||
sessionId: string;
|
||||
}) {
|
||||
const res = await fetchWithAuthToken({
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/session/${params.sessionId}`,
|
||||
method: "DELETE",
|
||||
project: params.project,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to update session");
|
||||
}
|
||||
const data = await res.json();
|
||||
|
||||
return data.result as DeletedSessionInfo;
|
||||
}
|
||||
|
||||
export async function getSessions(params: { project: Project }) {
|
||||
const res = await fetchWithAuthToken({
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/session/list`,
|
||||
method: "GET",
|
||||
project: params.project,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to update session");
|
||||
}
|
||||
const data = await res.json();
|
||||
|
||||
return data.result as TruncatedSessionInfo[];
|
||||
}
|
||||
|
||||
export async function getSessionById(params: {
|
||||
project: Project;
|
||||
sessionId: string;
|
||||
}) {
|
||||
const res = await fetchWithAuthToken({
|
||||
endpoint: `${NEXT_PUBLIC_THIRDWEB_AI_HOST}/session/${params.sessionId}`,
|
||||
method: "GET",
|
||||
project: params.project,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error("Failed to update session");
|
||||
}
|
||||
const data = await res.json();
|
||||
|
||||
return data.result as SessionInfo;
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
type SessionContextFilter = {
|
||||
chain_ids: string[] | null;
|
||||
wallet_address: string | null;
|
||||
};
|
||||
|
||||
type NebulaUserMessageContentItem =
|
||||
| {
|
||||
type: "image";
|
||||
image_url: string | null;
|
||||
b64: string | null;
|
||||
}
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
type: "transaction";
|
||||
transaction_hash: string;
|
||||
chain_id: number;
|
||||
};
|
||||
|
||||
export type NebulaUserMessageContent = NebulaUserMessageContentItem[];
|
||||
|
||||
export type NebulaUserMessage = {
|
||||
role: "user";
|
||||
content: NebulaUserMessageContent;
|
||||
};
|
||||
|
||||
export type NebulaSessionHistoryMessage =
|
||||
| {
|
||||
role: "assistant" | "action" | "image";
|
||||
content: string;
|
||||
timestamp: number;
|
||||
}
|
||||
| {
|
||||
role: "user";
|
||||
content: NebulaUserMessageContent | string;
|
||||
};
|
||||
|
||||
export type SessionInfo = {
|
||||
id: string;
|
||||
account_id: string;
|
||||
model_name: string;
|
||||
archive_at: string | null;
|
||||
can_execute: boolean;
|
||||
created_at: string;
|
||||
deleted_at: string | null;
|
||||
history: Array<NebulaSessionHistoryMessage> | null;
|
||||
updated_at: string;
|
||||
archived_at: string | null;
|
||||
title: string | null;
|
||||
is_public: boolean | null;
|
||||
context: SessionContextFilter | null;
|
||||
// memory
|
||||
// action: array<object> | null; <-- type of this is not available on https://nebula-api.thirdweb-dev.com/docs#/default/get_session_session__session_id__get
|
||||
};
|
||||
|
||||
export type UpdatedSessionInfo = {
|
||||
title: string;
|
||||
model_name: string;
|
||||
account_id: string;
|
||||
context: SessionContextFilter | null;
|
||||
};
|
||||
|
||||
export type DeletedSessionInfo = {
|
||||
id: string;
|
||||
deleted_at: string;
|
||||
};
|
||||
|
||||
export type TruncatedSessionInfo = {
|
||||
created_at: string;
|
||||
id: string;
|
||||
updated_at: string;
|
||||
title: string | null;
|
||||
};
|
||||
|
||||
export type NebulaTxData = {
|
||||
chain_id: number;
|
||||
data: `0x${string}`;
|
||||
to: string;
|
||||
value?: string;
|
||||
};
|
||||
|
||||
export type NebulaContext = {
|
||||
chainIds: string[] | null;
|
||||
walletAddress: string | null;
|
||||
networks: "mainnet" | "testnet" | "all" | null;
|
||||
};
|
||||
|
||||
export type NebulaSwapData = {
|
||||
action: string;
|
||||
transaction: {
|
||||
chain_id: number;
|
||||
to: `0x${string}`;
|
||||
data: `0x${string}`;
|
||||
value?: string;
|
||||
};
|
||||
to_token: {
|
||||
address: `0x${string}`;
|
||||
amount: string;
|
||||
chain_id: number;
|
||||
decimals: number;
|
||||
symbol: string;
|
||||
};
|
||||
from_token: {
|
||||
address: `0x${string}`;
|
||||
amount: string;
|
||||
chain_id: number;
|
||||
decimals: number;
|
||||
symbol: string;
|
||||
};
|
||||
intent: {
|
||||
amount: string;
|
||||
destination_chain_id: number;
|
||||
destination_token_address: `0x${string}`;
|
||||
origin_chain_id: number;
|
||||
origin_token_address: `0x${string}`;
|
||||
receiver: `0x${string}`;
|
||||
sender: `0x${string}`;
|
||||
};
|
||||
};
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getAuthToken, getUserThirdwebClient } from "@/api/auth-token";
|
||||
import { getProject } from "@/api/project/projects";
|
||||
import { getSessionById, getSessions } from "../../api/session";
|
||||
import { ChatPageContent } from "../../components/ChatPageContent";
|
||||
import { ChatPageLayout } from "../../components/ChatPageLayout";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{
|
||||
team_slug: string;
|
||||
project_slug: string;
|
||||
session_id: string;
|
||||
}>;
|
||||
}) {
|
||||
const [params] = await Promise.all([props.params]);
|
||||
const [authToken, project] = await Promise.all([
|
||||
getAuthToken(),
|
||||
getProject(params.team_slug, params.project_slug),
|
||||
]);
|
||||
|
||||
if (!authToken) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
if (!project) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const client = await getUserThirdwebClient({ teamId: project.teamId });
|
||||
|
||||
const [session, sessions] = await Promise.all([
|
||||
getSessionById({
|
||||
project: project,
|
||||
sessionId: params.session_id,
|
||||
}).catch(() => undefined),
|
||||
getSessions({
|
||||
project: project,
|
||||
}).catch(() => []),
|
||||
]);
|
||||
|
||||
if (!session) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<ChatPageLayout
|
||||
team_slug={params.team_slug}
|
||||
project={project}
|
||||
authToken={authToken}
|
||||
client={client}
|
||||
accountAddress={""}
|
||||
sessions={sessions}
|
||||
>
|
||||
<ChatPageContent
|
||||
project={project}
|
||||
accountAddress={""}
|
||||
authToken={authToken}
|
||||
client={client}
|
||||
initialParams={undefined}
|
||||
session={session}
|
||||
type="new-chat"
|
||||
/>
|
||||
</ChatPageLayout>
|
||||
);
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { subDays } from "date-fns";
|
||||
import { ThirdwebProvider } from "thirdweb/react";
|
||||
import { projectStub, randomLorem } from "@/storybook/stubs";
|
||||
import { storybookThirdwebClient } from "@/storybook/utils";
|
||||
import { ChatPageLayout } from "../../components/ChatPageLayout";
|
||||
import { ChatHistoryPageUI } from "./ChatHistoryPage";
|
||||
|
||||
const meta = {
|
||||
component: Variant,
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<ThirdwebProvider>
|
||||
<Story />
|
||||
</ThirdwebProvider>
|
||||
),
|
||||
],
|
||||
parameters: {
|
||||
nextjs: {
|
||||
appDirectory: true,
|
||||
},
|
||||
},
|
||||
title: "AI/history",
|
||||
} satisfies Meta<typeof Variant>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const TenChats: Story = {
|
||||
args: {
|
||||
length: 10,
|
||||
},
|
||||
};
|
||||
|
||||
export const ZeroChats: Story = {
|
||||
args: {
|
||||
length: 0,
|
||||
},
|
||||
};
|
||||
|
||||
export const OneChat: Story = {
|
||||
args: {
|
||||
length: 1,
|
||||
},
|
||||
};
|
||||
|
||||
export const PrefillSearch: Story = {
|
||||
args: {
|
||||
length: 10,
|
||||
prefillSearch: "xxxxxxxxxxxx",
|
||||
},
|
||||
};
|
||||
|
||||
function createRandomSessions(length: number) {
|
||||
const sessions = [];
|
||||
for (let i = 0; i < length; i++) {
|
||||
sessions.push({
|
||||
created_at: new Date().toISOString(),
|
||||
id: Math.random().toString(),
|
||||
title: randomLorem(Math.floor(5 + Math.random() * 15)),
|
||||
updated_at: subDays(
|
||||
new Date(),
|
||||
Math.floor(Math.random() * 10),
|
||||
).toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
function Variant(props: { length: number; prefillSearch?: string }) {
|
||||
return (
|
||||
<ChatPageLayout
|
||||
accountAddress="0x1234567890"
|
||||
authToken="xxxxxxxx"
|
||||
sessions={createRandomSessions(props.length)}
|
||||
project={projectStub("xxxxx", "team-1")}
|
||||
client={storybookThirdwebClient}
|
||||
team_slug="team-1"
|
||||
>
|
||||
<ChatHistoryPageUI
|
||||
deleteSession={async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}}
|
||||
prefillSearch={props.prefillSearch}
|
||||
sessions={createRandomSessions(props.length)}
|
||||
team_slug="team-1"
|
||||
project={projectStub("xxxxx", "team-1")}
|
||||
/>
|
||||
</ChatPageLayout>
|
||||
);
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { ScrollShadow } from "@workspace/ui/components/scroll-shadow";
|
||||
import { Spinner } from "@workspace/ui/components/spinner";
|
||||
import { formatDistance } from "date-fns";
|
||||
import Fuse from "fuse.js";
|
||||
import {
|
||||
EllipsisIcon,
|
||||
MessageCircleIcon,
|
||||
SearchIcon,
|
||||
TrashIcon,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { Project } from "@/api/project/projects";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { deleteSession } from "../../api/session";
|
||||
import type { TruncatedSessionInfo } from "../../api/types";
|
||||
import { useSessionsWithLocalOverrides } from "../../hooks/useSessionsWithLocalOverrides";
|
||||
import { deletedSessionsStore } from "../../stores";
|
||||
|
||||
export function ChatHistoryPage(props: {
|
||||
sessions: TruncatedSessionInfo[];
|
||||
prefillSearch?: string;
|
||||
team_slug: string;
|
||||
project: Project;
|
||||
}) {
|
||||
return (
|
||||
<ChatHistoryPageUI
|
||||
{...props}
|
||||
deleteSession={async (s) => {
|
||||
await deleteSession({
|
||||
project: props.project,
|
||||
sessionId: s,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatHistoryPageUI(props: {
|
||||
sessions: TruncatedSessionInfo[];
|
||||
prefillSearch?: string;
|
||||
deleteSession: (sessionId: string) => Promise<void>;
|
||||
team_slug: string;
|
||||
project: Project;
|
||||
}) {
|
||||
const [searchVal, setSearchVal] = useState(props.prefillSearch ?? "");
|
||||
const allSessions = useSessionsWithLocalOverrides(props.sessions);
|
||||
|
||||
const fuse = useMemo(() => {
|
||||
return new Fuse(allSessions, {
|
||||
keys: [
|
||||
{
|
||||
name: "title",
|
||||
weight: 1,
|
||||
},
|
||||
],
|
||||
threshold: 0.5,
|
||||
});
|
||||
}, [allSessions]);
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
if (!searchVal) {
|
||||
return allSessions;
|
||||
}
|
||||
|
||||
return fuse.search(searchVal).map((e) => e.item);
|
||||
}, [allSessions, searchVal, fuse]);
|
||||
return (
|
||||
<div className="flex grow flex-col overflow-hidden">
|
||||
<header className="border-b py-4">
|
||||
<h1 className="px-6 font-semibold text-lg tracking-tight">All Chats</h1>
|
||||
</header>
|
||||
<SearchInput
|
||||
onValueChange={setSearchVal}
|
||||
placeholder="Search for a chat"
|
||||
value={searchVal}
|
||||
/>
|
||||
|
||||
{filteredSessions.length > 0 && (
|
||||
<ScrollShadow
|
||||
className="flex-1"
|
||||
scrollableClassName="max-h-full py-6"
|
||||
shadowClassName="z-10"
|
||||
shadowColor="hsl(var(--background))"
|
||||
>
|
||||
{filteredSessions.length > 0 && (
|
||||
<div className="container flex max-w-[800px] flex-col gap-5">
|
||||
{filteredSessions.map((session) => (
|
||||
<SessionCard
|
||||
project={props.project}
|
||||
team_slug={props.team_slug}
|
||||
deleteSession={props.deleteSession}
|
||||
key={session.id + session.updated_at + session.created_at}
|
||||
session={session}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollShadow>
|
||||
)}
|
||||
|
||||
{/* No Search Results */}
|
||||
{allSessions.length > 0 && filteredSessions.length === 0 && (
|
||||
<div className="flex grow flex-col justify-center rounded-lg">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="rounded-xl border bg-card p-2">
|
||||
<MessageCircleIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="h-4" />
|
||||
<h3 className="text-center"> No Chats Found </h3>
|
||||
<div className="h-1" />
|
||||
<p className="text-center text-muted-foreground text-sm">
|
||||
Try a different search term
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* No Chats at all */}
|
||||
{allSessions.length === 0 && (
|
||||
<div className="flex grow flex-col justify-center">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="rounded-xl border bg-card p-2">
|
||||
<MessageCircleIcon className="size-5 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="h-4" />
|
||||
<h3 className="text-center"> No Chats Created </h3>
|
||||
<div className="h-1" />
|
||||
<p className="text-center text-muted-foreground text-sm">
|
||||
Start a new chat to get started.
|
||||
</p>
|
||||
<div className="h-5" />
|
||||
<Button asChild size="sm">
|
||||
<Link href={`/team/${props.team_slug}/${props.project.slug}/ai`}>
|
||||
New Chat
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SearchInput(props: {
|
||||
placeholder: string;
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<Input
|
||||
className="!border-b h-auto rounded-none border-0 px-6 py-4 pl-11 focus-visible:ring-0 focus-visible:ring-offset-0"
|
||||
onChange={(e) => props.onValueChange(e.target.value)}
|
||||
placeholder={props.placeholder}
|
||||
value={props.value}
|
||||
/>
|
||||
<SearchIcon className="-translate-y-1/2 absolute top-1/2 left-5 size-4 text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO - add delete chat confirmation dialog
|
||||
|
||||
function SessionCard(props: {
|
||||
session: TruncatedSessionInfo;
|
||||
project: Project;
|
||||
team_slug: string;
|
||||
deleteSession: (sessionId: string) => Promise<void>;
|
||||
}) {
|
||||
const deleteChat = useMutation({
|
||||
mutationFn: () => {
|
||||
return props.deleteSession(props.session.id);
|
||||
},
|
||||
onSuccess: () => {
|
||||
const prev = deletedSessionsStore.getValue();
|
||||
deletedSessionsStore.setValue([...prev, props.session.id]);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="relative overflow-hidden rounded-lg border bg-card p-4">
|
||||
<h3 className="line-clamp-3 break-all">
|
||||
<Link
|
||||
className="before:absolute before:inset-0"
|
||||
href={`/team/${props.team_slug}/${props.project.slug}/ai/chat/${props.session.id}`}
|
||||
prefetch={false}
|
||||
>
|
||||
{props.session.title || "Untitled"}
|
||||
</Link>
|
||||
</h3>
|
||||
<div className="mt-4 flex items-center justify-between gap-6 border-t pt-3">
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Updated{" "}
|
||||
{formatDistance(new Date(props.session.updated_at), new Date(), {
|
||||
addSuffix: true,
|
||||
})}
|
||||
</p>
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
className="relative z-10 h-auto w-auto p-1.5"
|
||||
variant="ghost"
|
||||
>
|
||||
<EllipsisIcon className="size-4 text-muted-foreground" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="end" className="w-44 p-1" side="top">
|
||||
<Button
|
||||
className="!text-destructive-text flex w-full justify-start gap-2.5 px-2"
|
||||
onClick={() => {
|
||||
const promise = deleteChat.mutateAsync();
|
||||
toast.promise(promise, {
|
||||
error: "Failed to delete chat",
|
||||
success: "Chat deleted successfully",
|
||||
});
|
||||
}}
|
||||
variant="ghost"
|
||||
>
|
||||
{deleteChat.isPending ? (
|
||||
<Spinner className="size-4" />
|
||||
) : (
|
||||
<TrashIcon className="size-4" />
|
||||
)}
|
||||
Delete
|
||||
</Button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { getProject } from "@/api/project/projects";
|
||||
import { getSessions } from "../../api/session";
|
||||
import { ChatHistoryPage } from "./ChatHistoryPage";
|
||||
|
||||
export default async function Page(props: {
|
||||
params: Promise<{ team_slug: string; project_slug: string }>;
|
||||
}) {
|
||||
const [params] = await Promise.all([props.params]);
|
||||
|
||||
const project = await getProject(params.team_slug, params.project_slug);
|
||||
|
||||
if (!project) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const sessions = await getSessions({ project }).catch(() => []);
|
||||
return (
|
||||
<ChatHistoryPage
|
||||
sessions={sessions}
|
||||
project={project}
|
||||
team_slug={params.team_slug}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { storybookThirdwebClient } from "@/storybook/utils";
|
||||
import { type AssetBalance, AssetsSectionUI } from "./AssetsSection";
|
||||
|
||||
const meta = {
|
||||
component: AssetsSectionUI,
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div className="mx-auto h-dvh w-full max-w-[300px] bg-card p-2">
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
title: "AI/AssetsSection",
|
||||
} satisfies Meta<typeof AssetsSectionUI>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
const tokensStub: AssetBalance[] = [
|
||||
{
|
||||
balance: "10000000000000000000000",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "Broge",
|
||||
symbol: "BROGE",
|
||||
token_address: "0xe8e55a847bb446d967ef92f4580162fb8f2d3f38",
|
||||
},
|
||||
{
|
||||
balance: "2",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "clBTC",
|
||||
symbol: "clBTC",
|
||||
token_address: "0x8d2757ea27aabf172da4cca4e5474c76016e3dc5",
|
||||
},
|
||||
{
|
||||
balance: "1000000000000000000",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "BASED USA",
|
||||
symbol: "USA",
|
||||
token_address: "0xb56d0839998fd79efcd15c27cf966250aa58d6d3",
|
||||
},
|
||||
{
|
||||
balance: "48888800000000000000",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "BearPaw",
|
||||
symbol: "PAW",
|
||||
token_address: "0x600c9b69a65fb6d2551623a53ddef17b050233cd",
|
||||
},
|
||||
{
|
||||
balance: "69000000000000000000",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "Degen Point Of View",
|
||||
symbol: "POV",
|
||||
token_address: "0x4c96a67b0577358894407af7bc3158fc1dffbeb5",
|
||||
},
|
||||
{
|
||||
balance: "6237535850425",
|
||||
chain_id: 8453,
|
||||
decimals: 18,
|
||||
name: "Wrapped Ether",
|
||||
symbol: "WETH",
|
||||
token_address: "0x4200000000000000000000000000000000000006",
|
||||
},
|
||||
];
|
||||
|
||||
export const MultipleAssets: Story = {
|
||||
args: {
|
||||
client: storybookThirdwebClient,
|
||||
data: tokensStub,
|
||||
isPending: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const SingleAsset: Story = {
|
||||
args: {
|
||||
client: storybookThirdwebClient,
|
||||
data: tokensStub.slice(0, 1),
|
||||
isPending: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const EmptyAssets: Story = {
|
||||
args: {
|
||||
client: storybookThirdwebClient,
|
||||
data: [],
|
||||
isPending: false,
|
||||
},
|
||||
};
|
||||
|
||||
export const Loading: Story = {
|
||||
args: {
|
||||
client: storybookThirdwebClient,
|
||||
data: [],
|
||||
isPending: true,
|
||||
},
|
||||
};
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
"use client";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
defineChain,
|
||||
getAddress,
|
||||
NATIVE_TOKEN_ADDRESS,
|
||||
type ThirdwebClient,
|
||||
toTokens,
|
||||
} from "thirdweb";
|
||||
import {
|
||||
Blobbie,
|
||||
TokenIcon,
|
||||
TokenProvider,
|
||||
useActiveAccount,
|
||||
useActiveWalletChain,
|
||||
} from "thirdweb/react";
|
||||
import { getWalletBalance } from "thirdweb/wallets";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { isProd } from "@/constants/env-utils";
|
||||
import { useAllChainsData } from "@/hooks/chains/allChains";
|
||||
import { useV5DashboardChain } from "@/hooks/chains/v5-adapter";
|
||||
import { ChainIconClient } from "@/icons/ChainIcon";
|
||||
|
||||
export type AssetBalance = {
|
||||
chain_id: number;
|
||||
token_address: string;
|
||||
balance: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
|
||||
export function AssetsSectionUI(props: {
|
||||
data: AssetBalance[];
|
||||
isPending: boolean;
|
||||
client: ThirdwebClient;
|
||||
}) {
|
||||
if (props.data.length === 0 && !props.isPending) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 px-2 py-1">
|
||||
<div className="rounded-full border p-1">
|
||||
<XIcon className="size-4" />
|
||||
</div>
|
||||
<div className="text-muted-foreground text-sm">No Assets </div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{!props.isPending &&
|
||||
props.data.map((asset) => (
|
||||
<AssetItem
|
||||
asset={asset}
|
||||
client={props.client}
|
||||
key={`${asset.chain_id}-${asset.token_address}`}
|
||||
/>
|
||||
))}
|
||||
|
||||
{props.isPending &&
|
||||
new Array(10).fill(null).map((_, index) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: for the placeholder this is explicitly the key
|
||||
<SkeletonAssetItem key={index} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SkeletonAssetItem() {
|
||||
return (
|
||||
<div className="flex h-[48px] items-center gap-2 px-2 py-1">
|
||||
<Skeleton className="size-8 rounded-full" />
|
||||
<div className="flex flex-col gap-1">
|
||||
<Skeleton className="h-3 w-32 bg-muted" />
|
||||
<Skeleton className="h-3 w-24 bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetItem(props: { asset: AssetBalance; client: ThirdwebClient }) {
|
||||
const { idToChain } = useAllChainsData();
|
||||
const chainMeta = idToChain.get(props.asset.chain_id);
|
||||
const isNativeToken = props.asset.token_address === NATIVE_TOKEN_ADDRESS;
|
||||
const chain = useV5DashboardChain(props.asset.chain_id);
|
||||
|
||||
return (
|
||||
<TokenProvider
|
||||
address={props.asset.token_address}
|
||||
chain={chain}
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
client={props.client}
|
||||
>
|
||||
<div className="relative flex h-[48px] items-center gap-2.5 rounded-lg px-2 py-1 hover:bg-accent">
|
||||
<div className="relative">
|
||||
<TokenIcon
|
||||
className="size-8 rounded-full border"
|
||||
fallbackComponent={
|
||||
<Blobbie
|
||||
address={props.asset.token_address}
|
||||
className="size-8 rounded-full"
|
||||
/>
|
||||
}
|
||||
loadingComponent={
|
||||
<Blobbie
|
||||
address={props.asset.token_address}
|
||||
className="size-8 rounded-full"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{!isNativeToken && (
|
||||
<div className="-right-0.5 -bottom-0.5 absolute rounded-full border bg-background p-0.5">
|
||||
<ChainIconClient
|
||||
className="size-3.5"
|
||||
client={props.client}
|
||||
src={chainMeta?.icon?.url || ""}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-col text-sm">
|
||||
<Link
|
||||
className="truncate font-medium before:absolute before:inset-0"
|
||||
href={
|
||||
isNativeToken
|
||||
? `https://thirdweb.com/${props.asset.chain_id}`
|
||||
: `https://thirdweb.com/${props.asset.chain_id}/${props.asset.token_address}`
|
||||
}
|
||||
target="_blank"
|
||||
>
|
||||
{props.asset.name}
|
||||
</Link>
|
||||
|
||||
<p className="truncate text-muted-foreground text-sm">
|
||||
{`${toTokens(BigInt(props.asset.balance), props.asset.decimals)} ${props.asset.symbol}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</TokenProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function AssetsSection(props: { client: ThirdwebClient }) {
|
||||
const account = useActiveAccount();
|
||||
const activeChain = useActiveWalletChain();
|
||||
|
||||
const assetsQuery = useQuery({
|
||||
enabled: !!account && !!activeChain,
|
||||
queryFn: async () => {
|
||||
if (!account || !activeChain) {
|
||||
return [];
|
||||
}
|
||||
const chains = [...new Set([1, 8453, 10, 137, activeChain.id])];
|
||||
const url = new URL(
|
||||
`https://insight.${isProd ? "thirdweb" : "thirdweb-dev"}.com/v1/tokens/erc20/${account?.address}`,
|
||||
);
|
||||
url.searchParams.set("limit", "50");
|
||||
url.searchParams.set("metadata", "true");
|
||||
url.searchParams.set("include_spam", "false");
|
||||
url.searchParams.set("clientId", props.client.clientId);
|
||||
for (const chain of chains) {
|
||||
url.searchParams.append("chain", chain.toString());
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
const json = (await response.json()) as {
|
||||
data: AssetBalance[];
|
||||
};
|
||||
|
||||
const tokensToShowOnTop = new Set(
|
||||
[
|
||||
// base
|
||||
"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", // usdc,
|
||||
"0x0555E30da8f98308EdB960aa94C0Db47230d2B9c", // wbtc
|
||||
"0x4200000000000000000000000000000000000006", // wrapped eth
|
||||
// ethereum
|
||||
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // usdc
|
||||
"0xdac17f958d2ee523a2206206994597c13d831ec7", // usdt
|
||||
"0xB8c77482e45F1F44dE1745F52C74426C631bDD52", // bnb
|
||||
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // weth
|
||||
"0x2260fac5e5542a773aa44fbcfedf7c193bc2c599", // wbtc
|
||||
// optimism
|
||||
"0x4200000000000000000000000000000000000042", // op token
|
||||
"0xdc6ff44d5d932cbd77b52e5612ba0529dc6226f1", // world coin
|
||||
"0x94b008aa00579c1307b0ef2c499ad98a8ce58e58", // usdt
|
||||
"0x0b2c639c533813f4aa9d7837caf62653d097ff85", // usdc
|
||||
"0x4200000000000000000000000000000000000006", // wrapped eth
|
||||
// polygon
|
||||
"0x7ceb23fd6bc0add59e62ac25578270cff1b9f619", // weth
|
||||
"0xc2132d05d31c914a87c6611c10748aeb04b58e8f", // usdt
|
||||
"0x3BA4c387f786bFEE076A58914F5Bd38d668B42c3", // bnb
|
||||
"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", // usdc
|
||||
"0x2791bca1f2de4661ed88a30c99a7a9449aa84174", // usdc.e
|
||||
].map((x) => getAddress(x)),
|
||||
);
|
||||
|
||||
return json.data.sort((a, b) => {
|
||||
if (tokensToShowOnTop.has(getAddress(a.token_address))) {
|
||||
return -1;
|
||||
}
|
||||
if (tokensToShowOnTop.has(getAddress(b.token_address))) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
},
|
||||
queryKey: ["v1/tokens/erc20", account?.address, activeChain?.id],
|
||||
});
|
||||
|
||||
const nativeBalances = useQuery({
|
||||
queryFn: async () => {
|
||||
if (!account || !activeChain) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const chains = [...new Set([1, 8453, 10, 137, activeChain.id])];
|
||||
|
||||
const result = await Promise.allSettled(
|
||||
chains.map((chain) =>
|
||||
getWalletBalance({
|
||||
address: account.address,
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
chain: defineChain(chain),
|
||||
client: props.client,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return result
|
||||
.filter((r) => r.status === "fulfilled")
|
||||
.map((r) => ({
|
||||
balance: r.value.value.toString(),
|
||||
chain_id: r.value.chainId,
|
||||
decimals: r.value.decimals,
|
||||
name: r.value.name,
|
||||
symbol: r.value.symbol,
|
||||
token_address: r.value.tokenAddress,
|
||||
}))
|
||||
.filter((x) => x.balance !== "0") as AssetBalance[];
|
||||
},
|
||||
queryKey: ["getWalletBalance", account?.address, activeChain?.id],
|
||||
});
|
||||
|
||||
const isPending = assetsQuery.isPending || nativeBalances.isPending;
|
||||
|
||||
const data = [...(nativeBalances.data ?? []), ...(assetsQuery.data ?? [])];
|
||||
|
||||
return (
|
||||
<AssetsSectionUI client={props.client} data={data} isPending={isPending} />
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user