← Writing

How Mayarin Clears a Payment: A Tour of the System

· By Rizkyy. · 7 min read

How Mayarin Clears a Payment: A Tour of the System
On this page

Mayarin is a programmable clearing layer. A merchant prices in their local currency and settles in a stablecoin; the payer brings whatever supported asset they hold. The payer can be a person at a checkout, an application, or an autonomous agent paying over x402. All three reach the same clearing engine, the same ledger and the same merchant.

This post walks through the system from the request at the edge down to the merchant's Safe, and explains the few rules that keep it correct when chains are slow, RPCs fail and processes crash halfway through a payment.

The centre: a nine-state clearing engine

Everything in Mayarin revolves around one state machine. Each payment walks the same nine states, and each state records exactly one thing that moved:

# State What moves
1 CREATED Intent opened
2 QR_PARSED Merchant QR read
3 PRICE_LOCKED Quote signed, amounts as bigint
4 PAYMENT_PENDING Deposit address waits for funds
5 ASSET_RECEIVED Chain worker saw the deposit
6 CLEARING Ledger postings sum to zero
7 SETTLING PaymentRouter pays out to a Safe
8 SETTLED Transaction confirmed on chain
9 SUCCESS Webhook sent to the merchant

FAILED is reachable from any non-terminal state.

Four rules hold the engine together.

1. Every step has a key. Each step is keyed ${transactionId}:${state}. Ledger postings and provider calls carry that key, so replaying a step never duplicates value.

2. Side effect first, then persist the state. A step does its work, then records the new state. If the process dies in between, the resumed step repeats what is now a no-op and records the state. Persisted state is the only input a step needs, so a stalled payment can always be picked up again.

3. A webhook is a signal, not truth. When a provider calls us, the engine wakes up and asks the provider for the authoritative status. A spoofed or replayed webhook cannot settle a payment on its own.

4. Never UPDATE a balance. Value moves only through balanced double-entry postings. An unbalanced posting raises an error instead of being written. Every state transition appends an event in the same database transaction as the state change, so the history and the current state cannot drift apart.

Money is never a float anywhere in this path. An amount is a bigint count of an asset's minor units, whether that is two-decimal rupiah or an 18-decimal ERC-20 balance. Rates and fees are integers too.

The edge

Merchants, payers and agents all enter through Cloudflare. A tunnel carries traffic to the API host, a small Worker proxies the pay pages, and the dashboard and landing site are served from the same edge.

Behind it sit two APIs:

  • core-api — payments, quotes, checkout and x402. This is the public payment surface.
  • dashboard-api — the merchant console: accounts, keys, configuration, reporting.

Both write to the same Postgres database, and both go through the clearing engine rather than touching tables directly.

The ledger: Postgres

A single Postgres 16 instance holds the ledger, the event log and the payment intents. It is private to the API host and has point-in-time recovery enabled.

The rule that matters here is the one on the diagram in red: a fix is a retry or a refund, never an edit to the ledger. If something goes wrong, the operator either resumes the payment so the engine finishes it, or issues a refund that is itself a new set of balanced postings. History is append-only.

Pricing: the liquidity router

When a payer brings an asset that is not the merchant's settlement asset, the liquidity router prices the conversion. It quotes through DEX aggregators and venues (Uniswap, LiFi, 0x) and checks the result against reference prices (Chainlink, Coinbase, Pyth). A quote that strays too far from the reference is rejected by a deviation guard.

The router sits behind a RateProvider port. The clearing engine does not know which venue answered; a new source plugs in without changing the engine.

The chain layer

The chain-worker is a separate process from the API. It has four jobs:

  • Deposit watcher — reads chain logs for the per-intent deposit addresses and reports each arrival to the clearing engine through a single seam, recordAssetReceived.
  • Treasury executor — sends the settlement transaction through the PaymentRouter contract.
  • Auto-return — sends back deposits that cannot be used for the payment.
  • Stuck alert — notices payments that have not moved.

The chain package knows the engine only as an injected sink. It never imports the clearing code, which keeps the dependency pointing one way.

On mainnet, Mayarin runs on Base, Polygon, BSC, Arbitrum, Optimism and Celo, with the same PaymentRouter and the same forwarder addresses on every chain. Testnet adds Solana, Tron, TON and Arc. Settlement lands in the merchant's Safe in USDC or USDT.

Signing keys never live on the host. The order signer used by core-api and the operator key used by the worker are held in AWS KMS, and the IAM policy refuses their use from anywhere but the API host.

Three ways a payment is funded

Separate from who pays, there are three execution paths, chosen per payment:

  1. Contract path — the payer calls the PaymentRouter directly.
  2. Deposit-match — the payer sends funds to a per-intent deposit address, and the worker matches the deposit to the intent.
  3. x402 — an agent signs one authorization; a facilitator settles it.

A payer can also fund a payment in local currency. TransFi takes QRIS, GCash or FPX and delivers stablecoin to the intent's deposit address. To the clearing engine, this is an ordinary deposit-match payment.

Merchant wallets are provisioned through Turnkey, so a merchant gets a working settlement wallet without handling keys.

Watching it run

Three independent checks watch production:

  • Stuck-payment check — polls for any payment sitting in one state for more than ten minutes and alerts on Telegram. The answer to an alert is always the same: Retry or refund, never edit the ledger.
  • Sentry — collects console.error and traces on mainnet.
  • UptimeRobot — sends HEAD /health to the API, the merchant API and the pay pages.

CloudTrail and GuardDuty report account-level events by email.

Where it runs

Mainnet runs on a single EC2 instance (t4g.medium) with Docker Compose, next to a private RDS Postgres. Testnet runs the same four services — core-api, dashboard-api, chain-worker and Postgres — on Railway.

One host is a choice, not an oversight. The clearing engine is resumable and idempotent, so a restart loses nothing; scaling out waits until real volume asks for it.

Takeaways

  • Put one state machine at the centre and make every step idempotent and resumable. Most failure handling then becomes "run it again".
  • Keep the ledger append-only. Fixes are new postings, never edits.
  • Treat every external signal — webhooks, chain events — as a reason to look, not as the answer.
  • Keep chains, pricing venues and providers behind ports, so adding a chain or a venue does not touch the engine.