Initial commit

This commit is contained in:
zvspany
2026-03-07 16:34:10 +01:00
commit 48d3ac684f
524 changed files with 9352 additions and 0 deletions

3
.env.example Normal file
View File

@@ -0,0 +1,3 @@
# No API keys are required for the default setup.
# Optional: override the internal API route base when deploying behind a proxy.
# NEXT_PUBLIC_API_BASE_URL=

6
.eslintrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"extends": ["next/core-web-vitals", "next/typescript"],
"rules": {
"@next/next/no-img-element": "off"
}
}

13
.gitignore vendored Normal file
View File

@@ -0,0 +1,13 @@
node_modules/
.next/
out/
dist/
build/
.env
.env.local
.env.*.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.DS_Store

153
README.md Normal file
View File

@@ -0,0 +1,153 @@
# NexCurrency
Modern currency and crypto converter built with Next.js 14, TypeScript, Tailwind CSS, and shadcn-style UI components.
## Features
- Unified conversion for:
- Fiat to fiat
- Fiat to crypto
- Crypto to fiat
- Crypto to crypto
- Searchable asset selectors with popular presets
- Currency icons in selectors and conversion summary:
- Crypto icons from `cryptocurrency-icons`
- Fiat flags from `currency-flags`
- Default pair: `USD -> EUR`
- Instant conversion with swap action
- Current rate, inverse rate, and last update timestamp
- Client-side validation for invalid/negative amounts
- Loading, error, and empty states
- Dark, responsive fintech-style UI for mobile and desktop
- Normalized data layer for easy API provider swapping
## Tech Stack
- Next.js 14 (App Router)
- TypeScript
- Tailwind CSS
- shadcn-style UI components (local implementation)
- Zod (validation)
## Data Sources
- Fiat rates and currency list: [Frankfurter](https://www.frankfurter.app/)
- Crypto USD prices: [CoinGecko API](https://www.coingecko.com/en/api)
The app normalizes both feeds into a shared internal model (`usdPrice` per asset) and performs all conversions through USD when direct pairs are not available.
## Project Structure
```text
.
├── app
│ ├── api/rates/route.ts
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── components
│ ├── converter
│ │ ├── converter-card.tsx
│ │ └── currency-select.tsx
│ ├── sections
│ │ ├── hero.tsx
│ │ └── insights-section.tsx
│ └── ui
│ ├── badge.tsx
│ ├── button.tsx
│ ├── card.tsx
│ ├── command.tsx
│ ├── input.tsx
│ ├── popover.tsx
│ ├── separator.tsx
│ └── skeleton.tsx
├── hooks
│ ├── use-debounced-value.ts
│ └── use-market-rates.ts
├── lib
│ ├── api
│ │ ├── crypto.ts
│ │ ├── fiat.ts
│ │ └── normalize.ts
│ ├── assets.ts
│ ├── format.ts
│ ├── rates.ts
│ ├── utils.ts
│ └── validation.ts
├── .env.example
├── next.config.mjs
├── package.json
├── postcss.config.mjs
├── tailwind.config.ts
└── tsconfig.json
```
## Setup
1. Install dependencies:
```bash
npm install
```
2. Run development server:
```bash
npm run dev
```
3. Open:
```text
http://localhost:3000
```
## Build and Lint
```bash
npm run lint
npm run build
npm run start
```
If you update `cryptocurrency-icons`, resync local PNG assets with:
```bash
npm run sync:crypto-icons
```
## Environment Variables
No API keys are required.
Optional variable (only if you want to call API routes through a custom base URL):
```env
NEXT_PUBLIC_API_BASE_URL=
```
If empty, the app uses the local default (`/api/rates`).
## Architecture Notes
- `app/api/rates/route.ts` is the single internal market endpoint for the frontend.
- Provider modules are isolated in `lib/api/` so they can be swapped independently.
- `lib/api/normalize.ts` unifies fiat and crypto responses into one shape used by UI.
- Conversion formula is provider-agnostic:
- `result = amount * (from.usdPrice / to.usdPrice)`
- UI stays fully client-side for interaction speed, while data aggregation stays server-side.
## Validation and Formatting
- Input validation is handled with Zod (`lib/validation.ts`)
- Fiat and crypto formatting rules are separated (`lib/format.ts`)
- Crypto values allow higher precision and support fractional amounts
## Notes
- The UI and all copy are fully English.
- Default experience is dark mode with a premium minimalist style.
## License
This project is licensed under the MIT License. See the `LICENSE` file for full text.

75
app/api/rates/route.ts Normal file
View File

@@ -0,0 +1,75 @@
import { NextResponse } from "next/server";
import { fetchUnifiedRates } from "@/lib/api/normalize";
import type { RatesResponse } from "@/lib/rates";
const CACHE_TTL_MS = 300_000;
const CACHE_CONTROL_VALUE = "s-maxage=300, stale-while-revalidate=1800";
let cachedRates: RatesResponse | null = null;
let cacheTimestamp = 0;
let inFlightRequest: Promise<RatesResponse> | null = null;
export const revalidate = 300;
async function getRatesWithCache(): Promise<RatesResponse> {
const now = Date.now();
const hasFreshCache = cachedRates && now - cacheTimestamp < CACHE_TTL_MS;
if (hasFreshCache && cachedRates) {
return cachedRates;
}
if (inFlightRequest) {
return inFlightRequest;
}
inFlightRequest = (async () => {
const freshRates = await fetchUnifiedRates();
cachedRates = freshRates;
cacheTimestamp = Date.now();
return freshRates;
})();
try {
return await inFlightRequest;
} finally {
inFlightRequest = null;
}
}
export async function GET() {
try {
const data = await getRatesWithCache();
return NextResponse.json(data, {
status: 200,
headers: {
"Cache-Control": CACHE_CONTROL_VALUE
}
});
} catch (error) {
if (cachedRates) {
return NextResponse.json(cachedRates, {
status: 200,
headers: {
"Cache-Control": CACHE_CONTROL_VALUE,
"X-Cache-Fallback": "stale-on-error"
}
});
}
const message =
error instanceof Error
? error.message
: "Unexpected error while loading rates";
return NextResponse.json(
{
message
},
{
status: 500
}
);
}
}

78
app/globals.css Normal file
View File

@@ -0,0 +1,78 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: 222 47% 8%;
--foreground: 213 31% 96%;
--card: 220 34% 11%;
--card-foreground: 210 38% 96%;
--popover: 221 36% 12%;
--popover-foreground: 210 38% 97%;
--primary: 193 92% 58%;
--primary-foreground: 221 39% 10%;
--secondary: 217 20% 18%;
--secondary-foreground: 210 37% 95%;
--muted: 218 18% 18%;
--muted-foreground: 217 17% 72%;
--accent: 202 88% 16%;
--accent-foreground: 198 100% 90%;
--border: 217 24% 24%;
--input: 217 24% 24%;
--ring: 192 89% 60%;
--radius: 0.9rem;
}
* {
@apply border-border;
}
html,
body {
height: 100%;
}
body {
@apply bg-background text-foreground;
font-family: "Manrope", "Avenir Next", "Segoe UI", sans-serif;
position: relative;
z-index: 0;
isolation: isolate;
overflow-x: hidden;
background-color: hsl(var(--background));
}
body::before {
content: "";
position: fixed;
inset: -15vh -15vw;
z-index: -1;
pointer-events: none;
background-image:
radial-gradient(
68% 58% at 50% -10%,
hsl(193 95% 58% / 0.24) 0%,
hsl(193 95% 58% / 0.13) 38%,
transparent 76%
),
radial-gradient(52% 64% at 102% 42%, hsl(162 90% 50% / 0.11) 0%, transparent 74%),
radial-gradient(52% 64% at -2% 78%, hsl(210 92% 56% / 0.1) 0%, transparent 74%),
linear-gradient(180deg, hsl(222 45% 7%) 0%, hsl(223 48% 6%) 100%);
transform: translateZ(0);
will-change: transform;
}
.font-heading {
font-family: "Space Grotesk", "Manrope", "Segoe UI", sans-serif;
}
@layer base {
h1,
h2,
h3,
h4,
h5,
h6 {
@apply font-heading;
}
}

24
app/layout.tsx Normal file
View File

@@ -0,0 +1,24 @@
import type { Metadata } from "next";
import "./globals.css";
import "currency-flags/dist/currency-flags.min.css";
export const metadata: Metadata = {
title: "NexCurrency | Modern Currency & Crypto Converter",
description:
"Convert fiat and crypto assets instantly with live rates, smart formatting, and a premium modern interface."
};
export default function RootLayout({
children
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="dark" suppressHydrationWarning>
<body className="font-sans antialiased">
{children}
</body>
</html>
);
}

65
app/page.tsx Normal file
View File

@@ -0,0 +1,65 @@
"use client";
import { useCallback, useState } from "react";
import { ConverterCard } from "@/components/converter/converter-card";
import { Hero } from "@/components/sections/hero";
import { InsightsSection } from "@/components/sections/insights-section";
const DEFAULT_FROM = "USD";
const DEFAULT_TO = "EUR";
export default function HomePage() {
const [selectedFromCode, setSelectedFromCode] = useState(DEFAULT_FROM);
const [selectedToCode, setSelectedToCode] = useState(DEFAULT_TO);
const handleSelectPopularPair = useCallback(
(fromCode: string, toCode: string) => {
setSelectedFromCode(fromCode);
setSelectedToCode(toCode);
},
[],
);
const handlePairChange = useCallback((fromCode: string, toCode: string) => {
setSelectedFromCode(fromCode);
setSelectedToCode(toCode);
}, []);
return (
<main className="relative isolate min-h-[100svh] overflow-hidden pb-20">
<div className="container relative z-10">
<Hero />
<section className="mx-auto mt-10 max-w-5xl animate-in fade-in-0 slide-in-from-bottom-2 duration-700">
<ConverterCard
forcedFromCode={selectedFromCode}
forcedToCode={selectedToCode}
onPairChange={handlePairChange}
/>
<InsightsSection
selectedFromCode={selectedFromCode}
selectedToCode={selectedToCode}
onSelectPopularPair={handleSelectPopularPair}
/>
</section>
</div>
<footer className="container mt-12 flex flex-col items-center gap-2 text-center text-xs text-muted-foreground">
<p>
Market data is provided by Frankfurter and CoinGecko. Rates are
refreshed automatically.
</p>
{/*
<a
href="https://github.com/zvspany/nextcurrency"
target="_blank"
rel="noreferrer"
className="rounded-full border border-border/70 bg-background/50 px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:border-cyan-400/40 hover:bg-cyan-400/10 hover:text-cyan-100"
>
Repository
</a>
*/}
</footer>
</main>
);
}

View File

@@ -0,0 +1,362 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { AlertTriangle, ArrowUpDown, Loader2, RefreshCcw } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { CurrencySelect } from "@/components/converter/currency-select";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useMarketRates } from "@/hooks/use-market-rates";
import {
formatAmount,
formatInverseRate,
formatRate,
formatTimestamp
} from "@/lib/format";
import { buildRateMap, convertAmount } from "@/lib/rates";
import { validateAmount } from "@/lib/validation";
const DEFAULT_FROM = "USD";
const DEFAULT_TO = "EUR";
interface ConverterCardProps {
forcedFromCode?: string;
forcedToCode?: string;
onPairChange?: (fromCode: string, toCode: string) => void;
}
function ConverterSkeleton() {
return (
<Card className="border-border/70">
<CardHeader>
<Skeleton className="h-6 w-40" />
<Skeleton className="h-4 w-72" />
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-2">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-14 w-full rounded-xl" />
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
<Skeleton className="h-20 w-full rounded-xl" />
<Skeleton className="mx-auto h-10 w-10 rounded-full" />
<Skeleton className="h-20 w-full rounded-xl" />
</div>
<Skeleton className="h-28 w-full rounded-xl" />
</CardContent>
</Card>
);
}
function ErrorState({
message,
onRetry
}: {
message: string;
onRetry: () => void;
}) {
return (
<Card className="border-red-500/30 bg-red-500/5">
<CardContent className="flex flex-col gap-4 p-6">
<div className="flex items-start gap-3">
<AlertTriangle className="mt-0.5 h-5 w-5 text-red-300" />
<div>
<p className="text-sm font-medium text-red-200">Unable to load market rates</p>
<p className="mt-1 text-sm text-red-200/80">{message}</p>
</div>
</div>
<Button variant="outline" onClick={onRetry} className="w-fit border-red-300/30">
<RefreshCcw className="mr-2 h-4 w-4" />
Retry
</Button>
</CardContent>
</Card>
);
}
function EmptyState() {
return (
<Card className="border-border/70">
<CardContent className="p-6">
<p className="text-sm text-muted-foreground">
No assets are currently available. Please try again shortly.
</p>
</CardContent>
</Card>
);
}
export function ConverterCard({
forcedFromCode,
forcedToCode,
onPairChange
}: ConverterCardProps) {
const { data, error, isLoading, refresh } = useMarketRates();
const [amountInput, setAmountInput] = useState("1");
const [fromCode, setFromCode] = useState(DEFAULT_FROM);
const [toCode, setToCode] = useState(DEFAULT_TO);
const debouncedAmount = useDebouncedValue(amountInput, 120);
const assets = useMemo(() => data?.assets ?? [], [data]);
const rateMap = useMemo(() => buildRateMap(assets), [assets]);
useEffect(() => {
if (!assets.length) {
return;
}
if (!rateMap.has(fromCode)) {
setFromCode(rateMap.has(DEFAULT_FROM) ? DEFAULT_FROM : assets[0].code);
}
if (!rateMap.has(toCode)) {
const fallback = rateMap.has(DEFAULT_TO)
? DEFAULT_TO
: assets.find((asset) => asset.code !== fromCode)?.code ?? assets[0].code;
setToCode(fallback);
}
}, [assets, fromCode, toCode, rateMap]);
useEffect(() => {
if (!assets.length) {
return;
}
if (forcedFromCode && rateMap.has(forcedFromCode)) {
setFromCode(forcedFromCode);
}
if (forcedToCode && rateMap.has(forcedToCode)) {
setToCode(forcedToCode);
}
}, [assets, forcedFromCode, forcedToCode, rateMap]);
useEffect(() => {
onPairChange?.(fromCode, toCode);
}, [fromCode, toCode, onPairChange]);
const inputValidation = validateAmount(amountInput);
const debouncedValidation = validateAmount(debouncedAmount);
const fromAsset = rateMap.get(fromCode);
const toAsset = rateMap.get(toCode);
const convertedValue = useMemo(() => {
if (!fromAsset || !toAsset || !debouncedValidation.ok) {
return null;
}
return convertAmount(debouncedValidation.value, fromAsset, toAsset);
}, [fromAsset, toAsset, debouncedValidation]);
const currentRate = useMemo(() => {
if (!fromAsset || !toAsset) {
return null;
}
return formatRate(fromAsset, toAsset);
}, [fromAsset, toAsset]);
const inverseRate = useMemo(() => {
if (!fromAsset || !toAsset) {
return null;
}
return formatInverseRate(fromAsset, toAsset);
}, [fromAsset, toAsset]);
const handleSwap = () => {
setFromCode(toCode);
setToCode(fromCode);
};
if (isLoading && !data) {
return <ConverterSkeleton />;
}
if (!data && error) {
return <ErrorState message={error} onRetry={() => void refresh()} />;
}
if (!data || assets.length === 0) {
return <EmptyState />;
}
const convertedDisplay =
convertedValue !== null && toAsset
? `${formatAmount(convertedValue, toAsset)} ${toAsset.code}`
: "--";
const amountError = inputValidation.ok ? null : inputValidation.error;
return (
<Card className="relative overflow-hidden border-border/70 bg-card/90">
<CardHeader className="relative z-10 rounded-t-2xl bg-gradient-to-r from-sky-500/10 via-cyan-400/5 to-emerald-500/10 pb-4 sm:pb-5">
<div className="flex flex-wrap items-center justify-between gap-2">
<CardTitle className="text-2xl font-semibold tracking-tight">
Smart Converter
</CardTitle>
<div className="flex items-center gap-2">
<Badge variant="outline" className="border-border/70 bg-background/50">
Fiat: {data.sources.fiat}
</Badge>
<Badge variant="outline" className="border-border/70 bg-background/50">
Crypto: {data.sources.crypto}
</Badge>
</div>
</div>
<CardDescription className="pr-1 text-base/7 sm:text-sm">
Convert fiat and crypto assets instantly using live normalized USD quote data.
</CardDescription>
</CardHeader>
<CardContent className="relative z-10 space-y-5 pt-4 sm:pt-5">
{error ? (
<div className="flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-200">
<AlertTriangle className="h-4 w-4" />
<span>Using last successful data. Latest refresh failed: {error}</span>
</div>
) : null}
<div className="space-y-2">
<label
htmlFor="amount"
className="text-xs uppercase tracking-[0.14em] text-muted-foreground"
>
Amount
</label>
<Input
id="amount"
type="text"
inputMode="decimal"
value={amountInput}
onChange={(event) => setAmountInput(event.target.value)}
placeholder="Enter amount"
className="h-14 rounded-xl bg-background/70 px-4 text-lg"
aria-invalid={Boolean(amountError)}
aria-describedby={amountError ? "amount-error" : undefined}
/>
{amountError ? (
<p id="amount-error" className="text-sm text-red-300">
{amountError}
</p>
) : null}
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
<CurrencySelect
label="From"
value={fromCode}
onChange={setFromCode}
assets={assets}
/>
<Button
type="button"
size="icon"
variant="outline"
className="mx-auto mb-0.5 rounded-full border-border/70 bg-background/50"
onClick={handleSwap}
aria-label="Swap currencies"
>
<ArrowUpDown className="h-4 w-4" />
</Button>
<CurrencySelect
label="To"
value={toCode}
onChange={setToCode}
assets={assets}
/>
</div>
<div className="rounded-xl border border-border/70 bg-background/50 p-4">
<p className="text-xs uppercase tracking-[0.12em] text-muted-foreground">
Converted value
</p>
{fromAsset && toAsset ? (
<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon code={fromAsset.code} type={fromAsset.type} size="sm" />
{fromAsset.code}
</span>
<span>to</span>
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/70 bg-background/60 px-2 py-1">
<CurrencyIcon code={toAsset.code} type={toAsset.type} size="sm" />
{toAsset.code}
</span>
</div>
) : null}
<p className="mt-2 break-all text-3xl font-semibold tracking-tight text-foreground sm:text-4xl">
{convertedDisplay}
</p>
{fromAsset ? (
<p className="mt-2 text-sm text-muted-foreground">
for {inputValidation.ok ? formatAmount(inputValidation.value, fromAsset) : "-"}{" "}
{fromAsset.code}
</p>
) : null}
</div>
<Separator className="bg-border/70" />
<div className="grid gap-3 text-sm text-muted-foreground sm:grid-cols-3">
<div>
<p className="text-xs uppercase tracking-[0.12em]">Current rate</p>
<p className="mt-1 text-sm text-foreground">
{fromAsset && toAsset && currentRate
? `1 ${fromAsset.code} = ${currentRate} ${toAsset.code}`
: "-"}
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Inverse rate</p>
<p className="mt-1 text-sm text-foreground">
{fromAsset && toAsset && inverseRate
? `1 ${toAsset.code} = ${inverseRate} ${fromAsset.code}`
: "-"}
</p>
</div>
<div>
<p className="text-xs uppercase tracking-[0.12em]">Last updated</p>
<p className="mt-1 text-sm text-foreground">
{formatTimestamp(data.updatedAt)}
</p>
</div>
</div>
<div className="flex items-center justify-end">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => void refresh()}
className="text-muted-foreground"
>
<RefreshCcw className="mr-2 h-4 w-4" />
Refresh rates
</Button>
</div>
{isLoading ? (
<div className="flex items-center justify-end gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Updating market rates...
</div>
) : null}
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,82 @@
"use client";
import { useMemo, useState } from "react";
import type { AssetType } from "@/lib/assets";
import { FIAT_FLAG_CODES } from "@/lib/fiat-flag-codes";
import { cn } from "@/lib/utils";
const sizeClassMap = {
sm: "h-5 w-5",
md: "h-6 w-6",
lg: "h-8 w-8"
} as const;
type IconSize = keyof typeof sizeClassMap;
interface CurrencyIconProps {
code: string;
type: AssetType;
size?: IconSize;
className?: string;
}
export function CurrencyIcon({
code,
type,
size = "md",
className
}: CurrencyIconProps) {
const [cryptoMissing, setCryptoMissing] = useState(false);
const lowerCode = useMemo(() => code.toLowerCase(), [code]);
const wrapperSize = sizeClassMap[size];
if (type === "fiat" && FIAT_FLAG_CODES.has(lowerCode)) {
return (
<span
className={cn(
"inline-flex items-center justify-center overflow-hidden rounded-full border border-border/70 bg-background/60 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]",
wrapperSize,
className
)}
aria-hidden
>
<span
className={`currency-flag currency-flag-${lowerCode}`}
style={{
width: "100%",
height: "100%",
backgroundSize: "cover",
backgroundPosition: "center"
}}
/>
</span>
);
}
if (type === "crypto" && !cryptoMissing) {
return (
<img
src={`/icons/crypto/${lowerCode}.png`}
alt=""
aria-hidden
className={cn("rounded-full object-cover", wrapperSize, className)}
onError={() => setCryptoMissing(true)}
/>
);
}
return (
<span
className={cn(
"inline-flex items-center justify-center rounded-full border border-border/70 bg-muted text-[10px] font-semibold uppercase text-muted-foreground",
wrapperSize,
className
)}
aria-hidden
>
{code.slice(0, 2)}
</span>
);
}

View File

@@ -0,0 +1,193 @@
"use client";
import { useMemo, useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { POPULAR_CODES } from "@/lib/assets";
import { RateAsset } from "@/lib/rates";
import { cn } from "@/lib/utils";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
interface CurrencySelectProps {
value: string;
onChange: (nextCode: string) => void;
assets: RateAsset[];
label: string;
disabled?: boolean;
}
function AssetLabel({ asset }: { asset?: RateAsset }) {
if (!asset) {
return (
<span className="text-sm text-muted-foreground">Choose currency</span>
);
}
return (
<span className="flex min-w-0 items-center gap-2.5 text-left">
<CurrencyIcon code={asset.code} type={asset.type} size="md" className="shrink-0" />
<span className="flex min-w-0 flex-col">
<span className="truncate text-sm font-medium text-foreground">
{asset.code} - {asset.name}
</span>
<span className="truncate text-xs text-muted-foreground">
{asset.type === "fiat" ? "Fiat" : "Crypto"}
{asset.symbol ? ` | ${asset.symbol}` : ""}
</span>
</span>
</span>
);
}
export function CurrencySelect({
value,
onChange,
assets,
label,
disabled
}: CurrencySelectProps) {
const [open, setOpen] = useState(false);
const selectedAsset = useMemo(
() => assets.find((asset) => asset.code === value),
[assets, value]
);
const popularAssets = useMemo(
() =>
POPULAR_CODES.map((code) => assets.find((asset) => asset.code === code)).filter(
(asset): asset is RateAsset => Boolean(asset)
),
[assets]
);
const allAssets = useMemo(() => {
const popularSet = new Set(popularAssets.map((asset) => asset.code));
return assets
.filter((asset) => !popularSet.has(asset.code))
.sort((a, b) => {
if (a.type !== b.type) {
return a.type === "fiat" ? -1 : 1;
}
return a.code.localeCompare(b.code);
});
}, [assets, popularAssets]);
return (
<div className="space-y-2">
<p className="text-xs uppercase tracking-[0.14em] text-muted-foreground">
{label}
</p>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
disabled={disabled}
className="h-auto w-full justify-between rounded-xl border-border/70 px-3 py-2.5"
>
<AssetLabel asset={selectedAsset} />
<ChevronDown className="ml-2 h-4 w-4 shrink-0 text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
<Command>
<CommandInput placeholder="Search by code or name..." />
<CommandList>
<CommandEmpty>No assets found.</CommandEmpty>
{popularAssets.length > 0 ? (
<CommandGroup heading="Popular">
{popularAssets.map((asset) => (
<CommandItem
key={asset.code}
value={`${asset.code} ${asset.name} ${asset.type}`}
onSelect={() => {
onChange(asset.code);
setOpen(false);
}}
>
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<CurrencyIcon
code={asset.code}
type={asset.type}
size="md"
className="shrink-0"
/>
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">
{asset.code} - {asset.name}
</span>
<span className="truncate text-xs text-muted-foreground">
{asset.type === "fiat" ? "Fiat" : "Crypto"}
{asset.symbol ? ` | ${asset.symbol}` : ""}
</span>
</span>
</div>
<Check
className={cn(
"ml-2 h-4 w-4",
value === asset.code ? "opacity-100" : "opacity-0"
)}
/>
</CommandItem>
))}
</CommandGroup>
) : null}
{allAssets.length > 0 ? <CommandSeparator /> : null}
<CommandGroup heading="All assets">
{allAssets.map((asset) => (
<CommandItem
key={asset.code}
value={`${asset.code} ${asset.name} ${asset.type}`}
onSelect={() => {
onChange(asset.code);
setOpen(false);
}}
>
<div className="flex min-w-0 flex-1 items-center gap-2.5">
<CurrencyIcon
code={asset.code}
type={asset.type}
size="md"
className="shrink-0"
/>
<span className="flex min-w-0 flex-col">
<span className="truncate font-medium">
{asset.code} - {asset.name}
</span>
<span className="truncate text-xs text-muted-foreground">
{asset.type === "fiat" ? "Fiat" : "Crypto"}
{asset.symbol ? ` | ${asset.symbol}` : ""}
</span>
</span>
</div>
<Check
className={cn(
"ml-2 h-4 w-4",
value === asset.code ? "opacity-100" : "opacity-0"
)}
/>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}

View File

@@ -0,0 +1,23 @@
import { Badge } from "@/components/ui/badge";
export function Hero() {
return (
<section className="relative pt-10 sm:pt-14">
<div className="mx-auto max-w-3xl text-center">
<Badge
variant="outline"
className="border-cyan-400/40 bg-cyan-400/10 px-3 py-1 text-cyan-200"
>
Real-time fiat and crypto conversion
</Badge>
<h1 className="mt-5 text-balance font-heading text-4xl font-semibold leading-tight tracking-tight text-foreground sm:text-5xl lg:text-6xl">
Convert Global Currencies and Crypto in One Premium Workspace
</h1>
<p className="mx-auto mt-4 max-w-2xl text-balance text-base text-muted-foreground sm:text-lg">
Instantly switch between fiat and digital assets with live rates, smart
formatting, and a clean professional interface built for speed.
</p>
</div>
</section>
);
}

View File

@@ -0,0 +1,145 @@
"use client";
import { ArrowRightLeft, Landmark, Layers, MoveRight, Workflow } from "lucide-react";
import { CurrencyIcon } from "@/components/converter/currency-icon";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { AssetType } from "@/lib/assets";
import { cn } from "@/lib/utils";
interface PopularPair {
from: string;
to: string;
fromType: AssetType;
toType: AssetType;
}
const popularPairs: PopularPair[] = [
{ from: "USD", to: "PLN", fromType: "fiat", toType: "fiat" },
{ from: "EUR", to: "GBP", fromType: "fiat", toType: "fiat" },
{ from: "USD", to: "BTC", fromType: "fiat", toType: "crypto" },
{ from: "BTC", to: "USD", fromType: "crypto", toType: "fiat" },
{ from: "ETH", to: "SOL", fromType: "crypto", toType: "crypto" },
{ from: "XMR", to: "BTC", fromType: "crypto", toType: "crypto" },
{ from: "LTC", to: "BTC", fromType: "crypto", toType: "crypto" },
{ from: "CHF", to: "JPY", fromType: "fiat", toType: "fiat" }
];
const howItWorks = [
"Fiat rates are fetched from Frankfurter with USD as the common quote.",
"Crypto prices are fetched from CoinGecko in USD.",
"Any pair is converted through normalized USD-per-unit pricing."
];
const supportedAssets = [
{
title: "Fiat currencies",
description:
"Supports a broad list of global government-issued currencies, including major and regional pairs."
},
{
title: "Cryptocurrencies",
description:
"Includes leading crypto assets such as BTC, ETH, LTC, XMR, SOL, USDT, and more."
},
{
title: "Cross-market pairs",
description:
"Convert fiat-to-crypto, crypto-to-fiat, and crypto-to-crypto in one unified experience."
}
];
interface InsightsSectionProps {
selectedFromCode: string;
selectedToCode: string;
onSelectPopularPair: (fromCode: string, toCode: string) => void;
}
export function InsightsSection({
selectedFromCode,
selectedToCode,
onSelectPopularPair
}: InsightsSectionProps) {
return (
<section className="mt-10 grid gap-5 lg:grid-cols-3">
<Card className="border-border/70 bg-card/85">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-lg">
<ArrowRightLeft className="h-4 w-4 text-sky-300" />
Popular conversions
</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap gap-2 pt-0">
{popularPairs.map((pair) => {
const isActive =
pair.from === selectedFromCode && pair.to === selectedToCode;
return (
<Button
key={`${pair.from}-${pair.to}`}
type="button"
variant="outline"
size="sm"
onClick={() => onSelectPopularPair(pair.from, pair.to)}
className={cn(
"h-9 rounded-full border-border/70 bg-background/50 px-3.5 font-normal transition-all",
"hover:border-cyan-400/40 hover:bg-cyan-400/10 hover:text-cyan-100",
isActive &&
"border-cyan-400/50 bg-cyan-400/15 text-cyan-100 shadow-[0_0_0_1px_hsl(189_100%_40%_/_0.2)]"
)}
>
<span className="inline-flex items-center gap-1.5 text-xs sm:text-sm">
<CurrencyIcon code={pair.from} type={pair.fromType} size="sm" />
<span>{pair.from}</span>
<MoveRight className="h-3.5 w-3.5 text-cyan-300" />
<CurrencyIcon code={pair.to} type={pair.toType} size="sm" />
<span>{pair.to}</span>
</span>
</Button>
);
})}
</CardContent>
</Card>
<Card className="border-border/70 bg-card/85">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-lg">
<Workflow className="h-4 w-4 text-cyan-300" />
How it works
</CardTitle>
</CardHeader>
<CardContent className="space-y-3 pt-0 text-sm text-muted-foreground">
{howItWorks.map((line) => (
<p key={line} className="rounded-lg border border-border/60 bg-background/40 px-3 py-2">
{line}
</p>
))}
</CardContent>
</Card>
<Card className="border-border/70 bg-card/85">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-lg">
<Layers className="h-4 w-4 text-emerald-300" />
Supported asset types
</CardTitle>
</CardHeader>
<CardContent className="space-y-3 pt-0 text-sm">
{supportedAssets.map((item) => (
<div
key={item.title}
className="rounded-lg border border-border/60 bg-background/40 px-3 py-2"
>
<p className="flex items-center gap-2 font-medium text-foreground">
<Landmark className="h-3.5 w-3.5 text-muted-foreground" />
{item.title}
</p>
<p className="mt-1 text-muted-foreground">{item.description}</p>
</div>
))}
</CardContent>
</Card>
</section>
);
}

30
components/ui/badge.tsx Normal file
View File

@@ -0,0 +1,30 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors",
{
variants: {
variant: {
default: "border-transparent bg-primary/20 text-primary",
secondary: "border-transparent bg-secondary text-secondary-foreground",
outline: "border-border text-foreground"
}
},
defaultVariants: {
variant: "default"
}
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
}
export { Badge, badgeVariants };

55
components/ui/button.tsx Normal file
View File

@@ -0,0 +1,55 @@
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:scale-[0.99]",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/85",
ghost: "hover:bg-accent hover:text-accent-foreground",
outline:
"border border-border bg-background/70 backdrop-blur hover:bg-accent hover:text-accent-foreground"
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-lg px-8",
icon: "h-10 w-10"
}
},
defaultVariants: {
variant: "default",
size: "default"
}
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = "Button";
export { Button, buttonVariants };

72
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,72 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-2xl border border-border/70 bg-card/85 text-card-foreground shadow-card backdrop-blur-xl",
className
)}
{...props}
/>
));
Card.displayName = "Card";
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<
HTMLHeadingElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };

