Early access · beta

Router API

Trade USDC, USDF or SOL for any Flipcash currency, or one currency for another, in a single transaction. JSON over HTTPS, from your server.

Building and sending need an API key. Request early access; we usually reply within a day or two. Quotes, the currency list and receipts work without one.

Request early access
On this page
Start here

What the Router does

The Router turns “swap this for that” into a ready-made Solana transaction. Your wallet signs it; the Router never signs and never holds funds. Every trade is five steps:

  1. Quote: what you pay and what you get.
  2. Build: an unsigned transaction for your wallet.
  3. Sign: with your wallet.
  4. Send: the Router sees it through to confirmation.
  5. Receipt: what happened, read from the chain.

Fees: calling the API is free. Buys carry up to 1%: the Router’s 0.5%, plus up to 0.5% that you set for yourself. Sells carry no Router fee, but Flipcash’s Reserve Contract keeps 1% of every sell, whoever builds it. A swap is a sell and a buy, so it carries both. Each of these fees is its own line in the quote; a SOL trade’s small pool fee is already inside its price (Fees).

Who signs depends on what you build:

  • A website or an app. Your server builds and sends; your user’s own wallet signs in the browser. Guide: A web app.
  • A bot or a backend. Your server holds its own wallet and signs. Guide: A server that trades.

Nothing moves until the wallet signs. The Router is in beta: see Safety and risks.

What you can trade

Any Flipcash currency, each trade in a single transaction:

Buy

Pay USDC, USDF or SOL and get a currency.

Sell

Pay a currency and get USDC, USDF or SOL. The Reserve Contract keeps 1%.

Swap

Trade one currency straight for another. The sell side pays Flipcash’s 1%.

Flipcash currencies

Vaults. Each Flipcash currency is a Solana token governed by Flipcash’s Reserve Contract. When a currency is created, its whole supply, a fixed 21 million coins, goes into the Reserve Contract. There the currency gets its own pool with two vaults: one holds the coins not yet sold, the other holds the USDF paid for them.

Liquidity. You buy from a currency’s pool and sell back to it. The pool always sells at the curve’s price and buys back with the USDF in its vault. So every currency can be traded from the day it is created, with no order book, market makers or liquidity providers.

Price. Every currency follows the same predefined curve: the first coin sells for $0.01, and the price rises about a cent for every $11,400 of coins bought. Selling moves it back down the same curve. A bigger trade moves further along the curve, and the quote’s priceImpactPct shows how far. Every sell pays the pool’s 1% sell fee. The Router doesn’t set prices: it reads each pool on chain when it quotes.

GET /tokens lists every currency the Router trades; Moony (MNY) is the one in our examples.

How the Router connects them

Every step runs in one transaction, in either direction. Your wallet signs once, and if any step would fail, none of it happens.

A swap sells the first currency for USDF and buys the second with it. SOL comes and goes as plain SOL, never a wrapped token.

USDF is Flipcash’s dollar: a US dollar stablecoin on Solana, created by Flipcash with Coinbase’s Custom Stablecoin platform and fully backed by USDC. It converts to and from USDC one for one.

The Router is built by Moonyversal and is independent of Flipcash and Coinbase.

Before you begin

You need an API key, a wallet, and a little USDC and SOL. A quote needs none of these, so you can try one first.

  1. Get an API key

    Request early access. Once approved, create a key at developer.moonyversal.com. Every key is live and moves real money, so test with $1 or less. Questions go to Moonyversal Dev, our developer group in the Flipcash app ($1 of any currency to join), or to contact@moonyversal.com.

  2. Set up a wallet

    Building a website? Your users sign with their own wallets, such as Phantom or Solflare; test with yours. Running a server? Make a wallet with Solana’s command-line tools (install guide), in the folder where you will keep the script:

    Terminal · wallet
    $ solana-keygen new --outfile wallet.json
    $ solana-keygen pubkey wallet.json
    

    The first makes the wallet; the second prints its address.

    wallet.json is the wallet’s private key. It stays on your machine and we never see it: keep it out of git (add it to .gitignore), back it up, and keep only what you trade in it (Anza’s guide).

  3. Fund it, on the Solana network

    Send the address about 2 USDC and 0.01 SOL. When you withdraw from an exchange, choose the Solana network: USDC sent on another network does not arrive. SOL pays the network fees (Fees). This is Solana mainnet, the tools’ default: skip any devnet or airdrop steps in the guides.

  4. Check that it arrived

    Look the address up on an explorer such as solscan.io, or run solana balance <address> and spl-token accounts --owner <address> (Anza’s guide, the SPL Token CLI).

Your first quote

A quote is a price check: what 5 USDF buys in Moony right now. Nothing moves, so it needs no key. Paste this into a terminal:

Terminal · quote
$ curl -G https://router.moonyversal.com/api/v2/quote \
    -d pay=USDF -d amount=5 \
    -d receive=4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6

expected is what you would get, min is the least the trade will accept, and each fee is its own line. Every field: Quote.

Your first trade

One script does the whole trade, for real: it spends 1 USDC on Moony. Copy it into a file named trade.mjs in an empty folder (Node 20 or later):

