nano133

Build · Guides

Accept Nano payments without a processor

An address for each checkout, a clean amount, an exact check on your own node, and a sweep to your wallet. No processor, no fee. Your server holds a seed.

an address foreach checkoutyour walletӾone sweep
  • No processor
  • No fee
  • An address for each checkout
  • 30 minutes
  • Developer
  • Moves real Nano
  • Checked 24 October 2026
About this guide

Take payments in Nano on your own site, with no payment processor in between. Each checkout gets its own address and a clean amount. Your node tells you when exactly that amount has arrived and is confirmed, and a sweep moves the money to your own wallet. There is no fee. Your server holds a seed, so read how to keep it safe.

The rules of this guide

  1. Step 1

    Never change the secret or the label after money has come in. Take each index from an atomic counter that never goes down, and refuse an index of 1,000,000 or more. The secret stays on the server: never log it, return it, store it in a database, or put it in a page, a repository or a message. The same goes for a seed and a private key.

  2. Step 2

    Work in raw with big integers, never with floating point. Round the price up to a whole 0.0001 XNO, and refuse a price below it. The price comes from your server, never from the browser.

  3. Step 3

    Build the QR code and the wallet link from the address and the quote that your server returned. Show every digit of the amount. Never round it on the screen.

  4. Step 5

    Credit a payment only when its block is a confirmed send to this checkout's address of exactly the quote, first seen inside the window. There is no tolerance: one raw more or less is not this checkout's payment.

  5. Step 6

    Record the block hash as used and mark the checkout paid in one transaction. Refuse a hash that is already used.

  6. Step 7

    The destination of the sweep is a value in your code or your deploy settings, never a field of a request or a row. Stop when a record is wrong. Receive only the paid block. Record the signed send before you publish it, and let one run hold the checkout. Run the sweep from a timer, never from a visitor's request.

  7. Step 8

    When your node does not answer, credit nothing and answer busy (HTTP 503). Never use a node that you do not trust for this decision. Send every other payment back in full. Rate-limit the checkout and claim routes for each visitor.

  8. Google Cloud

    Never change IAM, Secret Manager or the Cloud Run service yourself, and never let a coding agent do it: the owner grants the access and maps the secret. Map a pinned version, never latest.

  9. Cloudflare Workers

    The secret goes in with wrangler secret put, never in vars, in the configuration file, in the repository or in a log. Never run wrangler deploy or change an account for the owner.

  10. Cloudflare Workers

    Run the sweep and the returns only from the timer, and let one run hold the lock. Do not call a node from a request just to sweep.

Why an address for each checkout

Why not a unique amount, and where nano133.com stands

The simple way to tell checkouts apart is to give each one its own amount: the price plus a small random tail. An earlier version of this guide did that. It fails with wallets that cut or round the amount. Cake Wallet sent Ӿ0.0593 for a quote of Ӿ0.059300000000000000000000801448, and nothing could match that payment.

So here each checkout gets its own address. Four things follow:

  • A payment names its checkout by the address it went to. The amount only has to be exact.
  • The amount is clean: the price rounded up to 0.0001 XNO, with no tail. A wallet that keeps four decimals sends exactly that amount. No wallet that we read or tried keeps fewer than four decimals.
  • Two payments at once never mix. Two buyers can pay the same amount at the same moment, and each pays a different address.
  • You need no amount lock, no tail and no memo.

nano133.com is moving its own checkouts to this way, one flow at a time. Nano Checkout shows it as a picture and says where it stands.

price 1¢scan to paythis sale asks forӾ0.0278no tailnano_1pju…edheits own address
One price, one clean amount, and an address that only this checkout has. The address is shortened and made from a secret that was thrown away: nobody can pay it.
Warning

The cost: your server holds a seed. Every checkout address comes from one secret, so your server can sign for all of them. That is a hot wallet. The sweep (step 7) moves each payment on, so little waits there, but anyone who gets the secret can take what waits and can derive every address. Steps 1 and 7 say how to keep it safe. If you cannot keep a seed on a server, read the keyless way at the end.

What you need

The five things you need
  • An address you control, from any Nano wallet. The sweep sends every payment on to it, and buyers never see it. Use a new address for your shop, so its history holds only your sales.
  • A Nano node you trust, with its RPC URL. Its answers decide what you credit and what you send, so use your own node (a guide for running one is coming). It must allow receivable, block_info, account_info, work_generate and process. A public node is fine to try the first steps, but it can limit you, go away, be wrong, or refuse work_generate and process.
  • A secret for the seed: 32 random bytes in hex, from your secret manager.
  • A database with transactions (Postgres, Firestore, SQLite…), for the index counter, the checkouts and the used block hashes.
  • Node.js 18 or newer and the package nanocurrency-web, to run the example. The Cloudflare track's file edge-state.mjs needs Node.js 22 or newer.

Step 1Give each checkout its own address

Give each checkout its own address, made from one secret and an index.

import { createHmac } from "node:crypto";
import nano from "nanocurrency-web"; // npm install nanocurrency-web
const { wallet } = nano;

// A name for your seed. Never change it, or the secret, after the first checkout.
const LABEL = "nano133 kit checkout seed v1";

// Checkout number `index` is account `index` of the seed that your secret makes.
function accountOf(secret, index) {
  const seed = createHmac("sha256", secret).update(LABEL).digest("hex").toUpperCase();
  return wallet.legacyAccounts(seed, index, index)[0];
}

// accountOf(secret, 0).address is public: show it ("nano_3…q9f").
// .privateKey is for the sweep only. Never show it, send it to a browser or log it.
What a seed is, and how an index gives an address