116
components/ui/command.tsx Normal file
View File

@@ -0,0 +1,116 @@
"use client";
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
"flex h-full w-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground",
className
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b border-border px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 text-muted-foreground" />
<CommandPrimitive.Input
ref={ref}
className={cn(
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn("max-h-[280px] overflow-y-auto overflow-x-hidden", className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-8 text-center text-sm text-muted-foreground"
{...props}
/>
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
"overflow-hidden p-1.5 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:uppercase [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:text-muted-foreground",
className
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-pointer select-none items-center rounded-md px-2 py-2.5 text-sm outline-none transition-colors data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",
className
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
export {
Command,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandSeparator
};

24
components/ui/input.tsx Normal file
View File

@@ -0,0 +1,24 @@
import * as React from "react";
import { cn } from "@/lib/utils";
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-lg border border-input bg-background/60 px-3 py-2 text-sm text-foreground shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };

31
components/ui/popover.tsx Normal file
View File

@@ -0,0 +1,31 @@
"use client";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/utils";
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 10, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-xl border border-border bg-popover p-0 text-popover-foreground shadow-glow outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };

View File

@@ -0,0 +1,28 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.HTMLAttributes<HTMLDivElement> & {
orientation?: "horizontal" | "vertical";
decorative?: boolean;
}) {
return (
<div
role={decorative ? "none" : "separator"}
aria-orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-px w-full" : "h-full w-px",
className
)}
{...props}
/>
);
}
export { Separator };