Show the scripttrade.mjs · 107 lines
trade.mjs
// trade.mjs: a server that trades on its own, with its own wallet.
// Node 20 or later, after `npm install @solana/web3.js@1.98.4 bs58@6`. Run it with:
//   ROUTER_KEY=mny_live_... WALLET_FILE=wallet.json node trade.mjs
// It buys $1 of Moony with USDC. PAY, RECEIVE and AMOUNT change the trade, for example
//   PAY=SOL AMOUNT=0.005 ...             pay 0.005 SOL instead
//   PAY=<a currency's mint> RECEIVE=USDC AMOUNT=<how much> ...   sell it back
// SLIPPAGE_BPS is how far below the quote you accept (default 50 = 0.5%).
// It exits 0 when the trade is confirmed, 1 when it did not happen, and 3 when the outcome is unknown: then look up the
// signature it printed before running it again.
import { existsSync, readFileSync } from "node:fs";
import { Keypair, Transaction, VersionedTransaction } from "@solana/web3.js";
import bs58 from "bs58";

const API = "https://router.moonyversal.com/api/v2";
const MNY = "4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6"; // Moony's mint

const { ROUTER_KEY, WALLET_FILE, PAY = "USDC", RECEIVE = MNY, AMOUNT = "1", SLIPPAGE_BPS = "50" } = process.env;
const slippageBps = Number(SLIPPAGE_BPS);
if (!Number.isInteger(slippageBps) || slippageBps < 0 || slippageBps > 500) throw new Error("SLIPPAGE_BPS must be a whole number from 0 to 500.");
if (!ROUTER_KEY || !WALLET_FILE) throw new Error("Set ROUTER_KEY to your key and WALLET_FILE to your wallet file (see Set up a wallet).");
if (!existsSync(WALLET_FILE)) throw new Error(`No wallet file at ${WALLET_FILE} (see Set up a wallet).`);
const headers = { authorization: `Bearer ${ROUTER_KEY}`, "content-type": "application/json" };
// Your wallet, a Solana keypair file. It signs here, on your machine.
const wallet = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(WALLET_FILE, "utf8"))));
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));

// Every response is JSON; an error carries { error, code, retryable, hint? }.
async function api(path, body) {
  const res = await fetch(API + path, { method: body ? "POST" : "GET", headers, body: body && JSON.stringify(body) });
  let json;
  try { json = await res.json(); } catch { json = { code: "bad_response", error: `HTTP ${res.status}, not JSON`, retryable: true }; }
  if (!res.ok) {
    const hint = json.hint ? ` ${json.hint}` : "";
    throw Object.assign(new Error(`${json.code}: ${json.error}${hint}`), { status: res.status, code: json.code, retryable: json.retryable });
  }
  return json;
}

// 1. Quote: what AMOUNT of PAY buys. Every key is live, so this script trades for real: start small.
const trade = { pay: PAY, receive: RECEIVE, amount: AMOUNT, slippageBps: String(slippageBps) };
const quote = await api(`/quote?${new URLSearchParams(trade)}`);
console.log(`Quote: ${quote.pay.amount} ${quote.pay.symbol} for about ${quote.receive.expected} ${quote.receive.symbol}`);

// 2. Build an unsigned transaction for your wallet. The Router prices the trade again and
//    simulates it as your wallet; build.quote is the price the transaction enforces.
const build = await api("/swap/build", { ...trade, slippageBps, wallet: wallet.publicKey.toBase58() });
if (build.simulation && !build.simulation.ok) throw new Error(build.simulation.message);
console.log(`Built: at least ${build.quote.receive.min} ${build.quote.receive.symbol}, or the trade fails`);
console.log(`Fees: ${build.quote.fees.map((f) => `${f.label} ${f.amount} ${f.asset}`).join(", ") || "none"}`);

// 3. Sign it yourself. The Router never sees your key. `format` says how to read the transaction.
const bytes = Buffer.from(build.transaction, "base64");
const tx = build.format === "v0" ? VersionedTransaction.deserialize(bytes) : Transaction.from(bytes);
// Never sign a transaction someone else pays for: its fee payer must be your wallet.
const payer = build.format === "v0" ? tx.message.staticAccountKeys[0] : tx.feePayer;
if (!payer?.equals(wallet.publicKey)) throw new Error("Not signing: the fee payer is not your wallet.");
let signature;
if (build.format === "v0") {
  tx.sign([wallet]);
  signature = bs58.encode(tx.signatures[0]);
} else {
  tx.sign(wallet);
  signature = bs58.encode(tx.signature);
}
const signedTransaction = Buffer.from(tx.serialize()).toString("base64");

// 4. Send it. This is the step that moves real money. You know its signature already.
console.log(`Sending ${signature}`);
// The give-up time for step 5: 3 minutes from now, on this machine's clock. A transaction expires 60 to 90 seconds
// after it was built, so one the network still does not know by then can no longer land.
const giveUpAt = Date.now() + 3 * 60_000;
try {
  const sent = await api("/swap/send", { signedTransaction });
  console.log(`Send: ${sent.status}`);
} catch (e) {
  // A 4xx response to this first send means the trade did not happen: fix the cause and build again.
  if (e.status >= 400 && e.status < 500) throw e;
  // Anything else (a timeout, a dropped connection, a 5xx) means it may still land.
  // Do not build again; the receipt below says what happened.
  console.log(`Send gave no clear answer (${e.message}). Checking the receipt.`);
}