A seed is one secret that a wallet makes many addresses from. Your secret makes the seed, and checkout number index gets account index of it. The same secret and the same index always give the same address. So you never store a key: you store the index.

// The next index comes from an atomic counter in your database.
// Two checkouts at once must never get one index.
//   SQL:       update checkout_counter set next = next + 1 returning next - 1;
//   Firestore: in a transaction, read the counter's `next`, then write `next + 1`.
// Save the checkout with its index and its address. Refuse an index of 1,000,000 or more.
The counter, and how to keep the secret safe

Take the next index from a counter, and save the checkout with it (the lines above).

Keep the secret safe, because it can move money:

  • It stays on the server. Never in your page, your code, your repository, your database or a log. Keep it in a secret manager.
  • Back it up like a wallet seed. With it you can always get back what waits at any address.
  • Never change it once money has come in. The same goes for the label. The money stays at the earlier addresses, and only the old secret and label make their keys again. Without them it cannot be swept or returned.
  • Never lower or delete the counter. It only grows, and it must be atomic.
Rule

Never change the secret or the label after money has come in. Take each index from an atomic counter that never goes down, and refuse an index of 1,000,000 or more. The secret stays on the server: never log it, return it, store it in a database, or put it in a page, a repository or a message. The same goes for a seed and a private key.

Check

run the example with --address 0 twice: the same address both times. Run it with --address 1: a different address.

Step 2Turn the price into a clean quote

Turn the price into a clean quote: whole raw, rounded up to 0.0001 XNO.

// 1 XNO = 10^30 raw. The quote is the price rounded UP to a whole 0.0001 XNO
// (10^26 raw), so it has no tail.
const STEP = 10n ** 26n;
if (raw < STEP) throw new Error("A price below 0.0001 XNO is refused");
const quote = ((raw + STEP - 1n) / STEP) * STEP;
Raw, big integers and the smallest price

Nano amounts are whole numbers of raw: 1 XNO is 1030 raw. Work in raw everywhere, with big integers (BigInt), never with floating point. Round the price up to a whole 0.0001 XNO. That is the quote: at most four decimals, and no tail.

A price below 0.0001 XNO is refused: rounding it up would charge many times its price, so change the price instead.

Rule

Work in raw with big integers, never with floating point. Round the price up to a whole 0.0001 XNO, and refuse a price below it. The price comes from your server, never from the browser.

Check

a price of 0.0271 XNO gives 27100000000000000000000000000 raw. A price of 0.00001 XNO is refused.

Step 3Show the payment

Show the buyer a QR code, a wallet link and the exact amount, from what your server returned.

// POST /api/checkout answers with what the page needs:
{ id, address, amount: quote, uri: `nano:${address}?amount=${quote}`, expiresAt }
// The page draws its QR code and its "Open in wallet" link from `uri`.
// It never builds them from a constant.
What the page shows, and what to tell the buyer

Your server answers the checkout request with the address and the quote. Show a QR code and an “Open in wallet” link built from what your server returned, and the exact amount (every digit) and the address as text for people who copy them (the lines above).

Tell the buyer to send the exact amount from a wallet they control. A wallet that opens the link sends it exactly. A person who types the amount by hand must type all of it, because any other amount is not this checkout's payment (step 8 covers that). Never round the amount on the screen.

Rule

Build the QR code and the wallet link from the address and the quote that your server returned. Show every digit of the amount. Never round it on the screen.

Check

scan the QR code with a wallet: it opens with the checkout's own address and the exact amount filled in.

Step 4Find the payment

Poll your node for the payments that wait at this checkout's address.

{ "action": "receivable", "account": "<the checkout's address>", "count": "50",
  "threshold": "<the quote>", "source": "true" }
How often to poll, and a faster way

Poll your node every 2 seconds while the checkout is open. Ask for the sends that wait at this checkout's address. The paid block waits there until your sweep receives it. The threshold skips anything smaller than the quote.

For a busy shop, listen to your node's WebSocket confirmation topic for the addresses of open checkouts instead of polling, and keep the poll as the backup. Also let the page send the block hash when the buyer's wallet reports it: then you check that one block and skip the search.

Check

run the example below with --check on a send you already received (its block hash, the address it went to and its amount in raw): it answers paid.

Step 5Check that it really pays this checkout

Ask the node for the block itself, and check every rule before you credit it.

{ "action": "block_info", "hash": "<send hash>", "json_block": "true" }

// It pays this checkout only when all of these hold:
b.subtype === "send"
b.contents.link_as_account === checkout.address   // THIS checkout's address
b.amount === checkout.quote                       // exactly, as a string of raw
b.confirmed === "true"
// First seen by your node inside the window (b.local_timestamp is in seconds),
// with 2 minutes either side for clocks that differ:
const seenAt = Number(b.local_timestamp) * 1000;
seenAt >= checkout.createdAt - 120_000
seenAt <= checkout.expiresAt + checkout.grace + 120_000
The rules, the time window and no tolerance

Never credit a block because it showed up in a list. Ask for the block itself and check every rule (the lines above).

