@toolpal/currency-convert
publicv2.0published 1 download this weekMIT
Converts an amount between currencies at today's (or a past day's) official European Central Bank reference rates. Covers about 30 major currencies (USD, EUR, GBP, INR, JPY, CNY, AUD, CAD, CHF, ...), with history back to 1999. No API key needed.
import { defineTool, Type } from "@toolpal/tool";
const CODE = "^[A-Za-z]{3}$";
const ZERO_DECIMAL = new Set(["JPY", "KRW", "ISK", "HUF", "IDR"]);
function assertValidCalendarDate(date: string): void {
const m = date.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (!m) throw new Error(`Invalid date "${date}". Use YYYY-MM-DD.`);
const year = Number(m[1]);
const month = Number(m[2]);
const day = Number(m[3]);
const d = new Date(Date.UTC(year, month - 1, day));
if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day) {
throw new Error(`"${date}" is not a real calendar date.`);
}
if (date < "1999-01-04") {
throw new Error(`No rates are available for ${date}; ECB history starts on 1999-01-04.`);
}
}
function roundAmount(value: number, currency: string): number {
if (value === 0) return 0;
if (ZERO_DECIMAL.has(currency) && Math.abs(value) >= 1) return Math.round(value);
if (Math.abs(value) >= 0.01) return Math.round(value * 100) / 100;
return Number(value.toPrecision(4));
}
async function frankfurter(path: string): Promise<Record<string, unknown> | null> {
const res = await fetch(`https://api.frankfurter.dev/v1/${path}`, {
headers: { accept: "application/json" },
signal: AbortSignal.timeout(12_000),
});
if (res.status === 404) return null;
if (!res.ok) throw new Error(`The exchange-rate service returned HTTP ${res.status}.`);
return (await res.json()) as Record<string, unknown>;
}
export default defineTool({
description:
"Converts an amount between currencies at today's (or a past day's) official European Central Bank reference rates. Covers about 30 major currencies (USD, EUR, GBP, INR, JPY, CNY, AUD, CAD, CHF, ...), with history back to 1999. No API key needed.",
input: Type.Object({
amount: Type.Optional(
Type.Number({ minimum: 0, description: "Amount in the source currency, 1 by default" }),
),
from: Type.String({
pattern: CODE,
description: "ISO 4217 code of the source currency, e.g. USD",
}),
to: Type.Array(Type.String({ pattern: CODE }), {
minItems: 1,
maxItems: 30,
description: 'Target currency codes, e.g. ["EUR", "INR"]',
}),
date: Type.Optional(
Type.String({
pattern: "^\\d{4}-\\d{2}-\\d{2}$",
description: "Use the rates of this day (YYYY-MM-DD); latest by default",
}),
),
}),
output: Type.Object({
amount: Type.Number(),
from: Type.String(),
rateDate: Type.String({
description:
"The business day the rates were published; weekends and holidays fall back to the day before",
}),
conversions: Type.Array(
Type.Object({ currency: Type.String(), rate: Type.Number(), amount: Type.Number() }),
),
source: Type.String(),
}),
examples: [
{
title: "Convert USD to EUR, INR, and JPY",
input: {
amount: 250,
from: "USD",
to: ["EUR", "INR", "JPY"],
},
},
],
handler: async ({ amount = 1, from, to, date }) => {
if (date) assertValidCalendarDate(date);
const base = from.toUpperCase();
const targets = [...new Set(to.map((c) => c.toUpperCase()))];
const others = targets.filter((c) => c !== base);
if (others.length === 0) {
const supported = Object.keys((await frankfurter("currencies")) ?? {});
if (!supported.includes(base)) {
throw new Error(
`Not covered by ECB reference rates: ${base}. Supported: ${supported.join(", ")}.`,
);
}
return {
amount,
from: base,
rateDate: date ?? new Date().toISOString().slice(0, 10),
conversions: [{ currency: base, rate: 1, amount: roundAmount(amount, base) }],
source: "European Central Bank reference rates, via frankfurter.dev",
};
}
const data = (await frankfurter(`${date ?? "latest"}?from=${base}&to=${others.join(",")}`)) as {
date?: string;
rates?: Record<string, number>;
} | null;
const rates: Record<string, number> = { ...(data?.rates ?? {}), [base]: 1 };
if (!data || targets.some((c) => rates[c] === undefined)) {
const supported = Object.keys((await frankfurter("currencies")) ?? {});
const unknown = [base, ...others].filter((c) => !supported.includes(c));
throw new Error(
unknown.length
? `Not covered by ECB reference rates: ${unknown.join(", ")}. Supported: ${supported.join(", ")}.`
: `No rates are available for ${date}; history starts on 1999-01-04.`,
);
}
return {
amount,
from: base,
rateDate: data.date ?? date ?? new Date().toISOString().slice(0, 10),
conversions: targets.map((currency) => ({
currency,
rate: rates[currency],
amount: roundAmount(amount * rates[currency], currency),
})),
source: "European Central Bank reference rates, via frankfurter.dev",
};
},
});