// 5. Read the receipt. It can lag the send by a few seconds, so ask until it appears.
//    Still missing 3 minutes after you sent it: the transaction can no longer land.
const check = `curl ${API}/receipt/${signature}`;
for (;;) {
  try {
    const receipt = await api(`/receipt/${signature}`);
    console.log(receipt.status, JSON.stringify(receipt.swap));
    process.exit(receipt.status === "confirmed" ? 0 : 1); // "failed": it landed and reverted
  } catch (e) {
    const tryAgain = e.code === "not_found" || e.retryable || !e.status; // !e.status: the request itself failed
    if (!tryAgain) {
      console.log(`Could not read the receipt (${e.message}). Do not run this script again yet: check ${check}`);
      process.exit(3);
    }
    if (Date.now() > giveUpAt) {
      if (e.code === "not_found") {
        console.log("Not found 3 minutes after it was sent: this trade did not happen. You can build a new one.");
        process.exit(1);
      }
      console.log(`The receipt is still unreadable. Do not run this script again yet: check ${check}`);
      process.exit(3);
    }
    await sleep(3000);
  }
}

Then, in that folder:

Terminal · first trade
$ npm install @solana/web3.js@1.98.4 bs58@6
$ ROUTER_KEY=mny_live_... WALLET_FILE=wallet.json node trade.mjs

It prints the quote, the fees, the least it will accept, the signature it sends, and the receipt. Keep @solana/web3.js on version 1: ignore npm audit fix --force.

PAY, RECEIVE and AMOUNT change the trade (PAY=SOL AMOUNT=0.005, say). Step by step: A server that trades.

Safety and risks

The Router is in early access beta. It never holds a key or funds, and nothing moves until your wallet signs. Like any new software it carries risk. During early access there is no uptime promise, and we may pause trading. Start with small amounts, and keep your API key and your users’ wallets safe.

How trades are protected

  • Your wallet signs every trade. The Router builds unsigned transactions; only your wallet can approve them.
  • A minimum on every trade. It is enforced on chain, and every build is simulated as your wallet first.
  • Only trades built for your key. Send relays nothing else.
  • We never keep your key. We store only a fingerprint of it, and fee wallet changes are emailed to your organization’s owners.

Using the Router means agreeing to its terms. Found a security problem? Email contact@moonyversal.com.

Guides

A server that trades

trade.mjs from Your first trade, one step at a time. You set it with environment variables:

trade.mjs settings
VariableMeaning
ROUTER_KEYYour key. Required.
WALLET_FILEYour wallet file. Required.
PAY, RECEIVE, AMOUNTThe trade. Default: 1 USDC for Moony.
SLIPPAGE_BPSHow far below the quote you accept, 0 to 500. Default 50 (0.5%).
  1. Quote

    What AMOUNT of PAY buys right now.

    trade.mjs · 1 quote
    // 1. Quote: what AMOUNT of PAY buys. Every key is live, so this script trades for real: start small.
    const trade = { pay: PAY, receive: RECEIVE, amount: AMOUNT, slippageBps: String(slippageBps) };
    const quote = await api(`/quote?${new URLSearchParams(trade)}`);
    console.log(`Quote: ${quote.pay.amount} ${quote.pay.symbol} for about ${quote.receive.expected} ${quote.receive.symbol}`);
    
  2. Build

    An unsigned transaction for your wallet. If the wallet is short of something, the response says what.

    trade.mjs · 2 build
    // 2. Build an unsigned transaction for your wallet. The Router prices the trade again and
    //    simulates it as your wallet; build.quote is the price the transaction enforces.
    const build = await api("/swap/build", { ...trade, slippageBps, wallet: wallet.publicKey.toBase58() });
    if (build.simulation && !build.simulation.ok) throw new Error(build.simulation.message);
    console.log(`Built: at least ${build.quote.receive.min} ${build.quote.receive.symbol}, or the trade fails`);
    console.log(`Fees: ${build.quote.fees.map((f) => `${f.label} ${f.amount} ${f.asset}`).join(", ") || "none"}`);
    
  3. Sign

    On your machine, and only if the fee payer is your wallet. format says how to read the transaction (Sign).

    trade.mjs · 3 sign
    // 3. Sign it yourself. The Router never sees your key. `format` says how to read the transaction.
    const bytes = Buffer.from(build.transaction, "base64");
    const tx = build.format === "v0" ? VersionedTransaction.deserialize(bytes) : Transaction.from(bytes);
    // Never sign a transaction someone else pays for: its fee payer must be your wallet.
    const payer = build.format === "v0" ? tx.message.staticAccountKeys[0] : tx.feePayer;
    if (!payer?.equals(wallet.publicKey)) throw new Error("Not signing: the fee payer is not your wallet.");
    let signature;
    if (build.format === "v0") {
      tx.sign([wallet]);
      signature = bs58.encode(tx.signatures[0]);
    } else {
      tx.sign(wallet);
      signature = bs58.encode(tx.signature);
    }
    const signedTransaction = Buffer.from(tx.serialize()).toString("base64");
    
  4. Send

    A 4xx response means it did not happen; anything else, check the receipt (Did the trade happen?).

    trade.mjs · 4 send
    // 4. Send it. This is the step that moves real money. You know its signature already.
    console.log(`Sending ${signature}`);
    // The give-up time for step 5: 3 minutes from now, on this machine's clock. A transaction expires 60 to 90 seconds
    // after it was built, so one the network still does not know by then can no longer land.
    const giveUpAt = Date.now() + 3 * 60_000;
    try {
      const sent = await api("/swap/send", { signedTransaction });
      console.log(`Send: ${sent.status}`);
    } catch (e) {
      // A 4xx response to this first send means the trade did not happen: fix the cause and build again.
      if (e.status >= 400 && e.status < 500) throw e;
      // Anything else (a timeout, a dropped connection, a 5xx) means it may still land.
      // Do not build again; the receipt below says what happened.
      console.log(`Send gave no clear answer (${e.message}). Checking the receipt.`);
    }
    
  5. Read the receipt

    Ask until it appears, and give up 3 minutes after sending. The script exits 0 when the trade is confirmed, 1 when it did not happen, and 3 when the outcome is unknown.

    trade.mjs · 5 receipt
    // 5. Read the receipt. It can lag the send by a few seconds, so ask until it appears.
    //    Still missing 3 minutes after you sent it: the transaction can no longer land.
    const check = `curl ${API}/receipt/${signature}`;
    for (;;) {
      try {
        const receipt = await api(`/receipt/${signature}`);
        console.log(receipt.status, JSON.stringify(receipt.swap));
        process.exit(receipt.status === "confirmed" ? 0 : 1); // "failed": it landed and reverted
      } catch (e) {
        const tryAgain = e.code === "not_found" || e.retryable || !e.status; // !e.status: the request itself failed
        if (!tryAgain) {
          console.log(`Could not read the receipt (${e.message}). Do not run this script again yet: check ${check}`);
          process.exit(3);
        }
        if (Date.now() > giveUpAt) {
          if (e.code === "not_found") {
            console.log("Not found 3 minutes after it was sent: this trade did not happen. You can build a new one.");
            process.exit(1);
          }
          console.log(`The receipt is still unreadable. Do not run this script again yet: check ${check}`);
          process.exit(3);
        }
        await sleep(3000);
      }
    }
    