View File

@@ -0,0 +1,17 @@
import type * as React from "react";
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn(
"animate-shimmer rounded-md bg-gradient-to-r from-muted/60 via-muted to-muted/60 bg-[length:200%_100%]",
className
)}
{...props}
/>
);
}
export { Skeleton };

View File

@@ -0,0 +1,19 @@
"use client";
import { useEffect, useState } from "react";
export function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = window.setTimeout(() => {
setDebounced(value);
}, delayMs);
return () => {
window.clearTimeout(id);
};
}, [value, delayMs]);
return debounced;
}

89
hooks/use-market-rates.ts Normal file
View File

@@ -0,0 +1,89 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { parseRatesResponse, RatesResponse } from "@/lib/rates";
const REFRESH_INTERVAL_MS = 60_000;
function buildApiUrl(path: string): string {
const base = process.env.NEXT_PUBLIC_API_BASE_URL?.trim();
if (!base) {
return path;
}
return `${base.replace(/\/$/, "")}${path}`;
}
export function useMarketRates() {
const [data, setData] = useState<RatesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const fetchRates = useCallback(async () => {
try {
const response = await fetch(buildApiUrl("/api/rates"));
if (!response.ok) {
const payload = (await response.json().catch(() => null)) as {
message?: string;
} | null;
throw new Error(
payload?.message ?? "Unable to fetch latest market rates",
);
}
const payload = await response.json();
const parsed = parseRatesResponse(payload);
setData(parsed);
setError(null);
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
setError(message);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
void fetchRates();
const tick = () => {
if (document.visibilityState === "visible") {
void fetchRates();
}
};
const id = window.setInterval(() => {
tick();
}, REFRESH_INTERVAL_MS);
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
void fetchRates();
}
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
window.clearInterval(id);
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [fetchRates]);
const state = useMemo(
() => ({
data,
error,
isLoading,
refresh: fetchRates,
}),
[data, error, isLoading, fetchRates],
);
return state;
}

66
lib/api/crypto.ts Normal file
View File

@@ -0,0 +1,66 @@
import { CRYPTO_ASSETS } from "@/lib/assets";
export interface CryptoRateResult {
usdPrices: Record<string, number>;
updatedAt: string;
}
const COINGECKO_BASE_URL = "https://api.coingecko.com/api/v3";
export async function fetchCryptoData(): Promise<CryptoRateResult> {
const ids = CRYPTO_ASSETS.map((asset) => asset.providerId).filter(
(id): id is string => Boolean(id)
);
const url = `${COINGECKO_BASE_URL}/simple/price?ids=${encodeURIComponent(
ids.join(",")
)}&vs_currencies=usd&include_last_updated_at=true`;
const response = await fetch(url, {
next: { revalidate: 60 },
headers: {
accept: "application/json"
}
});
if (!response.ok) {
throw new Error(`Unable to load crypto rates (${response.status})`);
}
const payload = (await response.json()) as Record<
string,
{
usd?: number;
last_updated_at?: number;
}
>;
const usdPrices: Record<string, number> = {};
let mostRecentUpdate = 0;
for (const asset of CRYPTO_ASSETS) {
if (!asset.providerId) {
continue;
}
const entry = payload[asset.providerId];
if (!entry?.usd || entry.usd <= 0) {
continue;
}
usdPrices[asset.code] = entry.usd;
if (entry.last_updated_at && entry.last_updated_at > mostRecentUpdate) {
mostRecentUpdate = entry.last_updated_at;
}
}
return {
usdPrices,
updatedAt:
mostRecentUpdate > 0
? new Date(mostRecentUpdate * 1000).toISOString()
: new Date().toISOString()
};
}

43
lib/api/fiat.ts Normal file
View File

@@ -0,0 +1,43 @@
export interface FiatRateResult {
currencyNames: Record<string, string>;
usdRates: Record<string, number>;
updatedAt: string;
}
const FRANKFURTER_BASE_URL = "https://api.frankfurter.app";
export async function fetchFiatData(): Promise<FiatRateResult> {
const [currenciesRes, latestRes] = await Promise.all([
fetch(`${FRANKFURTER_BASE_URL}/currencies`, {
next: { revalidate: 60 }
}),
fetch(`${FRANKFURTER_BASE_URL}/latest?from=USD`, {
next: { revalidate: 60 }
})
]);
if (!currenciesRes.ok) {
throw new Error(`Unable to load fiat currency names (${currenciesRes.status})`);
}
if (!latestRes.ok) {
throw new Error(`Unable to load fiat rates (${latestRes.status})`);
}
const currencyNames = (await currenciesRes.json()) as Record<string, string>;
const latest = (await latestRes.json()) as {
date: string;
rates: Record<string, number>;
};
const usdRates: Record<string, number> = {
USD: 1,
...latest.rates
};
return {
currencyNames,
usdRates,
updatedAt: new Date(`${latest.date}T00:00:00Z`).toISOString()
};
}

58
lib/api/normalize.ts Normal file
View File

@@ -0,0 +1,58 @@
import { buildAllAssets } from "@/lib/assets";
import { fetchCryptoData } from "@/lib/api/crypto";
import { fetchFiatData } from "@/lib/api/fiat";
import { RateAsset, RatesResponse } from "@/lib/rates";
function normalizeFiatUsdPrice(usdRate: number): number {
return 1 / usdRate;
}
export async function fetchUnifiedRates(): Promise<RatesResponse> {
const [fiat, crypto] = await Promise.all([fetchFiatData(), fetchCryptoData()]);
const assetDefinitions = buildAllAssets(fiat.currencyNames);
const assets: RateAsset[] = [];
for (const asset of assetDefinitions) {
if (asset.type === "fiat") {
const usdRate = fiat.usdRates[asset.code];
if (!usdRate || usdRate <= 0) {
continue;
}
assets.push({
...asset,
usdPrice: normalizeFiatUsdPrice(usdRate),
updatedAt: fiat.updatedAt
});
continue;
}
const usdPrice = crypto.usdPrices[asset.code];
if (!usdPrice || usdPrice <= 0) {
continue;
}
assets.push({
...asset,
usdPrice,
updatedAt: crypto.updatedAt
});
}
const fiatUpdated = new Date(fiat.updatedAt).getTime();
const cryptoUpdated = new Date(crypto.updatedAt).getTime();
return {
assets,
quoteCurrency: "USD",
updatedAt: new Date(Math.max(fiatUpdated, cryptoUpdated)).toISOString(),
sources: {
fiat: "Frankfurter",
crypto: "CoinGecko"
}
};
}

133
lib/assets.ts Normal file
View File

@@ -0,0 +1,133 @@
export type AssetType = "fiat" | "crypto";
export interface AssetDefinition {
code: string;
name: string;
type: AssetType;
symbol?: string;
providerId?: string;
popular?: boolean;
decimals?: number;
}
export const POPULAR_CODES = [
"USD",
"EUR",
"GBP",
"PLN",
"CHF",
"JPY",
"BTC",
"ETH",
"LTC",
"XMR",
"SOL",
"USDT"
] as const;
export const POPULAR_CODE_SET = new Set<string>(POPULAR_CODES);
export const FALLBACK_FIAT_CURRENCIES: Record<string, { name: string; symbol?: string }> = {
USD: { name: "US Dollar", symbol: "$" },
EUR: { name: "Euro", symbol: "EUR" },
GBP: { name: "British Pound", symbol: "GBP" },
PLN: { name: "Polish Zloty", symbol: "PLN" },
CHF: { name: "Swiss Franc", symbol: "CHF" },
JPY: { name: "Japanese Yen", symbol: "JPY" },
CAD: { name: "Canadian Dollar", symbol: "CAD" },
AUD: { name: "Australian Dollar", symbol: "AUD" },
NZD: { name: "New Zealand Dollar", symbol: "NZD" },
SEK: { name: "Swedish Krona", symbol: "SEK" },
NOK: { name: "Norwegian Krone", symbol: "NOK" },
DKK: { name: "Danish Krone", symbol: "DKK" },
CZK: { name: "Czech Koruna", symbol: "CZK" },
HUF: { name: "Hungarian Forint", symbol: "HUF" },
RON: { name: "Romanian Leu", symbol: "RON" },
BGN: { name: "Bulgarian Lev", symbol: "BGN" },
CNY: { name: "Chinese Yuan", symbol: "CNY" },
HKD: { name: "Hong Kong Dollar", symbol: "HKD" },
SGD: { name: "Singapore Dollar", symbol: "SGD" },
INR: { name: "Indian Rupee", symbol: "INR" },
KRW: { name: "South Korean Won", symbol: "KRW" },
TRY: { name: "Turkish Lira", symbol: "TRY" },
BRL: { name: "Brazilian Real", symbol: "BRL" },
MXN: { name: "Mexican Peso", symbol: "MXN" },
ZAR: { name: "South African Rand", symbol: "ZAR" },
AED: { name: "UAE Dirham", symbol: "AED" },
SAR: { name: "Saudi Riyal", symbol: "SAR" },
ILS: { name: "Israeli New Shekel", symbol: "ILS" },
THB: { name: "Thai Baht", symbol: "THB" },
MYR: { name: "Malaysian Ringgit", symbol: "MYR" },
IDR: { name: "Indonesian Rupiah", symbol: "IDR" }
};
export const CRYPTO_ASSETS: AssetDefinition[] = [
{ code: "BTC", name: "Bitcoin", type: "crypto", providerId: "bitcoin", symbol: "BTC", popular: true, decimals: 8 },
{ code: "ETH", name: "Ethereum", type: "crypto", providerId: "ethereum", popular: true, decimals: 8 },
{ code: "LTC", name: "Litecoin", type: "crypto", providerId: "litecoin", popular: true, decimals: 8 },
{ code: "XMR", name: "Monero", type: "crypto", providerId: "monero", popular: true, decimals: 8 },
{ code: "SOL", name: "Solana", type: "crypto", providerId: "solana", popular: true, decimals: 8 },
{ code: "USDT", name: "Tether", type: "crypto", providerId: "tether", popular: true, decimals: 8 },
{ code: "BNB", name: "BNB", type: "crypto", providerId: "binancecoin", decimals: 8 },
{ code: "XRP", name: "XRP", type: "crypto", providerId: "ripple", decimals: 8 },
{ code: "USDC", name: "USD Coin", type: "crypto", providerId: "usd-coin", decimals: 8 },
{ code: "ADA", name: "Cardano", type: "crypto", providerId: "cardano", decimals: 8 },
{ code: "DOGE", name: "Dogecoin", type: "crypto", providerId: "dogecoin", decimals: 8 },
{ code: "TRX", name: "TRON", type: "crypto", providerId: "tron", decimals: 8 },
{ code: "DOT", name: "Polkadot", type: "crypto", providerId: "polkadot", decimals: 8 },
{ code: "AVAX", name: "Avalanche", type: "crypto", providerId: "avalanche-2", decimals: 8 },
{ code: "LINK", name: "Chainlink", type: "crypto", providerId: "chainlink", decimals: 8 },
{ code: "TON", name: "Toncoin", type: "crypto", providerId: "the-open-network", decimals: 8 },
{ code: "NEAR", name: "NEAR Protocol", type: "crypto", providerId: "near", decimals: 8 },
{ code: "ATOM", name: "Cosmos", type: "crypto", providerId: "cosmos", decimals: 8 },
{ code: "BCH", name: "Bitcoin Cash", type: "crypto", providerId: "bitcoin-cash", decimals: 8 },
{ code: "ALGO", name: "Algorand", type: "crypto", providerId: "algorand", decimals: 8 },
{ code: "MATIC", name: "Polygon", type: "crypto", providerId: "matic-network", decimals: 8 },
{ code: "ETC", name: "Ethereum Classic", type: "crypto", providerId: "ethereum-classic", decimals: 8 }
];
export function buildFiatAssets(
fiatCurrencies?: Record<string, string>
): AssetDefinition[] {
const source = fiatCurrencies && Object.keys(fiatCurrencies).length > 0
? fiatCurrencies
: Object.fromEntries(
Object.entries(FALLBACK_FIAT_CURRENCIES).map(([code, value]) => [code, value.name])
);
return Object.entries(source)
.map(([code, name]) => {
const fallback = FALLBACK_FIAT_CURRENCIES[code];
return {
code,
name: fallback?.name ?? name,
type: "fiat" as const,
symbol: fallback?.symbol,
popular: POPULAR_CODE_SET.has(code)
};
})
.sort((a, b) => a.code.localeCompare(b.code));
}
export function buildAllAssets(fiatCurrencies?: Record<string, string>): AssetDefinition[] {
return [...buildFiatAssets(fiatCurrencies), ...CRYPTO_ASSETS].sort((a, b) => {
if (a.popular && !b.popular) {
return -1;
}
if (!a.popular && b.popular) {
return 1;
}
if (a.type !== b.type) {
return a.type === "fiat" ? -1 : 1;
}
return a.code.localeCompare(b.code);
});
}
export function isPopularCode(code: string): boolean {
return POPULAR_CODE_SET.has(code);
}

50
lib/fiat-flag-codes.ts Normal file
View File

@@ -0,0 +1,50 @@
export const FIAT_FLAG_CODES = new Set<string>([
"aed",
"ars",
"aud",
"bdt",
"bgn",
"brl",
"cad",
"chf",
"clp",
"cny",
"cop",
"czk",
"dkk",
"eur",
"gbp",
"gel",
"hkd",
"hrk",
"huf",
"idr",
"inr",
"jmd",
"jpy",
"kes",
"krw",
"lkr",
"mad",
"mxn",
"myr",
"ngn",
"nok",
"npr",
"nzd",
"pen",
"php",
"pkr",
"pln",
"ron",
"rub",
"sar",
"sek",
"sgd",
"thb",
"try",
"uah",
"usd",
"vnd",
"zar"
]);

52
lib/format.ts Normal file
View File

@@ -0,0 +1,52 @@
import { RateAsset } from "@/lib/rates";
function trimTrailingZeroes(value: string): string {
return value.replace(/\.?0+$/, "");
}
export function formatAmount(value: number, asset: RateAsset): string {
if (!Number.isFinite(value)) {
return "-";
}
if (asset.type === "crypto") {
if (value === 0) {
return "0";
}
if (Math.abs(value) < 0.00000001) {
return "<0.00000001";
}
const precision = asset.decimals ?? 8;
const formatted = value.toLocaleString("en-US", {
minimumFractionDigits: value < 1 ? 4 : 2,
maximumFractionDigits: precision
});
return trimTrailingZeroes(formatted);
}
return value.toLocaleString("en-US", {
minimumFractionDigits: 2,
maximumFractionDigits: value < 1 ? 6 : 4
});
}
export function formatRate(from: RateAsset, to: RateAsset): string {
const rate = from.usdPrice / to.usdPrice;
return formatAmount(rate, to);
}
export function formatInverseRate(from: RateAsset, to: RateAsset): string {
const inverse = to.usdPrice / from.usdPrice;
return formatAmount(inverse, from);
}
export function formatTimestamp(value: string): string {
const date = new Date(value);
return new Intl.DateTimeFormat("en-US", {
dateStyle: "medium",
timeStyle: "short"
}).format(date);
}

55
lib/rates.ts Normal file
View File

@@ -0,0 +1,55 @@
import { z } from "zod";
import { AssetDefinition } from "@/lib/assets";
export interface RateAsset extends AssetDefinition {
usdPrice: number;
updatedAt: string;
}
export interface RatesResponse {
assets: RateAsset[];
quoteCurrency: "USD";
updatedAt: string;
sources: {
fiat: string;
crypto: string;
};
}
const rateAssetSchema = z.object({
code: z.string(),
name: z.string(),
type: z.enum(["fiat", "crypto"]),
symbol: z.string().optional(),
providerId: z.string().optional(),
popular: z.boolean().optional(),
decimals: z.number().optional(),
usdPrice: z.number().positive(),
updatedAt: z.string()
});
const ratesResponseSchema = z.object({
assets: z.array(rateAssetSchema),
quoteCurrency: z.literal("USD"),
updatedAt: z.string(),
sources: z.object({
fiat: z.string(),
crypto: z.string()
})
});
export function parseRatesResponse(payload: unknown): RatesResponse {
return ratesResponseSchema.parse(payload);
}
export function buildRateMap(assets: RateAsset[]): Map<string, RateAsset> {
return new Map(assets.map((asset) => [asset.code, asset]));
}
export function convertAmount(
amount: number,
fromAsset: RateAsset,
toAsset: RateAsset
): number {
return amount * (fromAsset.usdPrice / toAsset.usdPrice);
}

6
lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

26
lib/validation.ts Normal file
View File

@@ -0,0 +1,26 @@
import { z } from "zod";
export const amountSchema = z
.string()
.trim()
.min(1, "Enter an amount")
.refine((value) => !Number.isNaN(Number(value)), "Enter a valid number")
.transform((value) => Number(value))
.refine((value) => Number.isFinite(value), "Enter a valid number")
.refine((value) => value > 0, "Amount must be greater than zero")
.refine((value) => value <= 1_000_000_000_000, "Amount is too large");
export function validateAmount(amount: string):
| { ok: true; value: number }
| { ok: false; error: string } {
const result = amountSchema.safeParse(amount);
if (result.success) {
return { ok: true, value: result.data };
}
return {
ok: false,
error: result.error.issues[0]?.message ?? "Invalid amount"
};
}

5
next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.

6
next.config.mjs Normal file
View File

@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true
};
export default nextConfig;