The address belongs to this checkout alone, so an old payment can never pay a later checkout. The time window decides when a payment still counts: from the moment the checkout started to the end of its open time plus its grace (the package's defaults are 15 minutes and 1 hour). Your clock and your node's clock may differ a little, so allow two minutes at both ends (the package does). Credit only a confirmed block; a send the network has not confirmed can still lose.

There is no tolerance. One raw short or one raw over is not this checkout's payment.

Rule

Credit a payment only when its block is a confirmed send to this checkout's address of exactly the quote, first seen inside the window. There is no tolerance: one raw more or less is not this checkout's payment.

Check

the same block checked against a different amount answers another amount, and against another address answers sent to another address. Neither answers paid.

Step 6Credit it once

Credit the payment once: one transaction records the hash and marks the checkout paid.

The transaction, and the buyer's receipt

In one database transaction, record the block hash as used and mark the checkout paid, with its sweep due. If the hash is already recorded, refuse. One block pays one checkout, once, even when two requests arrive at the same moment. Keep that list of used hashes: the sweep and Late Payment Return read it.

Then give the buyer what they paid for. If you give a receipt (a cookie or a link), sign it on the server and give it only to the browser that started the checkout.

Rule

Record the block hash as used and mark the checkout paid in one transaction. Refuse a hash that is already used.

Check

send the same claim twice at the same moment: your database records the block hash once and marks the checkout paid once.

Step 7Move the money to your wallet: the sweep

Run the sweep from a timer: it sends exactly the quote on to your own wallet, once.

a timer runs the sweeppaidits addressyour walletӾexactly the amountonce
// A value in YOUR code (a placeholder here). Never read it from a checkout,
// a request or a database row.
const DESTINATION = "nano_3…q9f";

// 1. Move nothing unless the record is whole and the paid block is what it says:
accountOf(secret, checkout.index).address === checkout.address
// block_info of checkout.paidHash: confirmed, a send, to checkout.address,
// of exactly checkout.quote

// 2. Receive that one block, then send exactly the quote on. Your node makes the
// work and takes the blocks. nanocurrency-web signs them.
{ "action": "work_generate", "difficulty": "fffffe0000000000",
  "hash": "<the frontier, or the public key of an address that is not open yet>" }
{ "action": "process", "json_block": "true", "block": { …the receive block… },
  "subtype": "open" }   // "receive" when the address is open
{ "action": "work_generate", "difficulty": "fffffff800000000",
  "hash": "<the receive block's hash>" }
{ "action": "process", "json_block": "true", "block": { …exactly the quote to DESTINATION… },
  "subtype": "send" }
What the sweep does, and five points

A payment waits at the checkout's own address, and your server holds its key. The sweep receives that one paid block there and sends exactly the quote on to your own wallet, once. Run it from a timer (every few minutes, or once a day: the money waits at the address until the next run), never from a visitor's request.

  • Your address is fixed in your code, or in your own deploy settings. The sweep never reads it from a checkout, a request or a database row, so nothing a visitor can change can send the money anywhere else.
  • It stops when a record is wrong. If the checkout's index does not give its address, or the stored block is not a confirmed send of exactly the quote to that address (asked of your node again), nothing moves.
  • It receives only that block. A wrong amount that waits at the address is not touched: step 8 sends it back.
  • Exactly once. Record the signed send on the checkout before you publish it, and let one run at a time hold the checkout. A crash, or a second run, then finds that send on the ledger instead of making another. Sign blocks from a server safely shows how, with a script and a test.
  • Keep the seed safe. The sweep is why little waits at an address, but the seed can still move whatever does.
Rule

The destination of the sweep is a value in your code or your deploy settings, never a field of a request or a row. Stop when a record is wrong. Receive only the paid block. Record the signed send before you publish it, and let one run hold the checkout. Run the sweep from a timer, never from a visitor's request.

Check

pay a test checkout and run the sweep: the checkout's address makes one send of exactly the quote to your wallet. Run it again: it says there is nothing to send.

Step 8Send anything else back, and fail closed

Send anything else back in full, and fail closed when your node does not answer.

15 min1 hour graceclosedӾtoo late, or not the exact amountthe senderits addressӾback by itself, once
Five points
  • Wrong or late amounts pay nothing: a rounded amount, a short one, an over one, a second payment, a payment after the grace. They stay at the checkout's address, and nothing is marked paid.
  • Send them back in full. Our Late Payment Return tool does that by itself, from the checkout's address, once, after at least 2 hours. It sends back payments of at least Ӿ0.001; a smaller one stays. It needs @nano133/late-returns version 0.4.0 and the seed your server already holds. Run the returns and the sweep one after the other: both build blocks on the same address. Send money back exactly once is the whole return flow, step by step.
  • Your node does not answer: answer “busy” (HTTP 503) and credit nothing. Never fall back to a node you do not trust for this decision.
  • Prices come from your server, never from the browser.
  • Rate-limit the checkout and claim routes per visitor: each checkout takes one index, and each claim costs your node a few calls.
Rule

When your node does not answer, credit nothing and answer busy (HTTP 503). Never use a node that you do not trust for this decision. Send every other payment back in full. Rate-limit the checkout and claim routes for each visitor.

Check

stop your node and claim: the page says “try again”, and nothing is credited.

Choose your platform

Google Cloud

Run the checkout on Cloud Run, keep its state in Firestore, its secret in Secret Manager and its timer in Cloud Scheduler. nano133.com runs its own checkouts this way, and the snippets below are written from its code. We have not deployed this guide's example on Google Cloud, so this track is Pre-alpha. What is said here about Google Cloud comes from nano133.com's own setup and records: we did not run gcloud for this guide, and we mark nothing here as checked.

Where the secret lives

gcloud secrets add-iam-policy-binding CHECKOUT_SECRET --member="serviceAccount:<the service account>" --role="roles/secretmanager.secretAccessor"
gcloud run services update <service> --region <region> --update-secrets=CHECKOUT_SECRET=CHECKOUT_SECRET:<version>
const secret = process.env.CHECKOUT_SECRET?.trim();           // trim a line end that the secret may carry
if (!secret) throw new Error("CHECKOUT_SECRET is not set");   // answer busy (503): never fall back to another value
Five points about the secret
  • Make the secret in Secret Manager, as a secret of its own: 32 random bytes in hex.
  • Give the service account that your Cloud Run service runs as read access to that one secret (the role roles/secretmanager.secretAccessor).
  • Map it into the service as an environment variable, pinned to a version number. Never latest: a version that someone adds later then changes nothing.
  • Keep the mapping when you deploy. gcloud run services update keeps every environment variable and secret that you do not name in it. A --set-secrets or --clear-secrets in your deploy step replaces or removes them, so check your step for them.
  • Do not remove the secret later. The sweep and the returns for addresses that already hold money stop with it.
Rule

Never change IAM, Secret Manager or the Cloud Run service yourself, and never let a coding agent do it: the owner grants the access and maps the secret. Map a pinned version, never latest.

Where the state lives, and the lock

// Step 1. The next index: read the counter, then write it, in one transaction.
const index = await db.runTransaction(async (tx) => {
  const ref = db.doc("checkout_index/counter");
  const next = (await tx.get(ref)).data()?.next ?? 0;
  if (next >= 1_000_000) throw new Error("the counter is past its cap");
  tx.set(ref, { next: next + 1 }, { merge: true });
  return next;
});

// Step 6. Credit once: the used hash and the paid checkout change in ONE transaction. Every read comes before the first write.
await db.runTransaction(async (tx) => {
  const used = db.doc(`used_hashes/${hash}`), checkout = db.doc(`checkouts/${id}`);
  const [u, c] = await Promise.all([tx.get(used), tx.get(checkout)]);
  if (u.exists) throw new Error("used");
  if (c.data()?.status !== "open") throw new Error("taken");
  tx.create(used, { checkout: id, at: Date.now() });
  tx.update(checkout, { status: "paid", paidHash: hash });
});
Why the state lives in documents

Firestore has what steps 1, 6 and 7 need: transactions. Cloud Run starts many instances and an instance's memory does not outlive it, so a counter, a flag or a lock in memory is not one. They live in documents.

take:  in a transaction, if the document exists and its `until` is in the future, return false; else set { owner, until: now + ttl } and return true
fence: in the same transaction as the write, read the document; if its owner is not this run, or its `until` has passed, throw LockLost
The lock and the fence in documents

The lock of step 7 is a document { owner, until }. Taking it, and proving that you still hold it before every write that records money (the fence), are transactions on that document. nano133.com's till does this (the lines above).

The guide Sign blocks from a server safely explains the lock and the fence, and has them in SQL.

What runs the timer

The timer's route, and four points

Cloud Scheduler calls a route of your service on a schedule. The route is the timer's only caller:

  • The job: an HTTP POST to your route, with Authorization: Bearer <a second secret> (kept in Secret Manager like the first one). The route compares it with timingSafeEqual. nano133.com gives its job a deadline of 300 seconds.
  • The answer: 403 for a bearer that does not match, 200 when the run happened, 503 when the server has no key, and 500 (with an error line in the log) when the run failed.
  • Once a day for the sweep. Many instances can receive a tick, so the day's gate is a Firestore document that a run claims in a transaction: { startedAt, owner, until }. A run that dies leaves its claim, and the first tick after the claim's time continues the work. nano133.com's job comes every 5 minutes for its other work, and the sweep of paid addresses goes through this gate at most once a day. For a small shop, one job a day is enough: the money waits at its address until the next run.
  • Never from a visitor's request. A visitor must not be able to start a sweep, and a slow sweep must not hold a page.

Cloudflare Workers

Run the checkout as a Cloudflare Worker, keep its state in D1, its secret as a Worker secret and its timer as a Cron Trigger. nano133.com's game starter runs a watch-only checkout this way (one receive address, no seed, no sweep), so our own Worker holds no seed. We have not run this guide's sweep on a Worker, so this track is Pre-alpha. We ran the SQL of edge-state.mjs on SQLite, not on D1 itself, and we have not deployed this guide's example on Cloudflare. What is said here about the plans of Cloudflare comes from the comments in the configuration of our starter: we did not look them up.

Where the secret lives

const secret = env.CHECKOUT_SECRET?.trim();
if (!secret) return new Response("busy", { status: 503 });
Four points about the secret
  • A variable is plain text in your configuration file. A secret is not. Put the secret in as a secret: npx wrangler secret put CHECKOUT_SECRET. The starter keeps every secret out of its configuration file and says so in it.
  • Local development reads a .dev.vars file next to the configuration. Never commit it. The starter ships .dev.vars.example with no value in it.
  • Read it in the Worker as env.CHECKOUT_SECRET, and fail closed when it is missing: answer busy (503).
  • A seed is a choice that nano133.com's own starter did not make. Its notes give two reasons: a creator with no technical background should hold no seed on a server, and a Worker does not make the proof of work that a sweep of derived addresses needs. This guide's sweep takes the proof of work from your node (work_generate, step 7): your node makes the work, and the Worker only signs. Whether that fits in a Worker is the open question in the limits below.
Rule

The secret goes in with wrangler secret put, never in vars, in the configuration file, in the repository or in a log. Never run wrangler deploy or change an account for the owner.

Where the state lives, and the lock

UPDATE checkouts SET status = 'paid', paid_hash = ? WHERE id = ? AND status = 'open'
-- paid_hash is UNIQUE: a block that already paid another checkout makes this fail. changes = 1: this checkout is paid.

INSERT INTO locks (name, owner, until) VALUES (?, ?, ?)
ON CONFLICT (name) DO UPDATE SET owner = excluded.owner, until = excluded.until WHERE locks.until <= ?
-- changes = 1: this run holds the lock. changes = 0: another run does.
Why the state lives in rows, and how to run a statement

D1 is SQLite. A Worker also has many copies (each Cloudflare location and each copy counts on its own), so a counter, a flag or a lock in a variable is not one: they are rows. The file below has the three things that steps 1, 6 and 7 need, as SQL: the counter (taken together with the checkout, in one transaction), the used hash (a unique column), and the sweep lock (one statement that makes the row or takes it over once its time has passed).

In a Worker, run a statement with env.DB.prepare(sql).bind(...).run() and read meta.changes from the result. Statements that must happen together go in one env.DB.batch([...]). The starter does both. D1 takes at most 100 bound values in one statement: the starter splits its reads into chunks for that.

edge-state.mjs115 lines
edge-state.mjsDownload
// The state of a shop that takes Nano payments, in SQL: the index counter, the used block hashes and the sweep lock.
// From the nano133.com guide "Accept Nano payments without a processor" (the Cloudflare track). MIT license.
// The statements are SQLite, the database of Cloudflare D1. This file runs them on node:sqlite, which needs Node.js 22 or newer.
// It runs on SQLite. We have not run it on D1 itself. The accept-nano.mjs of the same guide does not need it.
//
//   node edge-state.mjs open <database> <checkout id> <address> <quote in raw>
//       takes the next index from the counter and makes the checkout with it, in one step. Prints the index.
//   node edge-state.mjs credit <database> <checkout id> <send block hash>
//       marks the checkout paid with that block, once. Prints paid, used (the block paid another checkout) or taken.
//   node edge-state.mjs lock <database> <name> <time in ms>
//       takes the lock of the sweep. Prints held, or busy when another run holds it and its time has not passed.
//   node edge-state.mjs show <database>
//       prints the checkouts.
//
// EDGE_TEST_PAUSE_MS=<ms> exists for tests only: it waits inside the transaction of `open`, so that runs overlap.
//
// In your Worker the same statements go through `env.DB.prepare(sql).bind(…).run()`, and the statements that must happen together
// go in one `env.DB.batch([…])`.

import { randomBytes } from "node:crypto";
import { pathToFileURL } from "node:url";

export const MAX_INDEX = 1_000_000;

export const SCHEMA = `
  CREATE TABLE IF NOT EXISTS counter (id INTEGER PRIMARY KEY CHECK (id = 1), next INTEGER NOT NULL);
  INSERT OR IGNORE INTO counter (id, next) VALUES (1, 0);
  CREATE TABLE IF NOT EXISTS checkouts (
    id TEXT PRIMARY KEY,
    idx INTEGER NOT NULL UNIQUE,            -- one index, one address: two checkouts never share one
    address TEXT NOT NULL,
    quote TEXT NOT NULL,                    -- raw, as text
    status TEXT NOT NULL DEFAULT 'open',    -- open | paid
    paid_hash TEXT UNIQUE                   -- the block that paid: one block pays one checkout, once (NULLs never collide)
  );
  CREATE TABLE IF NOT EXISTS locks (name TEXT PRIMARY KEY, owner TEXT NOT NULL, until INTEGER NOT NULL);
`;

/** Opens the database on node:sqlite. In a Worker you use env.DB, and the schema is a migration. */
export async function openDatabase(path) {
  const { DatabaseSync } = await import("node:sqlite");
  const db = new DatabaseSync(path);
  db.exec("PRAGMA busy_timeout = 5000;");
  db.exec(SCHEMA);
  return db;
}

/**
 * Step 1. Makes a checkout with the next index. The counter and the checkout change in ONE transaction, so there is no checkout
 * without its index and no index that two checkouts share. (In D1: the two statements in one `batch`.)
 */
export function openCheckout(db, { id, address, quote }) {
  db.exec("BEGIN IMMEDIATE");
  try {
    const next = db.prepare("SELECT next FROM counter WHERE id = 1").get().next;
    if (process.env.EDGE_TEST_PAUSE_MS) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(process.env.EDGE_TEST_PAUSE_MS)); // tests only
    if (next >= MAX_INDEX) throw new Error(`The counter reached ${MAX_INDEX}: that is a bug or an attack, so nothing is made.`);
    db.prepare("INSERT INTO checkouts (id, idx, address, quote) VALUES (?, ?, ?, ?)").run(id, next, address, quote);
    db.prepare("UPDATE counter SET next = next + 1 WHERE id = 1").run();
    db.exec("COMMIT");
    return next;
  } catch (e) {
    db.exec("ROLLBACK");
    throw e;
  }
}