Moving funds out

Sell back to USDC with the script (PAY set to the currency’s mint, RECEIVE=USDC, AMOUNT set to what you hold), then move the USDC with spl-token transfer and the SOL with solana transfer (to a new address, add --fund-recipient and --allow-unfunded-recipient).

A web app

Your user’s wallet signs in the browser; your server holds the key and does the rest. Four rules:

  • Call the Router from your server. It does not answer browsers (no CORS), so your page talks to your server.
  • Serve the page over https, or from http://localhost while you build. Browser wallets connect only there.
  • Decide the trade on your server, and limit each visitor. Set the pair and the largest amount yourself; take only the wallet and the amount from the page. Your key’s limits are shared by all your visitors.
  • Show what the user gets and every fee, with the total, before they sign. That includes your partner fee, which the terms require, and Solana’s network fee. One trade at a time: wait for the result before offering another, even across a reload.

Connecting a wallet is the wallet’s own API: Phantom’s guide, Solflare’s docs. On a phone, visitors open your site in their wallet app’s browser.

Run it

Copy both files into an empty folder as server.mjs and index.html (Node 20 or later, nothing to install):

Show both filesserver.mjs · 88 linesindex.html · 126 lines
A web app in two files
// server.mjs: a web app's server. It holds the API key; the browser never sees it.
// Node 20 or later, nothing to install. Keep index.html next to it, then run:
//   ROUTER_KEY=mny_live_... node server.mjs        and open http://localhost:3000   (PORT=3001 to change the port)
// It listens on this machine only. To go live, serve it behind your own https site, and set TRUST_PROXY=1 there so
// each visitor is counted by the address your proxy adds (the last entry of X-Forwarded-For; earlier ones can be faked).
import { createServer } from "node:http";
import { readFileSync } from "node:fs";

const API = "https://router.moonyversal.com/api/v2";
const KEY = process.env.ROUTER_KEY;
const PORT = Number(process.env.PORT || 3000);
const TRUST_PROXY = process.env.TRUST_PROXY === "1";
// What this app trades, and how much: its own settings, never the visitor's. It buys Moony with USDC, up to $100.
const PAY = "USDC", RECEIVE = "4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6", MAX_AMOUNT = 100;
// How far below the quote a trade may land.
const SLIPPAGE_BPS = 50;
if (!KEY) throw new Error("Set ROUTER_KEY to your key.");
const page = readFileSync(new URL("./index.html", import.meta.url));

async function router(path, body) {
  const res = await fetch(API + path, {
    method: body ? "POST" : "GET",
    headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
    body: body && JSON.stringify(body),
  });
  let json;
  try { json = await res.json(); } catch { json = { error: `The Router answered HTTP ${res.status}.` }; }
  return { status: res.status, json };
}

// Your key's limits are shared by every visitor, so each visitor gets its own allowance here; receipts have their own,
// because a page asks for one every few seconds while a trade confirms.
const visits = new Map(); // "ip route" -> request times in the last minute
function allowed(ip, route) {
  const now = Date.now();
  for (const [k, times] of visits) if (now - times[times.length - 1] > 60_000) visits.delete(k);
  const key = `${ip} ${route}`;
  const recent = (visits.get(key) ?? []).filter((t) => now - t < 60_000);
  recent.push(now);
  visits.set(key, recent);
  return recent.length <= (route === "receipt" ? 60 : 20);
}
const readJson = (req) => new Promise((done) => {
  let s = "";
  req.on("data", (c) => { s += c; if (s.length > 100_000) req.destroy(); });
  req.on("end", () => { try { done(JSON.parse(s)); } catch { done({}); } });
});