6986
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@@ -0,0 +1,39 @@
{
"name": "nexcurrency",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"sync:crypto-icons": "mkdir -p public/icons/crypto && cp node_modules/cryptocurrency-icons/32/color/*.png public/icons/crypto/"
},
"dependencies": {
"@radix-ui/react-popover": "^1.1.2",
"@radix-ui/react-slot": "^1.1.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"cryptocurrency-icons": "^0.18.1",
"currency-flags": "github:vivekimsit/currency-flags",
"lucide-react": "^0.475.0",
"next": "^14.2.24",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwind-merge": "^2.5.5",
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"autoprefixer": "^10.4.20",
"eslint": "^8.57.1",
"eslint-config-next": "^14.2.24",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.7.2"
}
}

6
postcss.config.mjs Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 886 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 661 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
public/icons/crypto/abt.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 622 B

BIN
public/icons/crypto/act.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 559 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 627 B

BIN
public/icons/crypto/ada.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
public/icons/crypto/add.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 709 B

BIN
public/icons/crypto/adx.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 692 B

BIN
public/icons/crypto/ae.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 666 B

BIN
public/icons/crypto/agi.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 667 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 773 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1008 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 957 B

BIN
public/icons/crypto/amb.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 771 B

BIN
public/icons/crypto/amp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 816 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 937 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