/** Step 6. Marks the checkout paid with this block, once. `used`: the block paid another checkout. `taken`: this checkout was paid already. */
export function credit(db, { id, hash }) {
  try {
    const r = db.prepare("UPDATE checkouts SET status = 'paid', paid_hash = ? WHERE id = ? AND status = 'open'").run(hash, id);
    return Number(r.changes) === 1 ? "paid" : "taken";
  } catch (e) {
    if (/UNIQUE/i.test(String(e?.message ?? e))) return "used";
    throw e;
  }
}

/** Step 7. Takes the sweep's lock: one statement that makes the row, or takes it over once its time has passed. */
export function takeLock(db, { name, ttlMs, owner = randomBytes(8).toString("hex"), now = Date.now() }) {
  const r = db
    .prepare("INSERT INTO locks (name, owner, until) VALUES (?, ?, ?) ON CONFLICT (name) DO UPDATE SET owner = excluded.owner, until = excluded.until WHERE locks.until <= ?")
    .run(name, owner, now + ttlMs, now);
  return Number(r.changes) === 1 ? owner : null;
}

async function main(args) {
  const [command, path, a, b, c] = args;
  let db;
  try {
    db = await openDatabase(path);
  } catch (e) {
    if (/node:sqlite|ERR_UNKNOWN_BUILTIN_MODULE/i.test(String(e?.message ?? e))) {
      console.error("node:sqlite is not in this Node.js: use Node.js 22 or newer.");
      process.exit(9);
    }
    throw e;
  }
  if (command === "open") return console.log(openCheckout(db, { id: a, address: b, quote: c }));
  if (command === "credit") return console.log(credit(db, { id: a, hash: b.toUpperCase() }));
  if (command === "lock") return console.log(takeLock(db, { name: a, ttlMs: Number(b) }) ? "held" : "busy");
  if (command === "show") {
    for (const row of db.prepare("SELECT id, idx, address, quote, status, paid_hash FROM checkouts ORDER BY idx").all()) console.log(JSON.stringify(row));
    return;
  }
  throw new Error("Commands: open, credit, lock, show. Read the top of this file.");
}