createServer(async (req, res) => {
  const reply = (status, json) => {
    res.writeHead(status, { "content-type": "application/json" });
    res.end(JSON.stringify(json));
  };
  const url = new URL(req.url, "http://localhost");
  const ip = (TRUST_PROXY && String(req.headers["x-forwarded-for"] || "").split(",").pop().trim()) || req.socket.remoteAddress;
  try {
    if (req.method === "GET" && url.pathname === "/") {
      res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
      return res.end(page);
    }
    const route = url.pathname.split("/")[2];
    if (url.pathname.startsWith("/api/") && !allowed(ip, route)) return reply(429, { error: "Too many requests. Wait a minute." });
    // Build for the visitor's wallet. The visitor chooses only the wallet and the amount; the pair is this app's.
    if (req.method === "POST" && url.pathname === "/api/build") {
      const { wallet, amount } = await readJson(req);
      if (!/^\d+(\.\d{1,6})?$/.test(String(amount)) || !(Number(amount) > 0 && Number(amount) <= MAX_AMOUNT)) return reply(400, { error: `Enter an amount up to ${MAX_AMOUNT}.` });
      const { status, json } = await router("/swap/build", { wallet, pay: PAY, receive: RECEIVE, amount: String(amount), slippageBps: SLIPPAGE_BPS });
      // A trade the Router's own simulation says would fail: pass on its message, never a transaction to sign.
      if (status === 200 && json.simulation && !json.simulation.ok) delete json.transaction;
      return reply(status, json);
    }
    // Send what the visitor's wallet signed. The Router sends only a trade it built for this key.
    if (req.method === "POST" && url.pathname === "/api/send") {
      const { signedTransaction } = await readJson(req);
      if (typeof signedTransaction !== "string") return reply(400, { error: "That is not a signed transaction." });
      const { status, json } = await router("/swap/send", { signedTransaction }).catch(
        () => ({ status: 504, json: { error: "No answer from the Router yet." } }));
      return reply(status, json);
    }
    if (req.method === "GET" && url.pathname.startsWith("/api/receipt/")) {
      const { status, json } = await router(`/receipt/${encodeURIComponent(url.pathname.slice(13))}`);
      return reply(status, json);
    }
    reply(404, { error: "Not found." });
  } catch (e) {
    reply(500, { error: String(e.message || e) });
  }
}).listen(PORT, "127.0.0.1", () => console.log(`Open http://localhost:${PORT}`));

Then, in that folder:

Terminal · web app
$ ROUTER_KEY=mny_live_... node server.mjs

Then open http://localhost:3000.

PORT changes the port. Behind your own https proxy, set TRUST_PROXY=1 so each visitor is counted by their real address.

How it works

  1. The server builds

    It sets the pair and caps the amount itself, and never passes on a transaction that would fail.

    server.mjs · build
    // Build for the visitor's wallet. The visitor chooses only the wallet and the amount; the pair is this app's.
    if (req.method === "POST" && url.pathname === "/api/build") {
      const { wallet, amount } = await readJson(req);
      if (!/^\d+(\.\d{1,6})?$/.test(String(amount)) || !(Number(amount) > 0 && Number(amount) <= MAX_AMOUNT)) return reply(400, { error: `Enter an amount up to ${MAX_AMOUNT}.` });
      const { status, json } = await router("/swap/build", { wallet, pay: PAY, receive: RECEIVE, amount: String(amount), slippageBps: SLIPPAGE_BPS });
      // A trade the Router's own simulation says would fail: pass on its message, never a transaction to sign.
      if (status === 200 && json.simulation && !json.simulation.ok) delete json.transaction;
      return reply(status, json);
    }
    
  2. The page shows the fees, and the wallet signs

    index.html · sign
    // 2. Show what the user gets and every fee, with the total, before they sign. The minimum is enforced on chain.
    const { fees, receive } = build.json.quote;
    const total = fees.reduce((sum, f) => sum + Number(f.amount), 0);
    const feeText = fees.length ? `${fees.map((f) => `${f.label} ${f.amount} ${f.asset}`).join(", ")}; total ${total.toFixed(6)} USDF (USDF is Flipcash's dollar, one for one with USDC)` : "none";
    const network = "Solana's network fee is about 0.000005 SOL, plus about 0.002 SOL once if this wallet has never held Moony.";
    if (!confirm(`You get about ${receive.expected} MNY, and at least ${receive.min} or the trade does not happen. Fees: ${feeText}. ${network} Continue?`)) return say("Cancelled.");
    
    // 3. The wallet signs. `format` says how to read the transaction.
    const bytes = Uint8Array.from(atob(build.json.transaction), (c) => c.charCodeAt(0));
    const tx = build.json.format === "v0"
      ? solanaWeb3.VersionedTransaction.deserialize(bytes)
      : solanaWeb3.Transaction.from(bytes);
    const payer = build.json.format === "v0" ? tx.message.staticAccountKeys[0] : tx.feePayer;
    if (!payer?.equals(wallet.publicKey)) return say("Not signing: the fee payer is not this wallet.");
    const signed = await wallet.signTransaction(tx);
    const signedBytes = signed.serialize();
    const signature = signatureOf(signedBytes);
    const signedTransaction = btoa(String.fromCharCode(...signedBytes));
    // Past this point the trade may land, so the page stays locked until it knows what happened, even across a reload.
    done = false;
    const trade = { signature, sentAt: Date.now() };
    pending.set(trade);
    
  3. The server sends it

    The Router sends only trades it built for your key.

    server.mjs · send
    // Send what the visitor's wallet signed. The Router sends only a trade it built for this key.
    if (req.method === "POST" && url.pathname === "/api/send") {
      const { signedTransaction } = await readJson(req);
      if (typeof signedTransaction !== "string") return reply(400, { error: "That is not a signed transaction." });
      const { status, json } = await router("/swap/send", { signedTransaction }).catch(
        () => ({ status: 504, json: { error: "No answer from the Router yet." } }));
      return reply(status, json);
    }
    
  4. The page follows the trade to its answer

    It keeps the signature across reloads, so it offers no second trade until the first has one.

    index.html · receipt
    // Follow a sent trade to its answer, by its signature. Returns true once the outcome is known.
    // Only "not found" for 3 minutes after sending means it can no longer land (it expires 60 to 90 seconds after it was
    // built); if the receipt could not be read at all, the trade may have landed, so the page stays locked.
    async function follow({ signature, sentAt }) {
      const giveUpAt = sentAt + 3 * 60_000;
      let notFound = false;
      do { // at least once, so a trade followed long after a reload still gets its answer
        const r = await call(`/api/receipt/${signature}`);
        if (r.status === 200) {
          pending.set(null);
          if (r.json.status === "failed") { say("The trade reached the network but failed; only the network fee was spent."); return true; }
          const bought = r.json.swap?.bought;
          say(bought ? `Done: you got ${bought.amount} ${bought.symbol}.` : `Done. Signature ${signature}`);
          return true;
        }
        notFound = r.status === 404;
        say(`Confirming ${signature}...`);
        if (Date.now() < giveUpAt) await sleep(3000);
      } while (Date.now() < giveUpAt);
      if (!notFound) { say(`We could not confirm this trade. It may have gone through: look up ${signature} before trying again.`); return false; }
      pending.set(null);
      say("The trade did not go through, and nothing was spent. You can try again.");
      return true;
    }
    

