撤除终端内联支付:订阅按钮统一跳转 /account
删除 useTerminalPay.ts、billing-utils.ts,SubscriptionGate 恢复为 <Link href=/account>,全站支付入口统一到账户页。
This commit is contained in:
@@ -239,8 +239,14 @@ export function LoginClient({ nextPath, initialMode }: LoginClientProps) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full flex-col lg:flex-row bg-[#f8fafc] font-sans text-slate-900">
|
||||
{/* Left Dark Column */}
|
||||
<div className="relative flex flex-col justify-between bg-[#11161d] p-8 text-white lg:w-[480px] xl:w-[540px] shrink-0">
|
||||
<div className="flex flex-col gap-12">
|
||||
<div className="relative flex flex-col justify-between bg-[#0b0f19] p-8 text-white lg:w-[480px] xl:w-[540px] shrink-0 overflow-hidden border-r border-white/5">
|
||||
{/* Ambient Glows */}
|
||||
<div className="absolute -left-20 -top-20 h-80 w-80 rounded-full bg-blue-600/15 blur-[100px] pointer-events-none" />
|
||||
<div className="absolute right-0 bottom-0 h-[300px] w-[300px] rounded-full bg-indigo-500/10 blur-[120px] pointer-events-none" />
|
||||
{/* Grid overlay */}
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,#ffffff03_1px,transparent_1px),linear-gradient(to_bottom,#ffffff03_1px,transparent_1px)] bg-[size:24px_24px] pointer-events-none" />
|
||||
|
||||
<div className="relative z-10 flex flex-col gap-12">
|
||||
<Link href="/" className="flex items-center hover:opacity-90">
|
||||
<img src="/logo.png" alt="PolyWeather" className="h-8 w-auto object-contain" />
|
||||
</Link>
|
||||
@@ -269,31 +275,48 @@ export function LoginClient({ nextPath, initialMode }: LoginClientProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-12 space-y-8">
|
||||
<div className="space-y-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wider text-slate-500">
|
||||
{copy.trusted}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-3 max-w-sm">
|
||||
{[
|
||||
"Atmos Capital",
|
||||
"Celerity Risk",
|
||||
"Metis Trading",
|
||||
"Aviation Hedge",
|
||||
].map((name) => (
|
||||
<div
|
||||
key={name}
|
||||
className="flex h-9 items-center justify-center rounded border border-white/10 bg-white/5 text-xs font-medium text-slate-400"
|
||||
>
|
||||
{name}
|
||||
</div>
|
||||
))}
|
||||
{/* Sleek Terminal Preview Widget */}
|
||||
<div className="relative z-10 my-8 rounded-xl border border-white/10 bg-white/[0.02] p-5 backdrop-blur-md shadow-2xl max-w-sm">
|
||||
<div className="flex items-center justify-between border-b border-white/10 pb-3 mb-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-emerald-500 animate-pulse" />
|
||||
<span className="font-mono text-[10px] uppercase tracking-wider text-slate-400">
|
||||
{isEn ? "Runway 02L Settlement" : "跑道 02L 官方结算"}
|
||||
</span>
|
||||
</div>
|
||||
<span className="font-mono text-[9px] font-black text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded border border-emerald-500/20">LIVE</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 font-mono text-[11px]">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-400">{isEn ? "Current Temp:" : "当前气温:"}</span>
|
||||
<span className="font-bold text-white">28.8°C</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-400">{isEn ? "UMA Threshold:" : "UMA 结算阈值:"}</span>
|
||||
<span className="font-bold text-rose-400">30.0°C</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-400">{isEn ? "Model Probability:" : "模型预测概率:"}</span>
|
||||
<span className="font-bold text-blue-400">88.5%</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-slate-400">{isEn ? "Market Price:" : "市场买卖价差:"}</span>
|
||||
<span className="font-bold text-white">$10.00</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||
<span className="text-yellow-500">⭐⭐⭐⭐⭐</span>
|
||||
<span>4.9 out of 5 stars (G2 rating)</span>
|
||||
{/* Sparkline visualization */}
|
||||
<div className="mt-4 pt-3 border-t border-white/5">
|
||||
<div className="flex items-end justify-between gap-1.5 h-12">
|
||||
{[30, 45, 38, 52, 68, 85, 78, 92, 88].map((h, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex-1 rounded-t bg-gradient-to-t from-blue-600/30 to-blue-500/90 transition-all duration-300"
|
||||
style={{ height: `${h}%` }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -936,47 +936,6 @@ function ScanTerminalScreen() {
|
||||
);
|
||||
const generatedText = useRelativeTime(terminalData?.generated_at ?? null);
|
||||
|
||||
const refreshAuth = useCallback(() => {
|
||||
fetch("/api/auth/me", {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.json() as Promise<{
|
||||
authenticated?: boolean;
|
||||
user_id?: string | null;
|
||||
subscription_active?: boolean | null;
|
||||
subscription_plan_code?: string | null;
|
||||
subscription_expires_at?: string | null;
|
||||
subscription_total_expires_at?: string | null;
|
||||
subscription_queued_days?: number | null;
|
||||
points?: number | null;
|
||||
}>;
|
||||
})
|
||||
.then((payload) => {
|
||||
setProAccess({
|
||||
loading: false,
|
||||
authenticated: Boolean(payload.authenticated),
|
||||
userId: payload.user_id ?? null,
|
||||
subscriptionActive: payload.subscription_active === true,
|
||||
subscriptionPlanCode: payload.subscription_plan_code ?? null,
|
||||
subscriptionExpiresAt: payload.subscription_expires_at ?? null,
|
||||
subscriptionTotalExpiresAt:
|
||||
payload.subscription_total_expires_at ??
|
||||
payload.subscription_expires_at ??
|
||||
null,
|
||||
subscriptionQueuedDays: Math.max(
|
||||
0,
|
||||
Number(payload.subscription_queued_days ?? 0),
|
||||
),
|
||||
points: Number(payload.points ?? 0),
|
||||
error: null,
|
||||
});
|
||||
})
|
||||
.catch(() => {}); // keep current state on error
|
||||
}, []);
|
||||
|
||||
if (!hydrated || (proAccess.loading && !canUseLocalFullAccess)) {
|
||||
return (
|
||||
<ScanTerminalLoadingScreen
|
||||
@@ -993,8 +952,6 @@ function ScanTerminalScreen() {
|
||||
<ProductAccessRequired
|
||||
isAuthenticated={isAuthenticated}
|
||||
isEn={isEn}
|
||||
points={proAccess.points}
|
||||
onPaid={refreshAuth}
|
||||
userLocalTime={userLocalTime}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { LockKeyhole, CreditCard, LogIn } from "lucide-react";
|
||||
import { UnlockProOverlay } from "@/components/subscription/UnlockProOverlay";
|
||||
import { useTerminalPay } from "@/components/subscription/useTerminalPay";
|
||||
|
||||
const ACCESS_TERM = {
|
||||
signInToContinue: { en: "Sign in to continue", zh: "请先登录" },
|
||||
@@ -19,42 +16,7 @@ function t(key: keyof typeof ACCESS_TERM, isEn: boolean) {
|
||||
}
|
||||
|
||||
// ─── Layer 2: Authenticated but no active subscription ───────────────────────
|
||||
function SubscriptionGate({
|
||||
isEn,
|
||||
points,
|
||||
onPaid,
|
||||
}: {
|
||||
isEn: boolean;
|
||||
points: number;
|
||||
onPaid: () => void;
|
||||
}) {
|
||||
const [showOverlay, setShowOverlay] = useState(false);
|
||||
const {
|
||||
billing,
|
||||
usePoints,
|
||||
setUsePoints,
|
||||
payBusy,
|
||||
errorText,
|
||||
infoText,
|
||||
txHash,
|
||||
chainId,
|
||||
tokenSymbol,
|
||||
walletAddress,
|
||||
handlePay,
|
||||
} = useTerminalPay({
|
||||
points,
|
||||
planPriceUsd: 10,
|
||||
onPaid: () => {
|
||||
setShowOverlay(false);
|
||||
onPaid();
|
||||
},
|
||||
isEn,
|
||||
});
|
||||
|
||||
const handleSubscribeClick = () => {
|
||||
setShowOverlay(true);
|
||||
};
|
||||
|
||||
function SubscriptionGate({ isEn }: { isEn: boolean }) {
|
||||
const features = isEn
|
||||
? [
|
||||
"Real-time METAR observations across 500+ stations",
|
||||
@@ -72,7 +34,6 @@ function SubscriptionGate({
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center bg-[#e9edf3] p-6">
|
||||
<div className="w-full max-w-lg">
|
||||
{/* Header badge */}
|
||||
<div className="mb-6 flex items-center justify-center">
|
||||
<span className="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs font-bold uppercase tracking-wider text-amber-700">
|
||||
<LockKeyhole size={12} />
|
||||
@@ -80,9 +41,7 @@ function SubscriptionGate({
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Main card */}
|
||||
<div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-lg">
|
||||
{/* Card top band */}
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-700 px-8 py-6 text-white">
|
||||
<h1 className="text-xl font-black tracking-tight">
|
||||
{isEn
|
||||
@@ -97,7 +56,6 @@ function SubscriptionGate({
|
||||
</div>
|
||||
|
||||
<div className="p-8">
|
||||
{/* Price */}
|
||||
<div className="mb-6 flex items-baseline gap-1">
|
||||
<span className="text-4xl font-black text-slate-900">$10</span>
|
||||
<span className="text-base text-slate-500">
|
||||
@@ -105,7 +63,6 @@ function SubscriptionGate({
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Feature list */}
|
||||
<ul className="mb-8 space-y-3">
|
||||
{features.map((f) => (
|
||||
<li key={f} className="flex items-start gap-3 text-sm text-slate-700">
|
||||
@@ -119,15 +76,13 @@ function SubscriptionGate({
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{/* CTA */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubscribeClick}
|
||||
<Link
|
||||
href="/account"
|
||||
className="flex w-full items-center justify-center gap-2 rounded-xl bg-blue-600 py-3.5 text-sm font-black text-white shadow-sm transition hover:bg-blue-700"
|
||||
>
|
||||
<CreditCard size={16} />
|
||||
{t("subscribeNow", isEn)}
|
||||
</button>
|
||||
</Link>
|
||||
|
||||
<p className="mt-4 text-center text-[11px] text-slate-400">
|
||||
{isEn
|
||||
@@ -137,7 +92,6 @@ function SubscriptionGate({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Back link */}
|
||||
<div className="mt-5 text-center">
|
||||
<Link
|
||||
href="/"
|
||||
@@ -147,38 +101,6 @@ function SubscriptionGate({
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment overlay */}
|
||||
{showOverlay && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
|
||||
<UnlockProOverlay
|
||||
points={points}
|
||||
planPriceUsd={10}
|
||||
usePoints={usePoints}
|
||||
billing={billing}
|
||||
onToggleUsePoints={() => setUsePoints((prev) => !prev)}
|
||||
onPay={() => void handlePay()}
|
||||
onClose={() => setShowOverlay(false)}
|
||||
payBusy={payBusy}
|
||||
payLabel={
|
||||
walletAddress
|
||||
? isEn
|
||||
? "Subscribe & Activate"
|
||||
: "立即订阅并激活服务"
|
||||
: isEn
|
||||
? "Connect Wallet & Subscribe"
|
||||
: "连接钱包并订阅"
|
||||
}
|
||||
errorText={errorText || undefined}
|
||||
infoText={infoText || undefined}
|
||||
txHash={txHash || undefined}
|
||||
chainId={chainId}
|
||||
paymentTokenLabel={tokenSymbol}
|
||||
locale={isEn ? "en-US" : "zh-CN"}
|
||||
faqHref="/subscription-help"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -241,18 +163,13 @@ function UnauthenticatedGate({
|
||||
);
|
||||
}
|
||||
|
||||
/** Unified access gate — routes to the correct layer based on auth state */
|
||||
export function ProductAccessRequired({
|
||||
isAuthenticated,
|
||||
isEn,
|
||||
points,
|
||||
onPaid,
|
||||
userLocalTime,
|
||||
}: {
|
||||
isAuthenticated: boolean;
|
||||
isEn: boolean;
|
||||
points: number;
|
||||
onPaid: () => void;
|
||||
userLocalTime: string;
|
||||
}) {
|
||||
if (!isAuthenticated) {
|
||||
@@ -269,7 +186,7 @@ export function ProductAccessRequired({
|
||||
</Link>
|
||||
<div className="font-mono text-sm text-slate-300">{userLocalTime}</div>
|
||||
</header>
|
||||
<SubscriptionGate isEn={isEn} points={points} onPaid={onPaid} />
|
||||
<SubscriptionGate isEn={isEn} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,418 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { UnlockProBilling } from "@/components/subscription/UnlockProOverlay";
|
||||
import { computeBilling } from "@/lib/billing-utils";
|
||||
import {
|
||||
WALLETCONNECT_POLYGON_RPC_URL,
|
||||
WALLET_TRANSACTION_REQUEST_TIMEOUT_MS,
|
||||
} from "@/components/account/constants";
|
||||
import {
|
||||
buildAllowanceCalldata,
|
||||
buildApproveCalldata,
|
||||
buildBalanceOfCalldata,
|
||||
requestWalletWithTimeout,
|
||||
} from "@/components/account/payment-utils";
|
||||
import { isPaymentHostAllowed, getCurrentPaymentHost } from "@/lib/payment-host";
|
||||
import {
|
||||
getEvmProvider,
|
||||
getEvmWalletLabel,
|
||||
getWalletConnectProvider,
|
||||
} from "@/components/account/wallet";
|
||||
import { getSupabaseBrowserClient } from "@/lib/supabase/client";
|
||||
import type { EvmProvider, CreatedIntent } from "@/components/account/types";
|
||||
|
||||
const DEFAULT_CHAIN_ID = 137;
|
||||
const INTENT_POLL_INTERVAL_MS = 5000;
|
||||
const INTENT_POLL_TIMEOUT_MS = 180_000;
|
||||
|
||||
function normalizePaymentError(err: unknown, fallback: string): string {
|
||||
if (!err) return fallback;
|
||||
const e = err as Record<string, unknown>;
|
||||
return String(
|
||||
e.shortMessage || e.message || e.reason || e.error || fallback,
|
||||
);
|
||||
}
|
||||
|
||||
export function useTerminalPay(params: {
|
||||
points: number;
|
||||
planPriceUsd: number;
|
||||
onPaid: () => void;
|
||||
isEn: boolean;
|
||||
}) {
|
||||
const { points, planPriceUsd, onPaid, isEn } = params;
|
||||
|
||||
const [paymentConfig, setPaymentConfig] = useState<Record<string, unknown> | null>(null);
|
||||
const [walletAddress, setWalletAddress] = useState<string | null>(null);
|
||||
const [usePoints, setUsePoints] = useState(true);
|
||||
const [payBusy, setPayBusy] = useState(false);
|
||||
const [errorText, setErrorText] = useState("");
|
||||
const [infoText, setInfoText] = useState("");
|
||||
const [txHash, setTxHash] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch("/api/payments/config", {
|
||||
cache: "no-store",
|
||||
headers: { Accept: "application/json" },
|
||||
})
|
||||
.then(async (r) => {
|
||||
if (!r.ok) return null;
|
||||
return r.json();
|
||||
})
|
||||
.then((cfg) => {
|
||||
if (cancelled) return;
|
||||
setPaymentConfig(cfg || null);
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
const billing: UnlockProBilling = useMemo(() => {
|
||||
const raw = computeBilling({
|
||||
planPriceUsd,
|
||||
totalPoints: points,
|
||||
usePoints,
|
||||
redemptionCfg: (paymentConfig?.points_redemption as Record<string, unknown>) ?? null,
|
||||
});
|
||||
return {
|
||||
pointsEnabled: raw.pointsEnabled,
|
||||
isEligible: raw.canRedeem,
|
||||
pointsUsed: raw.pointsUsed,
|
||||
discountAmount: raw.discountAmount,
|
||||
finalPrice: raw.payAmount,
|
||||
maxDiscountUsd: raw.maxDiscountUsdc,
|
||||
pointsPerUsd: raw.pointsPerUsdc,
|
||||
};
|
||||
}, [planPriceUsd, points, usePoints, paymentConfig]);
|
||||
|
||||
const chainId = useMemo(
|
||||
() => Number(paymentConfig?.chain_id || DEFAULT_CHAIN_ID),
|
||||
[paymentConfig],
|
||||
);
|
||||
|
||||
const tokenAddress = useMemo(() => {
|
||||
const tokens = (paymentConfig?.tokens as Array<Record<string, unknown>>) || [];
|
||||
return String(tokens[0]?.address || "");
|
||||
}, [paymentConfig]);
|
||||
|
||||
const tokenSymbol = useMemo(() => {
|
||||
const tokens = (paymentConfig?.tokens as Array<Record<string, unknown>>) || [];
|
||||
return String(tokens[0]?.symbol || "USDC");
|
||||
}, [paymentConfig]);
|
||||
|
||||
const tokenDecimals = useMemo(() => {
|
||||
const tokens = (paymentConfig?.tokens as Array<Record<string, unknown>>) || [];
|
||||
return Number(tokens[0]?.decimals || 6);
|
||||
}, [paymentConfig]);
|
||||
|
||||
const receiverAddress = useMemo(
|
||||
() => String(paymentConfig?.receiver_address || ""),
|
||||
[paymentConfig],
|
||||
);
|
||||
|
||||
const connectWallet = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
let provider: EvmProvider | null = getEvmProvider();
|
||||
let label = getEvmWalletLabel(provider);
|
||||
|
||||
if (!provider) {
|
||||
const wcId = String(
|
||||
process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID || "",
|
||||
).trim();
|
||||
if (!wcId) {
|
||||
setErrorText(
|
||||
isEn
|
||||
? "No wallet detected. Install MetaMask or configure WalletConnect."
|
||||
: "未检测到钱包插件,请安装 MetaMask 扩展。",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
provider = await getWalletConnectProvider(
|
||||
chainId,
|
||||
WALLETCONNECT_POLYGON_RPC_URL,
|
||||
);
|
||||
label = "WalletConnect";
|
||||
const existing = (await provider
|
||||
.request({ method: "eth_accounts" })
|
||||
.catch(() => [])) as string[];
|
||||
if (!Array.isArray(existing) || existing.length === 0) {
|
||||
if (typeof provider.connect === "function") {
|
||||
await provider.connect({ chains: [chainId] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const accounts = (await provider.request({
|
||||
method: "eth_requestAccounts",
|
||||
})) as string[];
|
||||
const address = String(accounts[0] || "").toLowerCase();
|
||||
if (!address) throw new Error("No account returned");
|
||||
|
||||
setWalletAddress(address);
|
||||
return address;
|
||||
} catch (err) {
|
||||
setErrorText(normalizePaymentError(err, isEn ? "Wallet connection failed" : "钱包连接失败"));
|
||||
return null;
|
||||
}
|
||||
}, [chainId, isEn]);
|
||||
|
||||
const handlePay = useCallback(async () => {
|
||||
if (payBusy) return;
|
||||
setPayBusy(true);
|
||||
setErrorText("");
|
||||
setInfoText("");
|
||||
|
||||
try {
|
||||
const host = getCurrentPaymentHost();
|
||||
const allowed = await isPaymentHostAllowed(host);
|
||||
if (!allowed) throw new Error(isEn ? "Payment host not allowed" : "当前域名不在支付白名单中");
|
||||
|
||||
// Get session token
|
||||
const supabase = getSupabaseBrowserClient();
|
||||
const { data: sessionData } = await supabase.auth.getSession();
|
||||
const token = sessionData?.session?.access_token;
|
||||
if (!token) throw new Error(isEn ? "Session expired, please refresh" : "会话过期,请刷新页面");
|
||||
const authHeaders = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
|
||||
|
||||
// Connect wallet
|
||||
let payingWallet = walletAddress;
|
||||
if (!payingWallet) {
|
||||
payingWallet = await connectWallet();
|
||||
if (!payingWallet) {
|
||||
setPayBusy(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh payment config
|
||||
const cfgRes = await fetch("/api/payments/config", {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
const latestCfg = cfgRes.ok ? await cfgRes.json() : paymentConfig;
|
||||
setPaymentConfig(latestCfg || paymentConfig);
|
||||
|
||||
const targetChainId = Number(latestCfg?.chain_id || DEFAULT_CHAIN_ID);
|
||||
|
||||
// Resolve provider for payment
|
||||
let eth = getEvmProvider();
|
||||
if (!eth) {
|
||||
const wcId = String(process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID || "").trim();
|
||||
if (!wcId) throw new Error("No wallet available");
|
||||
eth = await getWalletConnectProvider(targetChainId, WALLETCONNECT_POLYGON_RPC_URL);
|
||||
const existing = (await eth.request({ method: "eth_accounts" }).catch(() => [])) as string[];
|
||||
if (!Array.isArray(existing) || existing.length === 0) {
|
||||
if (typeof eth.connect === "function") {
|
||||
await eth.connect({ chains: [targetChainId] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure target chain
|
||||
const currentChainHex = String(
|
||||
(await requestWalletWithTimeout<string>(eth, { method: "eth_chainId" }, "chainId", WALLET_TRANSACTION_REQUEST_TIMEOUT_MS)) || "",
|
||||
);
|
||||
const targetHex = `0x${targetChainId.toString(16)}`;
|
||||
if (currentChainHex.toLowerCase() !== targetHex.toLowerCase()) {
|
||||
try {
|
||||
await requestWalletWithTimeout(eth, {
|
||||
method: "wallet_switchEthereumChain",
|
||||
params: [{ chainId: targetHex }],
|
||||
}, "switchChain");
|
||||
} catch (switchErr: unknown) {
|
||||
const code = Number((switchErr as Record<string, unknown>)?.code);
|
||||
if (code === 4902 || targetChainId === 137) {
|
||||
await requestWalletWithTimeout(eth, {
|
||||
method: "wallet_addEthereumChain",
|
||||
params: [{
|
||||
chainId: "0x89",
|
||||
chainName: "Polygon Mainnet",
|
||||
nativeCurrency: { name: "POL", symbol: "POL", decimals: 18 },
|
||||
rpcUrls: ["https://polygon-rpc.com"],
|
||||
blockExplorerUrls: ["https://polygonscan.com"],
|
||||
}],
|
||||
}, "addChain");
|
||||
} else {
|
||||
throw switchErr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create payment intent
|
||||
const resolvedToken = String(latestCfg?.tokens?.[0]?.address || tokenAddress);
|
||||
const intentRes = await fetch("/api/payments/intents", {
|
||||
method: "POST",
|
||||
headers: authHeaders,
|
||||
body: JSON.stringify({
|
||||
plan_code: "pro_monthly",
|
||||
payment_mode: "strict",
|
||||
allowed_wallet: payingWallet,
|
||||
token_address: resolvedToken || undefined,
|
||||
use_points: billing.isEligible && usePoints,
|
||||
points_to_consume: billing.isEligible && usePoints ? billing.pointsUsed : 0,
|
||||
metadata: {
|
||||
source: "terminal",
|
||||
frontend_host: host || null,
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (!intentRes.ok) {
|
||||
const errBody = await intentRes.json().catch(() => ({}));
|
||||
throw new Error(String(errBody?.detail || errBody?.message || `HTTP ${intentRes.status}`));
|
||||
}
|
||||
const created = (await intentRes.json()) as CreatedIntent;
|
||||
const intentId = String(created.intent?.intent_id || "");
|
||||
const txPayload = created.tx_payload;
|
||||
if (!intentId || !txPayload?.to || !txPayload?.data) {
|
||||
throw new Error(isEn ? "Invalid payment intent response" : "支付意图创建失败");
|
||||
}
|
||||
|
||||
// Verify receiver
|
||||
const expectedReceiver = String(latestCfg?.receiver_address || receiverAddress);
|
||||
if (expectedReceiver && txPayload.to.toLowerCase() !== expectedReceiver.toLowerCase()) {
|
||||
throw new Error(isEn ? "Payment receiver mismatch" : "收款地址不匹配");
|
||||
}
|
||||
|
||||
const resolvedTokenDecimals = Number(
|
||||
latestCfg?.tokens?.[0]?.decimals || tokenDecimals,
|
||||
);
|
||||
const amountUnits =
|
||||
typeof txPayload.amount_units === "string"
|
||||
? BigInt(txPayload.amount_units)
|
||||
: BigInt(String(txPayload.value || 0));
|
||||
|
||||
// Check balance
|
||||
const balanceHex = await requestWalletWithTimeout<string>(
|
||||
eth,
|
||||
{
|
||||
method: "eth_call",
|
||||
params: [
|
||||
{ to: txPayload.token_address || resolvedToken, data: buildBalanceOfCalldata(payingWallet) },
|
||||
"latest",
|
||||
],
|
||||
},
|
||||
"balanceOf",
|
||||
);
|
||||
const balance = BigInt(balanceHex || "0x0");
|
||||
if (balance < amountUnits) {
|
||||
throw new Error(isEn ? "Insufficient USDC balance" : "USDC 余额不足");
|
||||
}
|
||||
|
||||
// Check allowance and approve if needed
|
||||
const allowanceHex = await requestWalletWithTimeout<string>(
|
||||
eth,
|
||||
{
|
||||
method: "eth_call",
|
||||
params: [
|
||||
{ to: txPayload.token_address || resolvedToken, data: buildAllowanceCalldata(payingWallet, txPayload.to) },
|
||||
"latest",
|
||||
],
|
||||
},
|
||||
"allowance",
|
||||
);
|
||||
const allowance = BigInt(allowanceHex || "0x0");
|
||||
if (allowance < amountUnits) {
|
||||
setInfoText(isEn ? "Approving USDC..." : "正在授权 USDC...");
|
||||
const approveHash = await requestWalletWithTimeout<string>(
|
||||
eth,
|
||||
{
|
||||
method: "eth_sendTransaction",
|
||||
params: [{
|
||||
from: payingWallet,
|
||||
to: txPayload.token_address || resolvedToken,
|
||||
data: buildApproveCalldata(txPayload.to, amountUnits),
|
||||
}],
|
||||
},
|
||||
"approve",
|
||||
);
|
||||
// Wait for approval receipt via simple polling
|
||||
const approveStart = Date.now();
|
||||
while (Date.now() - approveStart < 120_000) {
|
||||
const receipt = await requestWalletWithTimeout<Record<string, unknown> | null>(
|
||||
eth,
|
||||
{ method: "eth_getTransactionReceipt", params: [approveHash] },
|
||||
"approveReceipt",
|
||||
).catch(() => null);
|
||||
if (receipt?.status === "0x1" || receipt?.status === 1) break;
|
||||
if (receipt?.status === "0x0" || receipt?.status === 0) {
|
||||
throw new Error(isEn ? "USDC approval failed" : "USDC 授权失败");
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
}
|
||||
}
|
||||
|
||||
// Send payment transaction
|
||||
setInfoText(isEn ? "Confirm in wallet..." : "请在钱包中确认交易...");
|
||||
const payHash = await requestWalletWithTimeout<string>(
|
||||
eth,
|
||||
{
|
||||
method: "eth_sendTransaction",
|
||||
params: [{ from: payingWallet, to: txPayload.to, data: txPayload.data }],
|
||||
},
|
||||
"pay",
|
||||
);
|
||||
setTxHash(payHash);
|
||||
|
||||
// Submit
|
||||
const submitRes = await fetch(`/api/payments/intents/${intentId}/submit`, {
|
||||
method: "POST",
|
||||
headers: authHeaders,
|
||||
body: JSON.stringify({ tx_hash: payHash, from_address: payingWallet }),
|
||||
});
|
||||
if (!submitRes.ok && submitRes.status !== 409) {
|
||||
const errBody = await submitRes.json().catch(() => ({}));
|
||||
throw new Error(String(errBody?.detail || `HTTP ${submitRes.status}`));
|
||||
}
|
||||
|
||||
// Confirm
|
||||
const confirmStart = Date.now();
|
||||
let confirmed = false;
|
||||
while (Date.now() - confirmStart < INTENT_POLL_TIMEOUT_MS) {
|
||||
const confirmRes = await fetch(`/api/payments/intents/${intentId}/confirm`, {
|
||||
method: "POST",
|
||||
headers: authHeaders,
|
||||
body: JSON.stringify({ tx_hash: payHash }),
|
||||
});
|
||||
if (confirmRes.ok) {
|
||||
setInfoText(isEn ? "Payment confirmed! Activating..." : "支付确认!正在激活...");
|
||||
confirmed = true;
|
||||
break;
|
||||
}
|
||||
if (confirmRes.status === 409 || confirmRes.status === 404 || confirmRes.status === 408) {
|
||||
await new Promise((r) => setTimeout(r, INTENT_POLL_INTERVAL_MS));
|
||||
continue;
|
||||
}
|
||||
const errBody = await confirmRes.json().catch(() => ({}));
|
||||
throw new Error(String(errBody?.detail || `HTTP ${confirmRes.status}`));
|
||||
}
|
||||
if (!confirmed) {
|
||||
throw new Error(isEn ? "Payment confirmation timeout" : "支付确认超时,请稍后检查订单状态");
|
||||
}
|
||||
|
||||
setInfoText(isEn ? "Subscription activated!" : "订阅已激活!");
|
||||
onPaid();
|
||||
} catch (err) {
|
||||
setErrorText(normalizePaymentError(err, isEn ? "Payment failed" : "支付失败"));
|
||||
} finally {
|
||||
setPayBusy(false);
|
||||
}
|
||||
}, [
|
||||
payBusy, walletAddress, paymentConfig, billing, usePoints, chainId,
|
||||
tokenAddress, tokenDecimals, receiverAddress, isEn, connectWallet, onPaid,
|
||||
]);
|
||||
|
||||
return {
|
||||
billing,
|
||||
usePoints,
|
||||
setUsePoints,
|
||||
payBusy,
|
||||
errorText,
|
||||
infoText,
|
||||
txHash,
|
||||
chainId,
|
||||
tokenSymbol,
|
||||
walletAddress,
|
||||
connectWallet,
|
||||
handlePay,
|
||||
};
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
export interface TerminalBilling {
|
||||
planAmount: number;
|
||||
pointsEnabled: boolean;
|
||||
pointsPerUsdc: number;
|
||||
maxDiscountUsdc: number;
|
||||
pointsUsed: number;
|
||||
discountAmount: number;
|
||||
payAmount: number;
|
||||
canRedeem: boolean;
|
||||
}
|
||||
|
||||
export interface PointsRedemptionConfig {
|
||||
enabled?: boolean;
|
||||
points_per_usdc?: number;
|
||||
max_discount_usdc?: number;
|
||||
}
|
||||
|
||||
export function computeBilling(params: {
|
||||
planPriceUsd: number;
|
||||
totalPoints: number;
|
||||
usePoints: boolean;
|
||||
redemptionCfg?: PointsRedemptionConfig | null;
|
||||
}): TerminalBilling {
|
||||
const planAmount =
|
||||
Number.isFinite(params.planPriceUsd) && params.planPriceUsd > 0
|
||||
? params.planPriceUsd
|
||||
: 10;
|
||||
|
||||
const cfg = params.redemptionCfg || {};
|
||||
const pointsEnabled = cfg.enabled !== false;
|
||||
const pointsPerUsdcRaw = Number(cfg.points_per_usdc ?? 500);
|
||||
const pointsPerUsdc =
|
||||
Number.isFinite(pointsPerUsdcRaw) && pointsPerUsdcRaw > 0
|
||||
? Math.floor(pointsPerUsdcRaw)
|
||||
: 500;
|
||||
|
||||
const maxDiscountRaw = Number(cfg.max_discount_usdc ?? 3);
|
||||
const maxDiscountUsdc = Math.max(
|
||||
0,
|
||||
Math.min(
|
||||
Math.floor(Number.isFinite(maxDiscountRaw) ? maxDiscountRaw : 3),
|
||||
Math.floor(planAmount),
|
||||
),
|
||||
);
|
||||
|
||||
const maxRedeemablePoints = pointsPerUsdc * maxDiscountUsdc;
|
||||
const actualRedeem = pointsEnabled
|
||||
? Math.min(params.totalPoints, maxRedeemablePoints)
|
||||
: 0;
|
||||
const discountUnits = Math.floor(actualRedeem / pointsPerUsdc);
|
||||
const pointsUsed = discountUnits * pointsPerUsdc;
|
||||
const canRedeem =
|
||||
pointsEnabled &&
|
||||
maxDiscountUsdc > 0 &&
|
||||
params.totalPoints >= pointsPerUsdc;
|
||||
const applyDiscount =
|
||||
params.usePoints && canRedeem && pointsUsed > 0;
|
||||
|
||||
return {
|
||||
planAmount,
|
||||
pointsEnabled,
|
||||
pointsPerUsdc,
|
||||
maxDiscountUsdc,
|
||||
pointsUsed,
|
||||
discountAmount: discountUnits,
|
||||
payAmount: planAmount - (applyDiscount ? discountUnits : 0),
|
||||
canRedeem,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user