// Run the command line only when this file is started by itself, not when your Worker or server imports it.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  main(process.argv.slice(2)).catch((e) => {
    console.error(e?.message ?? e);
    process.exit(1);
  });
}

What runs the timer

// wrangler configuration
"triggers": { "crons": ["0 3 * * *"] }    // once a day, 03:00 UTC: the sweep

// the Worker
export default {
  async scheduled(event, env, ctx) {
    ctx.waitUntil(sweepIfDue(env));        // takes the sweep lock first, and stops when another run holds it
  },
  async fetch(request, env) { /* the checkout and claim routes */ },
};
The Cron Trigger, and three points

A Cron Trigger calls your Worker's scheduled handler on a schedule that you write in the configuration. The starter runs one every 10 minutes and asks a node only when an order is waiting.

  • The sweep takes the lock first (takeLock), and stops when it is busy.
  • Never from a visitor's request. Only the timer starts a sweep.
  • The limits are open. The configuration of our starter says that the Free plan fixes a request at 10 ms of CPU and 50 calls to the outside, and that a Paid plan can set its own limits. A sweep for one address makes about 7 calls to your node (the block, the account, two proofs of work, two blocks). Not checked: that signing fits in a Worker's CPU limit. On the computer where we wrote this guide (Node.js 24.13.0, warm) signing a receive block took about 2.2 ms and a send block about 2.4 ms. A Worker is not that computer: measure on yours before you rely on it.