Did the trade happen?

Never trade twice by accident. Go by the response to your first send:

  • status: "confirmed": it landed. The receipt says what it did.
  • A 4xx response (400, 401, 403, 409, 429): the trade did not happen. Fix the cause and build again. One of them did reach the chain: failed_on_chain means it landed and reverted, and only the network fee was spent.
  • status: "pending", a 5xx, a timeout or no response: it may still land. Do not build again. Ask for the receipt every few seconds (you may also send the same signed bytes again); if it is still not found 3 minutes after you sent it, the trade can no longer land.

After an unclear response, only the receipt decides. Sending the same signed bytes again is safe: a transaction runs at most once, and if it already landed, send answers confirmed. A 4xx on a resend says nothing about the first send. retryable: true means send the same bytes or ask again, never build a new trade. You know the signature before you send (Sign), so you can always ask.

Reference

Basics

Base URL: https://router.moonyversal.com/api/v2. JSON in and out (send Content-Type: application/json with a body). Call it from your server.

Token amounts are decimal strings, in requests and responses, in whole units of the asset: "5" with pay=USDF is 5 USDF. Prices and percentages are numbers, and times are Unix seconds. Use at most 6 decimals for USDF and USDC, 9 for SOL and 10 for currencies. To spend a dollar amount of SOL, divide it by SOL’s priceUsd from GET /tokens and round down to 9 decimals.

Name USDF, USDC and SOL by name or mint. Name a currency by its mint only, since tickers can repeat (MNY is refused), and never pick one by matching its name. Quotes and receipts name SOL by So11111111111111111111111111111111111111112.

The JavaScript examples use api() from trade.mjs:

trade.mjs · api()
const API = "https://router.moonyversal.com/api/v2";
const MNY = "4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6"; // Moony's mint
const headers = { authorization: `Bearer ${ROUTER_KEY}`, "content-type": "application/json" };

// Every response is JSON; an error carries { error, code, retryable, hint? }.
async function api(path, body) {
  const res = await fetch(API + path, { method: body ? "POST" : "GET", headers, body: body && JSON.stringify(body) });
  let json;
  try { json = await res.json(); } catch { json = { code: "bad_response", error: `HTTP ${res.status}, not JSON`, retryable: true }; }
  if (!res.ok) {
    const hint = json.hint ? ` ${json.hint}` : "";
    throw Object.assign(new Error(`${json.code}: ${json.error}${hint}`), { status: res.status, code: json.code, retryable: json.retryable });
  }
  return json;
}

Words used here

Mint
A token’s address on Solana. Tickers can repeat; mints never do.
Basis points
Hundredths of a percent: 50 basis points is 0.5%.
Slippage
How far below the quote you let a trade land, in basis points.

Keys and limits

Send your key as Authorization: Bearer <key> (or x-api-key). Keys look like mny_live_ plus 32 letters and digits. A wrong or revoked key is refused with 401 invalid_key, even on a quote.

Every key is live, and there is no test network for Flipcash currencies. Keep your key on your server, never in a browser, a repository or a URL. We keep only a fingerprint, so a lost key is replaced, not recovered.

Requests allowed per minute, with a new key and without a key
Per minuteWith a keyNo key
Quotes300120
Builds60Needs a key
Sends30Needs a key
Receipts12060
Currency lists6060

Without a key, limits are per IP address. Ask us for more. Responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (seconds until the limit resets); past a limit you get 429 rate_limited with Retry-After.

Each key may also make 5,000 builds and 1,000 sends a day, reset at 00:00 UTC (429 daily_limit). Only successful builds and broadcast sends count. X-Daily-Limit and X-Daily-Remaining show where you are, and your organization’s owners get an email at 80%. A revoked key stops working within about 10 seconds.