BIN
public/icons/crypto/ant.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 853 B

BIN
public/icons/crypto/ape.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 512 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 716 B

BIN
public/icons/crypto/arg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 967 B

BIN
public/icons/crypto/ark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 699 B

BIN
public/icons/crypto/arn.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1012 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

BIN
public/icons/crypto/ary.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 782 B

BIN
public/icons/crypto/ast.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 689 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

BIN
public/icons/crypto/atm.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 775 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 729 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 882 B

BIN
public/icons/crypto/bab.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 712 B

BIN
public/icons/crypto/bal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
public/icons/crypto/bat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 B

BIN
public/icons/crypto/bay.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 761 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
public/icons/crypto/bcc.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

BIN
public/icons/crypto/bcd.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 781 B

BIN
public/icons/crypto/bch.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 782 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 746 B

BIN
public/icons/crypto/bcn.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 669 B

BIN
public/icons/crypto/bco.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 879 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

BIN
public/icons/crypto/bdl.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 692 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 750 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

BIN
public/icons/crypto/bix.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 749 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 324 B

BIN
public/icons/crypto/blk.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 848 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 693 B

BIN
public/icons/crypto/blz.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 909 B

BIN
public/icons/crypto/bnb.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 421 B

Some files were not shown because too many files have changed in this diff Show More