Rule

Run the sweep and the returns only from the timer, and let one run hold the lock. Do not call a node from a request just to sweep.

Run the whole thing

This script does steps 1 to 5 and step 7 for one checkout (step 6 is your database's job). It needs one package, nanocurrency-web. Make a throwaway secret, then pay the amount it prints from any wallet and watch it see the payment:

npm install nanocurrency-web
export CHECKOUT_SECRET=$(openssl rand -hex 32)   # a throwaway secret: write it down
node accept-nano.mjs --address 0                 # the address of checkout 0
NANO_RPC=https://your-node.example/rpc node accept-nano.mjs 0.001 0
Warning

Write the secret down before you pay. It lives only in that terminal. Whoever has it can move the money at its addresses, and without it nobody can. Pay a tiny amount while you test.

To test without paying, point it at a send you already received:

NANO_RPC=https://your-node.example/rpc \
  node accept-nano.mjs --check <send block hash> <checkout address> <quote in raw>

When it says paid, it prints the sweep command. The sweep sends exactly the quote to the address in NANO_DESTINATION:

NANO_RPC=https://your-node.example/rpc NANO_DESTINATION=nano_… \
  node accept-nano.mjs --sweep <index> <send block hash> <quote in raw>
accept-nano.mjs198 lines
accept-nano.mjsDownload
// Accept one Nano payment at its own address, without a payment processor.
// From the nano133.com guide "Accept Nano payments without a processor".
// Node.js 18 or newer, one package (npm install nanocurrency-web). MIT license.
//
//   export CHECKOUT_SECRET=$(openssl rand -hex 32)      # a throwaway secret for a test
//   NANO_RPC=https://your-node.example/rpc node accept-nano.mjs <price in XNO> <index>
//       derives the checkout's own address, prints the payment link, and waits
//       (15 minutes) until a confirmed send of exactly the quote arrives there.
//
//   node accept-nano.mjs --address <index>
//       prints the address of one index (it needs no node).
//
//   NANO_RPC=… node accept-nano.mjs --check <send block hash> <address> <quote in raw>
//       checks one block the way the checkout does, without a payment.
//
//   NANO_RPC=… NANO_DESTINATION=nano_… node accept-nano.mjs --sweep <index> <send block hash> <quote in raw>
//       receives that one paid block at the checkout's address and sends exactly
//       the quote on to NANO_DESTINATION, your own wallet.
//
// In a shop the secret comes from your secret manager and the index from an
// atomic counter in your database. Never print or log the secret. Use your own
// node: its answers decide what you credit and what you send. It must allow
// receivable, block_info, account_info, work_generate and process.

import { createHmac } from "node:crypto";
import nano from "nanocurrency-web";

const { wallet, block, tools } = nano;
const RPC = process.env.NANO_RPC;
const RAW_PER_XNO = 10n ** 30n;
const STEP = 10n ** 26n; // a clean quote is a whole number of 0.0001 XNO
const OPEN_MS = 15 * 60_000; // a checkout is open for 15 minutes
const GRACE_MS = 60 * 60_000; // and a late payment still counts for 1 hour after that
const SLACK_MS = 2 * 60_000; // your clock and your node's clock may differ by a little
const LABEL = "nano133 kit checkout seed v1"; // never change it, or the secret, after the first checkout
const SEND_WORK = "fffffff800000000";
const RECEIVE_WORK = "fffffe0000000000";

async function rpc(body) {
  const res = await fetch(RPC, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(25_000) });
  const json = await res.json();
  if (json.error) throw new Error(`${body.action}: ${json.error}`);
  return json;
}