Currencies GET /tokens

Everything the Router can trade, with its mint, decimals and whether it is trading now.

GET /tokens
$ curl https://router.moonyversal.com/api/v2/tokens

kind is dollar (USDF, USDC), native (SOL) or currency. tradeReady: false means it is not trading right now; tradeNote says why. partial: true means the list may be missing currencies or be out of date right now; ask again in a few seconds.

Quote GET /quote

Quote parameters
ParameterMeaning
payWhat you pay: USDF, USDC, SOL or a currency mint. Required.
receiveWhat you get. Required.
amountHow much of pay, as a decimal string. Required.
slippageBpsHow far below the expected amount you accept, 0 to 5000. Default 30 (0.3%). Keep it low: a high setting lets a trade land at a worse price.
partnerFeeBpsYour share of the buy fee, 0 to 50. Default: the share on your key. Needs a fee wallet (Your fee wallet).
GET /quote
$ curl -G https://router.moonyversal.com/api/v2/quote \
    -H "Authorization: Bearer $ROUTER_KEY" \
    -d pay=USDF -d receive=4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6 -d amount=5

expected is what you should get; min is the least the trade accepts, enforced on chain (base and minBase are the same amounts in the token’s smallest units). Each fee is its own line, { label, amount, asset, bps }; a sell shows Flipcash’s 1% as “Flipcash sell fee”. priceImpactPct is how far this trade’s average price is from the current price. Without SOL in the route it is information: the trade moves the currency along its curve as it fills, but nothing is lost, since every dollar after fees goes into the currency’s pool and the coins sell back for what went in, less Flipcash’s 1% sell fee, so show it if you like but don’t warn on it. With SOL in the route it includes the Orca or Raydium pool, where a large trade fills at a worse price than the market; that part is a real cost, so warn your users above a level you choose.

The kinds of trade a quote can be
kindThe trade
buy
sell
USDF to a currency, and back.
usdc-buy
usdc-sell
USDC to a currency, and back, through USDF.
sol-buy
sol-sell
SOL to a currency, and back, through USDC and USDF.
routedOne currency to another.
usdc-to-usdf
usdf-to-usdc
Between the two dollars, one for one.
sol-to-usdc
usdc-to-sol

sol-to-usdf

usdf-to-sol
Between SOL and the dollars.

A trade from SOL converts it to an exact amount of USDC, priced a little under the market; SOL that is not needed stays in the wallet. A quote is a price, not a hold: build prices the trade again, and build.quote is what the transaction enforces.

Build POST /swap/build

Build fields
FieldMeaning
walletThe address that signs and pays, including the network fee. Required.
pay, receive, amountAs in the quote. Required.
slippageBpsAs in the quote. Default 30.
partnerFeeBpsAs in the quote.
simulateSimulate as your wallet before responding. Default true.
POST /swap/build
$ export ROUTER_KEY=mny_live_...   # your key
$ curl https://router.moonyversal.com/api/v2/swap/build \
    -H "Authorization: Bearer $ROUTER_KEY" \
    -H "Content-Type: application/json" \
    -d '{ "wallet": "<your wallet>", "pay": "USDF",
          "receive": "4muAfB6m1P7C3Znad1VUsoqYFwvGQRkWGpJ3A4vupxz6", "amount": "5" }'

transaction is the unsigned transaction, base64. format is "v0" or "legacy": read it every time and use the matching class (Sign; Solana explains both in its guide). Times are Unix seconds.

simulation says whether the trade would work as your wallet. If not, the response is still 200, with ok: false and a plain message, such as “This wallet has no SOL to pay the network fee. Send it a little SOL and build again.” Some wallets that cannot pay are refused before that, with 400 insufficient_balance. Handle both.

A built transaction lives about 60 seconds. If signing takes longer, build again after expiresAt. An expired one gets 409 expired_blockhash and is not sent.

Sign

Sign with any Solana signer; the Router never asks for a key. These examples use @solana/web3.js version 1 (npm install @solana/web3.js@1.98.4). Stay on version 1: npm audit fix --force would move it to version 3, which works differently.

Before signing, check that the fee payer is your wallet. A browser wallet also shows the balance changes, which should match the quote.

Sign
import { Transaction, VersionedTransaction } from "@solana/web3.js";

const bytes = Buffer.from(build.transaction, "base64");
let tx;
if (build.format === "v0") {
  tx = VersionedTransaction.deserialize(bytes);
  tx.sign([keypair]); // your server's Solana keypair
} else {
  tx = Transaction.from(bytes);
  tx.sign(keypair);
}
const signedTransaction = Buffer.from(tx.serialize()).toString("base64");

The signature is the transaction’s first signature, so you know it before you send: bs58.encode(tx.signatures[0]) for v0, bs58.encode(tx.signature) for legacy. Keep it to look up the receipt.

Send POST /swap/send

POST /swap/send
$ curl https://router.moonyversal.com/api/v2/swap/send \
    -H "Authorization: Bearer $ROUTER_KEY" \
    -H "Content-Type: application/json" \
    -d '{ "signedTransaction": "<signed, base64>" }'

Send relays only a transaction the Router built for your key in the last 10 minutes (anything else gets 400 not_built). It simulates first (simulateFirst: false skips that), broadcasts, and waits up to about 30 seconds for confirmation, resending as it waits. You can broadcast it yourself instead. What each response means: Did the trade happen?

Receipt GET /receipt/<signature>

