Build a Telegram bot that quotes cross-chain swaps
Complete grammY Telegram bot that quotes a swap with the LayerHop API and replies with a prefilled swap link, so users sign in their own wallet. Non-custodial, about 80 lines.
This recipe builds your own Telegram bot with grammY. A user sends /quote 100 USDC base solana SOL; the bot calls the LayerHop API (GET /v1/quote), shows the best route, the minimum received, the ETA and the fee, and replies with a button that opens a prefilled swap on layerhop.com. The bot holds no keys and signs nothing: the user connects a wallet on the web page.
Looking for the ready-made bot instead? Use @layerhop_bot.
What do I need first?#
- A bot token from @BotFather, stored as
BOT_TOKEN. - Node 20+ and
npm i grammy. - Optional:
LAYERHOP_API_KEY(dashboard) and your partner id inLAYERHOP_INTEGRATORto earn a partner fee on the swaps your bot sends.
1. Write the bot#
// bot.ts (run: BOT_TOKEN=... npx tsx bot.ts)
import { Bot, InlineKeyboard } from "grammy";
const API = "https://api.layerhop.com/v1";
const INTEGRATOR = process.env.LAYERHOP_INTEGRATOR; // optional partner id, [a-z0-9-]{1,32}
const headers: Record<string, string> = process.env.LAYERHOP_API_KEY ? { "x-api-key": process.env.LAYERHOP_API_KEY } : {};
async function api(path: string, params: Record<string, string>) {
const res = await fetch(`${API}/${path}?${new URLSearchParams(params)}`, { headers });
const body: any = await res.json();
if (!res.ok) throw new Error(body.error?.message ?? `HTTP ${res.status}`);
return body;
}
async function decimalsOf(chain: string, symbol: string): Promise<number> {
const { tokens } = await api("tokens", { chain, q: symbol, limit: "5" });
const t = tokens.find((x: any) => x.symbol.toLowerCase() === symbol.toLowerCase());
if (!t) throw new Error(`I do not know ${symbol} on ${chain}. Try /help.`);
return t.decimals;
}
/** "100.5" with 6 decimals gives "100500000" (integer math, no floats). */
function toBaseUnits(amount: string, decimals: number): string {
const m = /^(\d+)(?:\.(\d+))?$/.exec(amount);
if (!m || (m[2]?.length ?? 0) > decimals) throw new Error("Invalid amount");
return (BigInt(m[1]!) * 10n ** BigInt(decimals) + BigInt((m[2] ?? "").padEnd(decimals, "0") || "0")).toString();
}
const bot = new Bot(process.env.BOT_TOKEN!);
bot.command(["start", "help"], (ctx) =>
ctx.reply("Usage: /quote <amount> <token> <from chain> <to chain> <to token>\nExample: /quote 100 USDC base solana SOL\nI only quote. You sign in your own wallet."));
bot.command("quote", async (ctx) => {
const [amount, srcToken, srcChain, dstChain, dstToken] = ctx.match.trim().split(/\s+/);
if (!dstToken) return ctx.reply("Example: /quote 100 USDC base solana SOL");
try {
// Telegram has no wallet address, and the quote needs a sender and a recipient of the right VM.
// For an indicative quote use well-known placeholder addresses; the swap page asks for the real wallet.
const evm = "0x1111111111111111111111111111111111111111";
const sol = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
const addr = (chain: string) => (chain.toLowerCase() === "solana" ? sol : evm);
const [srcDec, dstDec] = await Promise.all([decimalsOf(srcChain!, srcToken!), decimalsOf(dstChain!, dstToken)]);
const { best } = await api("quote", {
srcChain: srcChain!, srcToken: srcToken!, amount: toBaseUnits(amount!, srcDec),
dstChain, dstToken, sender: addr(srcChain!), recipient: addr(dstChain),
...(INTEGRATOR ? { integrator: INTEGRATOR } : {}),
});
const human = (v: string) => (Number(BigInt(v)) / 10 ** dstDec).toLocaleString("en-US", { maximumFractionDigits: 6 });
const link = `https://layerhop.com/swap?${new URLSearchParams({
srcChain: srcChain!, srcToken: srcToken!, dstChain, dstToken, amount: amount!,
...(INTEGRATOR ? { integrator: INTEGRATOR } : {}),
})}`;
await ctx.reply(
`${amount} ${srcToken} on ${srcChain} to ${dstToken} on ${dstChain}\n` +
`You receive about ${human(best.dstAmount)} ${dstToken} (at least ${human(best.dstAmountMin)})\n` +
`Route: ${best.provider}, about ${best.estimatedSeconds}s\n` +
`LayerHop fee: ${(best.fees.ourFeeBps / 100).toFixed(2)}%\n` +
`This is indicative: the live quote is shown before you sign.`,
{ reply_markup: new InlineKeyboard().url("Swap in your wallet", link) },
);
} catch (e) {
await ctx.reply(`Could not quote: ${(e as Error).message}`);
}
});
bot.start();How does it work?#
- The bot reads
/quote <amount> <token> <from chain> <to chain> <to token>and looks up the tokens'decimalswithGET /v1/tokens(chain,q). - It converts the human amount to base units with integer math and calls
GET /v1/quotewithsrcChain,srcToken,amount,dstChain,dstToken,sender,recipientand the optionalintegrator. - It replies with
best.dstAmount,best.dstAmountMin,best.estimatedSecondsandbest.fees.ourFeeBps, plus an inline button with a deep link. Deep links take the amount in human units, and the app builds a fresh live quote for the connected wallet.
The quote uses placeholder addresses because the bot never learns a wallet. The route and price are indicative; the real transaction is built on the swap page when the user connects.
Which fee applies to links from my bot?#
A deep link without ref=bot uses the web channel (0.15%); ref=bot is reserved for LayerHop's own bot and uses the 0.45% bot channel. With your integrator id, your partner fee is added on top. See Fees and channels.
Can the bot execute the swap for the user?#
It should not. Custodying keys in a chat bot is risky and unnecessary: the link keeps signing in the user's own wallet (Non-custodial by design). To track an order after the user swaps, call GET /v1/orders/{provider}/{id} with the source transaction hash, or receive webhooks.
Why does the quote say NO_ROUTE or AMOUNT_TOO_SMALL?#
NO_ROUTE means no provider could serve that pair or amount; AMOUNT_TOO_SMALL carries the route's minimum. Both come back as an error message the bot relays. See the error catalog and Error handling.
Next: Telegram bot, Swap by reply, API reference.
Last updated