/** Step 1. Checkout number `index`: one account of the seed that your secret makes. */
function accountOf(secret, index) {
  if (typeof secret !== "string" || secret.length < 32) throw new Error("Set CHECKOUT_SECRET to at least 32 characters (openssl rand -hex 32).");
  const seed = createHmac("sha256", secret).update(LABEL).digest("hex").toUpperCase();
  return wallet.legacyAccounts(seed, index, index)[0]; // .address is public; never show or log .privateKey
}

/** Step 2. "0.05" XNO → raw, rounded UP to a whole 0.0001 XNO. A price below 0.0001 XNO is refused. */
function cleanQuote(xno) {
  const [whole, frac = ""] = String(xno).split(".");
  const raw = BigInt(whole || "0") * RAW_PER_XNO + BigInt((frac + "0".repeat(30)).slice(0, 30));
  if (raw < STEP) throw new Error("A price below 0.0001 XNO is refused.");
  return ((raw + STEP - 1n) / STEP) * STEP;
}

const toXno = (raw) => {
  const s = raw.toString().padStart(31, "0");
  const frac = s.slice(-30).replace(/0+$/, "");
  return `${s.slice(0, -30).replace(/^0+(?=\d)/, "")}${frac ? `.${frac}` : ""}`;
};

/**
 * Step 5. Does `hash` pay this checkout? A send, to `to`, of exactly `quote`,
 * first seen by the node inside the window, and confirmed.
 */
async function check(hash, to, quote, window) {
  const b = await rpc({ action: "block_info", hash, json_block: "true" });
  const subtype = b.subtype ?? b.contents.subtype;
  if (subtype !== "send") return "not a send";
  if (b.contents.link_as_account !== to) return "sent to another address";
  if (b.amount !== quote) return "another amount";
  const seen = Number(b.local_timestamp ?? 0) * 1000;
  if (window && !(seen > 0 && seen >= window.from - SLACK_MS && seen <= window.until + SLACK_MS)) return "sent outside this checkout's window";
  return b.confirmed === "true" ? "paid" : "not confirmed yet";
}

/** Step 4. Sends of exactly `quote` that wait at the checkout's own address. */
async function candidates(to, quote) {
  const r = await rpc({ action: "receivable", account: to, count: "50", threshold: quote, source: "true" });
  return Object.entries(r.blocks || {})
    .filter(([, v]) => v.amount === quote)
    .map(([hash]) => hash);
}

const notFound = (e) => /not found/i.test(String(e?.message ?? e));

/**
 * Step 7. Receive the ONE paid block at the checkout's address, then send exactly the quote to `destination`.
 * The address's own balance is this script's record: after the send it holds nothing more than before, so a
 * second run finds nothing to send. A shop also records the signed send before it publishes it.
 */
async function sweep(secret, index, hash, quote, destination) {
  const acct = accountOf(secret, index);
  if (!tools.validateAddress(destination)) throw new Error("NANO_DESTINATION is not a valid Nano address.");
  if (destination === acct.address) throw new Error("The destination is the address being swept.");
  // Stop unless the block is a confirmed send of exactly the quote to THIS address.
  const verdict = await check(hash, acct.address, quote, null);
  if (verdict !== "paid") throw new Error(`Nothing moves: ${verdict}.`);
  const paid = await rpc({ action: "block_info", hash, json_block: "true" });
  const amount = BigInt(quote);
  const info = await rpc({ action: "account_info", account: acct.address, representative: "true" }).catch((e) => (notFound(e) ? null : Promise.reject(e)));
  let frontier = info?.frontier ?? null;
  let balance = BigInt(info?.balance ?? "0");
  const rep = info?.representative ?? (await rpc({ action: "account_info", account: paid.block_account, representative: "true" }).catch(() => null))?.representative ?? paid.block_account;
  const work = async (root, difficulty) => (await rpc({ action: "work_generate", hash: root, difficulty })).work;

  // 1. Receive that one block (not everything that waits here: a wrong amount belongs to Late Payment Return).
  const recv = block.receive(
    {
      walletBalanceRaw: balance.toString(),
      toAddress: acct.address,
      representativeAddress: rep,
      frontier: frontier ?? "0".repeat(64),
      transactionHash: hash,
      amountRaw: quote,
      work: await work(frontier ?? acct.publicKey, RECEIVE_WORK),
    },
    acct.privateKey,
  );
  try {
    frontier = (await rpc({ action: "process", json_block: "true", subtype: info ? "receive" : "open", block: recv })).hash;
    balance += amount;
  } catch (e) {
    if (!/unreceivable/i.test(String(e?.message ?? e))) throw e; // an earlier run received it: the balance already holds it
  }
  if (!frontier) throw new Error("The payment is not in the address.");

  // 2. Send exactly the quote on, once. A balance above the quote stays.
  if (balance < amount) throw new Error("Nothing to send: an earlier run already moved it on.");
  const send = block.send(
    {
      walletBalanceRaw: balance.toString(),
      fromAddress: acct.address,
      toAddress: destination,
      representativeAddress: rep,
      frontier,
      amountRaw: quote,
      work: await work(frontier, SEND_WORK),
    },
    acct.privateKey,
  );
  return (await rpc({ action: "process", json_block: "true", subtype: "send", block: send })).hash;
}