GET /receipt
$ curl https://router.moonyversal.com/api/v2/receipt/<signature>

Read from the chain: what was sold and bought, the dollar value, and every fee. status is confirmed, or failed if it landed and reverted (only the network fee was spent). swap.kind uses the quote’s names (sol-buy here). valueUsd is the dollar side of the trade.

Each fee is { label, amount, asset }, as in a quote (which adds bps); the network fee is in SOL. For a transaction the Router did not build, swap can be null.

A signature the chain does not know yet gets 404 not_found: ask again. Keep your own record of the signatures you send.

Fees

What the Router charges
ItemFee
Calling the APIFree.
BuysUp to 1%: the Router’s 0.5% (“Router buy fee”) plus your share of up to 0.5% (“Partner fee”). Your users never pay more than 1% on a buy. A buy is anything into a Flipcash currency.
Your shareFrom 0 to 0.5%, the same for every currency: a default on your key, or partnerFeeBps on any quote or build. The buyer pays it straight to your wallet’s USDF account, in the same transaction; the Router never holds it.
SellsNo Router or partner fee. Flipcash’s Reserve Contract keeps 1% of every sell, whoever builds it, shown in the quote as “Flipcash sell fee”.
Currency to currencyFlipcash’s 1% on the sell side, plus the buy fees.
SOLThe SOL/USDC pool’s small fee, already in the quote and listed in the receipt.
USDF and USDCOne for one.
Network feesPaid in SOL by the signing wallet: about 0.000005 SOL for most trades, 0.00016 SOL for a trade with SOL, and a one-time deposit of about 0.002 SOL the first time the wallet holds a token (it stays in that token account, and comes back if you close it).
Showing feesYour app must show users the total fee, including your partner fee, before they sign (Terms, “Your app and your users”).

Fee lines are labelled Router buy fee, Partner fee, Flipcash sell fee, Orca or Raydium pool fee (receipts, on SOL trades) and Network fee (receipts).

Coming soon Trade without holding SOL: the Router will pay the network fee and be repaid inside the same transaction.

Your fee wallet PUT /key/partner-fee

Set where your partner fee goes, with your key, any time. The wallet needs a USDF account first: send it any amount of USDF once (a usdc-to-usdf trade through the Router does it). The Router never creates that account, so your users never pay for it.

Fee wallet fields
FieldMeaning
walletThe address whose USDF account receives your share. Required the first time.
bpsYour default share, 0 to 50. Default 50. Any quote or build can still pass partnerFeeBps.
PUT /key/partner-fee
$ curl -X PUT https://router.moonyversal.com/api/v2/key/partner-fee \
    -H "Authorization: Bearer $ROUTER_KEY" \
    -H "Content-Type: application/json" \
    -d '{ "wallet": "<your wallet>", "bps": 50 }'

GET /key shows your settings; DELETE /key/partner-fee removes your fee. Changes take effect within about 10 seconds and are emailed to your organization’s owners (in a burst of changes, the rest are listed in Activity). Anyone with your key can change this, so if an email surprises you, revoke the key.

Errors

Every error is { error, code, retryable, hint?, source }. retryable says whether trying again can work; hint says what to do next. A broadcast send that expired also carries signature and status: "dropped".

An error
{
  "error": "You need USDF to make this swap. Use USDC or buy USDF first.",
  "code": "insufficient_balance",
  "retryable": false,
  "source": "moonyversal-router"
}

A real response: a build for a wallet without USDF.

Every error code, its status, and whether to retry
StatuscodeMeaningRetry
400invalid_inputSomething in the request: a missing field, too many decimals, a bad address, or slippageBps or partnerFeeBps out of range (partnerFeeBps also needs a key with a fee wallet).No
400insufficient_balanceThe wallet cannot pay for this trade. The message says what is missing.No
400simulation_failedThe signed transaction would fail, so it was not sent. The message says why.No
400invalid_inputOn a send: not signed by its fee payer, or changed after signing. Not sent.No
400not_builtOn a send: not a transaction the Router built for this key in the last 10 minutes. Not sent.No
400failed_on_chainIt landed and reverted. Only the network fee was spent.No
401invalid_keyThe key is malformed, unknown or revoked.No
401key_requiredBuild and send need a key.No
403forbidden_routeYour key's fee share is fixed, so it cannot be changed.No
404unknown_assetpay or receive is not USDF, USDC, SOL or a Flipcash currency mint.No
404not_foundThe chain does not know this signature yet. Ask again; not found 3 minutes after sending, it never will be.Yes
405method_not_allowedWrong method: build and send take POST.No
409expired_blockhashThe network no longer accepts this transaction, so it will never land (status "dropped" if it was broadcast). Build again.No
429rate_limitedPast your limit. Wait for Retry-After.Yes
429daily_limitThe key has used its builds or sends for today. Resets at 00:00 UTC.No
500internalSomething failed on our side.Yes
502send_failedThe network did not take it. Check the receipt; the same signed bytes can be sent again while they are valid.Yes
503internalOn a send: we could not check whether it already landed. Not sent; send the same signed bytes again.Yes
503tokens_unavailableWe could not read the currency list, or this currency, just now. Try again in a few seconds.Yes
503no_liquidityNot enough liquidity right now. Try later.Yes
503router_haltedWe paused building and sending; the message says why. Quotes and receipts still work.Later

Ready to build? Request a key and start with $1 or less. Questions: Moonyversal Dev on Flipcash, or contact@moonyversal.com.

Request early access