nemr.app

BlockchainEngineering

How I Built a USDT Bridge Between Minima and Ethereum

· 12 min read · by Elias Nemr

Inside a USDT bridge between Minima and Ethereum: the contract, monitors, queues, batching, refunds, alerting, the outages that shaped it, and an honest trust model.

Moving a stablecoin between two very different blockchains looks simple on a whiteboard and turns out to be mostly edge cases. Over roughly eleven months and more than three hundred commits, I built, alone, a bridge that lets people swap USDT on Ethereum for a USDT-backed token on the Minima network, and back again.

This is the engineering story: how the pieces fit together, the design decisions that mattered, the outages and near-misses that reshaped the code, and the honest trust model. The live bridge is at mxusd.global.

Educational, not financial advice. Bridges carry real risk. This describes the design as it was documented and built through 2026 (the project's public documentation was last updated on 20 August 2026), so check the live site for current figures, limits and protections before relying on anything here.

What it is, and what it isn't

The token on the Minima side is a claim on USDT held on Ethereum. When you swap USDT for it, your USDT is taken into custody on Ethereum and an equal amount of the Minima token is released to you. Swap back, and the token returns to the bridge and USDT is sent to your Ethereum address.

This is an operated bridge, not a trustless one: an operator holds keys and runs the services that make payments. That's a legitimate design with real trade-offs, and part of this post is about making them visible. (For the trust-minimised alternative, see my guide to bridging two L1s with different scripting languages using HTLCs.)

The system at a glance

The project is a monorepo of five packages that deploy and scale separately:

PackageRole
ContractsSolidity bridge contract (OpenZeppelin 5, Hardhat), with about 50 tests.
APIA GraphQL service (Keystone) on PostgreSQL: the system of record for every deposit.
Web appA Next.js front end where Ethereum users connect a wallet and deposit.
MiniDappA Minima-native app that lets Minima users swap from inside their own node UI.
ProcessorsTypeScript services that watch both chains and make payments: monitors, queue workers and schedulers.
Ethereum --events--> Ethereum monitor --> API/DB --> queue --> Minima worker --> payout on Minima
Minima  --coins---> Minima monitor   --> API/DB --> queue --> Ethereum worker --> payout on Ethereum
                                          ^                         |
                                          '---- status updates -----'

Every deposit, whichever way it travels, becomes a row in the database, and everything else is a service moving that row through a state machine.

The contract: small, boring, defensive

The Ethereum contract does only what has to be on-chain:

  • Deposits of supported ERC-20 tokens, each with a configured minimum and maximum, recorded with the depositor, amount, destination Minima address and timestamp, and announced with an event the monitors watch.
  • A refund path. A deposit that hasn't been paid out becomes refundable after two hours, and the depositor can trigger it, not just the operator.
  • Owner controls: add or remove tokens and limits, withdraw swept deposits, pause the bridge, and switch refunds off globally or for a single deposit.
  • Standard defences: reentrancy guards, pausing, safe token transfers, and a requirement that the token reports decimals.

The refund rule is the one worth reading carefully. Conceptually, a deposit is refundable only if all of these hold:

deposit exists
AND not already withdrawn or refunded
AND refunds are globally enabled
AND refunds are not disabled for this deposit
AND now >= deposit time + 2 hours

The tests cover this rule from every side: not refundable immediately, refundable after the window, not refundable once swept, not refundable when switched off, refundable by the depositor and by the owner, and rejected for anyone else. Decimals get their own tests: 18-decimal, 6-decimal (like USDT) and zero-decimal tokens, because mixing up units is the classic bridge bug.

The database is the state machine

Each deposit row moves through explicit states:

pending    -> deposit event detected
queued     -> added to the payment queue
processing -> a worker has claimed it
completed  -> paid on the destination chain
failed     -> gave up, with a human-readable reason
refunded   -> returned to the depositor

(plus a separate withdrawal status: withdrawn / withdrawal_failed)

A few decisions here paid for themselves repeatedly:

  • Unique keys do the idempotency. The deposit ID and the Minima coin ID are unique. If a monitor sees the same deposit twice, the second write simply fails to create a duplicate.
  • The fee is stored on the deposit. The base fee and percentage that applied at payment time are recorded per row, so later config changes never rewrite history. The payout is amount − max(baseFee, amount × percentage): a floor, not an extra charge.
  • Every state change carries a message. "Batch processing started", "Invalid Mx address: …", "Batch payment completed. Transaction: …". When something goes wrong, the row tells you why.

Watching two chains

Ethereum: cursor, confirmations and rate limits

The Ethereum monitor polls for contract events in block ranges. It keeps a cursor in the database (the last processed block, falling back to the contract's deployment block on first run), so a restart picks up exactly where it stopped. It only acts after a configurable number of confirmations (12 by default) so that a reorganisation can't make the bridge pay out against a deposit that no longer exists. Public RPC providers rate-limit, so a "too many requests" error puts the work back on the queue instead of failing the swap.

Minima: no events, so poll coins

Minima has no event logs to subscribe to. The monitor instead asks a payment service for the coins sitting on the bridge's deposit address, at a minimum coin depth (its version of confirmations). It parses each coin into a deposit, enforces the minimum and maximum amount, and filters out coin IDs it has already recorded. One detail came from an actual failure: when that payment service is down, it answers with a status flag and no payload. The first version destructured that into undefined and crashed with an unhelpful TypeError. Now the monitor checks the shape, logs "no coin list, skipping this poll", and tries again, backing off on errors.

Paying out: queues, batches and pure validation

Payments run on BullMQ queues backed by Redis. Workers process one job at a time with a rate limiter, jobs retry with exponential backoff, and finished jobs are pruned automatically.

Minima payouts are batched, in groups of ten, and deposits to the same Minima address are grouped so that a person who deposits twice is paid in one transaction. The batch processor follows a strict sequence:

  1. Validate each deposit: it exists, it's still queued, it has a destination address, and the node confirms that address is valid. Invalid ones are marked failed with the reason, immediately.
  2. Mark valid ones processing so no second worker can claim them.
  3. Pay the batch in a single transaction through the payment service.
  4. Map results back to individual deposits and write each one's outcome (transaction ID, block, fee used) to the database.
  5. If anything throws, mark everything still in processing as failed with the error message, so nothing is left in limbo.

The validation functions are deliberately pure: they read and return a verdict, and the orchestrator alone changes state. That separation made the logic easy to test and made it obvious where every state transition happens.

Money handling

  • Hot and cold wallets. Funds needed for payouts sit in hot wallets; excess is swept to cold storage by a scheduled job. There's also a rebalancer job for topping up hot-wallet balances.
  • Gas is a dependency. The bridge checks the hot wallet's ETH balance and raises an alert as it runs low, because a bridge that can't pay gas can't pay anyone.
  • Refunds on both sides. Ethereum refunds are contract-enforced. A scheduler also runs on an interval to handle refunds for Minima-initiated deposits that couldn't be completed.

Observability: the part I'd copy first

Most of the reliability came from a few observability ideas that are cheap to build:

  • Liveness by absence. Each service writes a key to Redis on an interval with a time-to-live. If the key is absent, the process is dead or wedged. No clock comparison is needed, and nothing can silently go stale. The TTL must comfortably exceed the longest alarm threshold, otherwise the key expires before the check can call the service stale and the alarm never fires.
  • A quiet alert channel. Activity (new swap, status changes) streams to one Telegram channel. Failures also go to a separate health channel that speaks only when something changes, so a message there means a human is needed. A failed swap in a busy activity feed reads like any other line and gets scrolled past.
  • Alert state survives redeploys. The last-known status of each check is stored, so a redeploy doesn't re-alert. While something stays broken, it repeats at a sensible interval, not on every poll.
  • A daily "all green" message, so that silence keeps meaning something.
  • Alerts never block the write path. The hooks that send them are fire-and-forget and can't throw, so Telegram being down can never stop a deposit being recorded.
  • Plus the usual: error tracking, structured logs and a queue dashboard.

Incidents that shaped the code

The transaction that was never going to confirm

A sweep transaction was broadcast with a priority fee so low that it was dropped from the mempool. The code waited for its receipt with no timeout. The worker sat waiting for something that would never exist. Because the queue renews a job's lock while the process is alive, the job never stalled out and was never reclaimed, so the queue held one "active" job for many hours and no deposit could be swept. The heartbeat and the health endpoint stayed green throughout, because the process was perfectly healthy; it was just stuck.

The fix had two parts. First, every receipt wait is now bounded. Second, and more important, a timeout is treated as "outcome unknown", not as a failure. The transaction might still mine later, or it might have been dropped, and recording a definite failure could strand a deposit that actually settled. The right response is to re-check on-chain state.

// the shape of the fix
const receipt = await Promise.race([tx.wait(), timeout(LIMIT)]);
if (!receipt) throw new ReceiptTimeout(tx.hash);   // UNKNOWN, not failed
// callers re-check the chain instead of recording a failure

The lesson: a green health check only proves the process is alive. Monitor progress (is work completing?), not just liveness.

Verify before you close the escape hatch

A deposit's refund window closes when the bridge sweeps the funds out of the contract. A later hardening change of mine made the order of operations explicit: verify that the Minima payout is on-chain, with confirmations, before sweeping. The bridge is not allowed to close the user's escape hatch until it has proven the user was paid. Any irreversible step should wait for evidence that the step before it really happened.

Deploys that can strand a deposit

Because batching happens in memory for a short window, restarting containers at the wrong moment could leave a deposit stuck at queued, a state no query selects. So the deploy script encodes the safety gates learned during a hardening pass:

  • refuse to deploy while any deposit is in flight;
  • refuse on a dirty working tree, so the running image always matches a commit you can find;
  • take a fresh database dump first;
  • tag the outgoing image so rollback is one command, not a rebuild;
  • stamp the new image with the git SHA, so "what is running?" has an answer;
  • bring the API up and wait for it to be healthy before starting the processors that depend on it;
  • verify afterwards, and print the rollback command if anything fails.

Turning hard-won lessons into a script means the next deploy, by me or anyone else, can't repeat them by accident.

A Minima-native front end

Ethereum users connect a wallet to the web app. Minima users don't have wallets in the browser; they run a node with its own UI. So there's also a MiniDapp: a small React app that runs inside the Minima node, previews the fee, sends the tokens to the bridge's deposit address, remembers the deposit IDs locally and shows a receipts page. Meeting each ecosystem's users where they already are made the bridge feel native on both sides.

The honest part: verifiable versus attested

I wrote a plain-language guide to checking the bridge yourself, built on one idea: separate what you can verify from what you must trust.

ClaimStatus
USDT held in custody on EthereumVerifiable by anyone, on-chain, permanently
The token you hold is the genuine oneVerifiable via Minima's domain-validation mechanism
Your own swap completedVerifiable on both chains
The contract's rules and your refund rightVerifiable in the contract code
Circulating supply and treasury holdings on MinimaAttested: you're trusting the operator

Why can't the Minima side be checked independently? Minima prunes spent history, and a node can only read the coins of addresses it tracks, so an outsider can't total an address or list a token's holders. Publishing treasury addresses would have looked like proof while providing none, so I labelled those figures "attested, not verifiable" instead. An honest label beats a convincing-looking number.

One small, valuable check: anyone can create a token called "USDT" on Minima. The guide's first step is confirming your token's ID matches the one published at the bridge's own domain.

The trust model, stated plainly

As documented, trust was concentrated, and I said so in the documentation:

  • Custody was a single externally-owned key, not a contract with autonomous rules.
  • The same key controlled the contract: pause, refunds, withdrawals. There was no multisig and no timelock.
  • The contract had not been independently audited.
  • Backing relied on policy, not an on-chain rule.

The natural hardening steps are multisig or MPC custody, timelocked admin actions and an independent audit. Writing the model down doesn't make it a problem; hiding it would.

What I'd tell anyone building a bridge

  • Choose your trust model first and publish it in plain language.
  • Wait for finality, and verify your own payouts before releasing anything irreversible.
  • Give users an exit that works without you, and be clear about its limits.
  • Make the database a state machine with explicit states, unique keys and a message on every transition.
  • Bound every wait. A timeout means "unknown"; re-check the chain, don't assume failure.
  • Monitor progress, not just liveness. Use liveness-by-absence, a quiet alert channel and a daily all-green message.
  • Encode deploy lessons in a script with gates, backups and one-command rollback.
  • Treat gas and rate limits as production dependencies.
  • Separate "verifiable" from "attested" in everything you publish.

For the theory behind trust-minimised designs, read how to bridge two blockchains with HTLCs and the developer's mental model of blockchains. If you're designing cross-chain infrastructure and want a second pair of eyes, say hello.

Elias Nemr is a software engineer who has built and shipped products across Blockchain, Finance, E-Commerce, AI, Energy and Indie Games. More about him →

Found this useful? Buy me a coffee

Keep reading