async function main() {
  const args = process.argv.slice(2);

  if (args[0] === "--address") {
    console.log(accountOf(process.env.CHECKOUT_SECRET, Number(args[1])).address);
  } else if (!RPC) {
    console.error("Set NANO_RPC to your node's RPC URL.");
    process.exit(1);
  } else if (args[0] === "--check") {
    const [, hash, to, quote] = args;
    console.log(await check(hash, to, quote, null));
  } else if (args[0] === "--sweep") {
    const [, index, hash, quote] = args;
    console.log(`Swept: send block ${await sweep(process.env.CHECKOUT_SECRET, Number(index), hash, quote, process.env.NANO_DESTINATION ?? "")}`);
  } else {
    const [price, index] = args;
    if (!(Number(price) > 0) || !Number.isInteger(Number(index)) || Number(index) < 0) {
      console.error("Usage: node accept-nano.mjs <price in XNO> <index>");
      process.exit(1);
    }
    const to = accountOf(process.env.CHECKOUT_SECRET, Number(index)).address;
    const quote = cleanQuote(price).toString();
    const created = Date.now();
    const window = { from: created, until: created + OPEN_MS + GRACE_MS };
    console.log(`Pay exactly Ӿ${toXno(BigInt(quote))} to ${to}`);
    console.log(`Wallet link: nano:${to}?amount=${quote}`);
    console.log("Waiting for the payment…");
    const seen = new Set();
    while (Date.now() < created + OPEN_MS) {
      for (const hash of await candidates(to, quote)) {
        const result = await check(hash, to, quote, window);
        if (result === "paid") {
          console.log(`Paid: block ${hash}. Record this hash so it pays only one checkout.`);
          console.log(`To move it on: node accept-nano.mjs --sweep ${index} ${hash} ${quote}`);
          process.exit(0);
        }
        if (!seen.has(hash + result)) console.log(`${hash.slice(0, 12)}…: ${result}`);
        seen.add(hash + result);
      }
      await new Promise((r) => setTimeout(r, 2000));
    }
    console.log("The checkout expired with no payment.");
  }
}

main().catch((e) => {
  console.error(e?.message ?? e);
  process.exit(1);
});
Warning

The example keeps nothing between runs. In your shop, steps 1, 6 and 7 belong in your database, inside transactions: the counter, the used block hashes, and the signed send of each sweep with its lock. Checked so far: steps 1 to 5 against a real Nano node (21 October 2026), and the sweep against a local copy of the ledger, because a real sweep moves real Nano. Test it with a tiny amount first.

Or use the kit

Nano Checkout packages these steps: an address for each checkout (createDerivedCheckout) with a clean quote, the exact payment check (claimCheckout), one use per block, the sweep (sweepPaid), signed receipts, and derivedReturns for Late Payment Return, with stores for Firestore or your own database. It is the same logic as this guide: with the same secret and the same index, the package and the script above give the same address. Install it with npm install @nano133/checkout nanocurrency-web @noble/hashes and import it from @nano133/checkout/derived.

The keyless way: one address and a unique amount

Warning

The keyless way gives every checkout your one address and asked for the price plus a small random tail in the last digits (1 to 999,999 raw). It needs no key on your server, only your address, so nobody can take money from your site. Its limit: a wallet that cuts or rounds the amount before it sends can never be matched, as in the Cake Wallet case above. The buyer pays and gets nothing until someone sends the money back. Pick it when you want the simplest set-up and no key, for example on a Cloudflare Worker. If you can keep a seed on a server and want every wallet to work, use an address for each checkout. The package supports both, and the old calls work as they did; Nano Checkout has the details.

What breaks, and what it costs

  • The secret leaks
    Loss in Nano
    Everything that waits at every checkout address, and every address made later
    Check
    Steps 1 and 7: the secret stays on the server, in a secret manager, and the sweep keeps little at an address
  • The secret or its label changes after money came in
    Loss in Nano
    The money stays at the older addresses. Only the old secret and label sweep or return it
    Check
    Step 1: never change either once money has come in
  • A wallet cuts or rounds the amount (a tail, in the keyless way)
    Loss in Nano
    The buyer pays and gets nothing until the money goes back
    Check
    Step 2: a clean quote with no tail. Step 8: send any other amount back in full
  • A block is credited twice
    Loss in Nano
    One block pays two checkouts, or one checkout twice
    Check
    Step 6: record the block hash and mark the checkout paid in one transaction
  • The sweep runs twice, or crashes after the send
    Loss in Nano
    A second send of the same payment
    Check
    Step 7: record the signed send before you publish it, and let one run hold the checkout
  • The sweep reads its destination from a request or a row
    Loss in Nano
    The money goes to an address that a visitor chose
    Check
    Step 7: the destination is fixed in your code
  • Your node does not answer
    Loss in Nano
    A wrong credit, if you do not fail closed
    Check
    Step 8: answer “busy” and credit nothing

Sources

Written by nano133.com from code that runs on this site. Code: MIT license.