We Rebuilt MYZ Payments Around a Canonical Ledger — Here’s What We Learned
When we started adding internal MYZ payments to MyZubster Marketplace, the obvious task looked simple:
buyer balance -= amount
seller balance += amount
That turned out to be the wrong level of abstraction.
The real challenge was not adding a payment button. It was making sure that every part of the application agreed on what a MYZ balance actually is.
During the implementation, we found multiple historical paths capable of representing or modifying MYZ independently.
That is exactly the kind of situation that eventually produces accounting bugs.
So instead of adding another payment path, we refactored the system around one rule:
There must be one canonical source of truth for spendable MYZ.
This post covers the architecture we implemented, the problems we found, and the trade-offs that are still open.
The original problem: balances were too easy to create
A field like this looks harmless:
{
userId,
balanceMYZ: 500
}
Until another subsystem has:
{
accountId,
myzCredit: 200
}
And another computes:
displayedBalance =
ledgerBalance +
mongoCredits -
utilityRedemptions;
Now the question becomes:
What is the user's real balance?
If multiple components can answer that question differently, the system no longer has a reliable accounting model.
That was the architectural problem we wanted to eliminate.
First principle: MYZ is an internal accounting unit
Before touching the code, we established the semantics.
MYZ is an internal MyZubster utility/accounting credit.
It is not automatically convertible into:
EUR
BTC
XMR
cash
and it is not represented by this implementation as an on-chain token.
This matters technically because it means we do not need an exchange-rate engine in order to spend MYZ.
If a Marketplace listing costs:
250 MYZ
the payment is simply:
250 MYZ
There is no intermediate:
250 MYZ → €X → seller
Likewise, a Zorgax plan can have an explicit MYZ price without deriving it from its EUR price.
The canonical ledger
The core service is:
src/services/myzLedgerApiService.js
Instead of mutating a user balance directly, transfers are recorded as ledger entries.
A payment creates two legs:
buyer -250 MYZ
seller +250 MYZ
Both are linked by the same:
transfer_id
Conceptually:
transfer_id: T-123
┌─────────────────┐
buyer account │ -250 MYZ │
│ │
seller account │ +250 MYZ │
└─────────────────┘
This gives us something a plain balance field does not provide naturally:
auditability.
We can answer:
Why is this balance 750 MYZ?
by looking at the entries that produced it.
Transfers are atomic inside the ledger
The transfer operation performs both accounting legs under the same write operation.
The important invariant is:
debit exists ⇔ credit exists
We do not want:
buyer -250
without:
seller +250
because the process crashed halfway through.
The ledger therefore validates the transfer first, then persists both entries together.
The relevant checks include:
valid payer
valid payee
payer != payee
valid amount
sufficient balance
valid idempotency key
no transfer ID collision
Only after those checks do the entries become recorded.
Never trust the UI to prevent overspending
One of the tests we cared about most was not:
Can Alice buy an item?
It was:
Can Alice buy two items at the same time
when she can only afford one?
Example:
Alice balance: 300 MYZ
Purchase A: 250 MYZ
Purchase B: 250 MYZ
Both requests may arrive concurrently.
A naïve implementation can do this:
if (balance >= 250) {
// request A sees 300
}
if (balance >= 250) {
// request B also sees 300
}
Then both succeed.
Final logical balance:
-200 MYZ
That is unacceptable for an accounting system.
Our expected result is:
one purchase succeeds
one purchase fails
final balance = 50 MYZ
The protection belongs in the ledger write path, not in React.
Idempotency became a first-class concept
Payment APIs are retried.
Browsers retry.
Networks fail.
Users double-click.
Servers can complete the financial operation and crash before returning 200 OK.
So this API:
POST /api/marketplace/orders/:id/payment/myz
requires an idempotency key.
A simplified request looks like:
Idempotency-Key: marketplace-order-123
If the exact operation is retried, we return the original transfer instead of charging again.
But there is another subtle problem.
What happens if somebody reuses the same idempotency key with a different payload?
For example:
key = abc
plan = Zorgax Pro
amount = 40 MYZ
followed by:
key = abc
plan = Zorgax Developer
amount = 40 MYZ
The amount is identical, but the operation is not.
So idempotency is bound not only to the numeric amount, but also to the semantic reference of the operation.
Same key + different meaning = conflict.
That protects against a class of bugs that simple "key already exists" implementations often miss.
Marketplace became a true buyer → seller transfer
For MYZ-priced Marketplace orders, the flow is now:
Buyer
↓
canonical MYZ transfer
↓
Seller
↓
order marked PAID
The order stores evidence of the accounting operation:
payment: {
asset: 'MYZ',
network: 'internal-ledger',
status: 'PAID',
transferId,
debitEntryId,
creditEntryId
}
We also enforce several business invariants.
The buyer must be authenticated.
The buyer must actually own the order.
Buyer and seller cannot be the same account.
The order must be accepted before payment.
And an unpaid MYZ order cannot transition to completed.
The important point is that these rules are checked server-side.
The React button is just UX.
Application state and ledger state are not the same transaction
There is an interesting systems problem here.
The MYZ ledger and the Marketplace order are not stored in the same transactional database.
So this can happen:
- MYZ transfer succeeds
- application crashes
- order has not yet been marked PAID
You cannot solve that with a normal database transaction across unrelated stores.
Instead, we use an idempotent recovery model.
On retry:
ledger sees existing transfer
→ does not charge again
application receives original receipt
→ retries order persistence
This is closer to a small saga than a traditional ACID transaction.
The important requirement is recoverability.
Zorgax uses the same accounting primitive
We reused the same ledger for Zorgax plans.
The flow is:
user MYZ account
↓
canonical transfer
↓
zorgax:system:treasury
↓
grant entitlement
Prices are configuration values:
ZORGAX_PRO_PRICE_MYZ
ZORGAX_DEVELOPER_PRICE_MYZ
They are deliberately not calculated from:
priceEur
If the MYZ price is missing, the checkout fails closed.
Production currently reports the MYZ plan as unavailable instead of guessing a price.
That is a feature, not a failure.
The most important refactor was deleting shadow accounting
While reviewing the system, we found an older Payment Dashboard flow that effectively calculated MYZ like this:
canonical ledger
+
Mongo credits
Mongo redemptions
It also contained an automatic EUR → MYZ rule.
That meant the canonical ledger was not actually canonical.
So we changed the model.
New Stripe payments do not automatically generate MYZ.
Historical Mongo conversion records remain available as legacy audit data, but they no longer contribute to spendable MYZ.
Utility spending now hits the canonical ledger.
MongoDB redemption records are retained for things like:
fulfillment status
receipt metadata
application workflow
but they are no longer a second balance system.
That distinction is extremely useful:
ledger = accounting truth
application database = business state
Then we found another hard-coded system: Marketplace categories
The same development cycle uncovered a less dangerous but very visible problem.
The React Marketplace category list was mostly hard-coded.
That means adding a category required changing application code.
We replaced that with a dynamic catalog:
GET /api/listings/categories
Users can now propose new categories from the Marketplace itself.
The interesting UX decision is that the creator can use their pending category immediately for their own listing.
Global visibility still requires moderation.
So the flow becomes:
create category
↓
pending
↓
creator may use it
↓
admin review
↓
global category
This is much more flexible than making category taxonomy a deploy-time decision.
Knowledge became a Marketplace object too
We also introduced a first-class:
knowledge
category.
Users can submit things like:
guides
methods
know-how
tutorials
manuals
practical skills
through a separate knowledge submission flow.
But we explicitly did not connect submission directly to rewards.
A new knowledge item starts as:
PENDING_REVIEW
The API response explicitly indicates that creation does not produce:
reward
ledger write
MYZ transfer
This separation matters.
A useful architecture is:
submission
↓
review
↓
verification
↓
optional reward
not:
user submits text
↓
money appears
Deployment uncovered another important distinction
The code was merged through PR #1286.
Production deployment succeeded on Vercel.
Marketplace category endpoints respond correctly.
knowledge is available in production.
No fatal/runtime errors appeared during our verification window.
But we are intentionally not saying the MYZ accounting system is fully production-ready yet.
Why?
Because the current ledger implementation is file-based.
And there is a big difference between:
the application can write a file
and:
this storage is durable, shared, atomic,
and appropriate for production accounting
In a serverless environment, local filesystem assumptions deserve special attention.
A file lock only protects concurrent writers if those writers actually share the same durable filesystem.
Multiple isolated serverless instances may not.
So this implementation establishes the accounting contract and business logic, but production MYZ writes still need a properly durable storage architecture before we treat the system as authoritative under distributed load.
That may mean moving the ledger to a transactional database or placing it behind a dedicated single-writer service.
We also refused to fake a green CI status
One final engineering lesson came from CI.
We created a dedicated GitHub Actions workflow for the MYZ ledger contract.
It includes service tests, route tests, internal-payment tests, and ledger verification.
But GitHub did not generate a workflow run.
We even created a dedicated commit touching the workflow itself:
33180d233dd6abbb558ed58b56371d77eb11faa2
ci(myz): trigger canonical ledger contract
Still:
workflow runs = 0
Other workflows in the repository have execution history.
So instead of writing:
CI ✅
we documented:
CI execution issue still open
It sounds minor, but this is one of the habits that matters most in engineering:
do not convert “we expected this to run” into “it passed.”
The architecture now looks much simpler
Before:
Dashboard MYZ
Payment Dashboard MYZ
Marketplace payment logic
Zorgax payment logic
conversion logic
redemption records
After:
CANONICAL MYZ LEDGER
│
┌────────────────┼────────────────┐
│ │ │
Marketplace Zorgax P2P
│ │
buyer → seller user → system
Business databases still exist.
They should.
But they track business state.
They no longer get to invent their own spendable MYZ balance.
What I would improve next
The implementation is merged and deployed, but the architecture still has clear next steps:
move the ledger to genuinely durable shared storage;
validate double-spend protection across multiple application instances, not only within one process;
fix the GitHub Actions workflow execution;
add persistent purchase intents for even stronger recovery across client idempotency-key loss;
define explicit migration rules for historical MYZ records;
define verified identity mapping between older contributor: accounts and newer marketplace:user: accounts.
None of those invalidate the current work.
They define the boundary between correct application logic and production-grade distributed accounting infrastructure.
And knowing that boundary is probably the most useful lesson from this refactor.
The biggest takeaway for me was simple:
A balance is a derived value.
A ledger is the history that makes the balance trustworthy.
Once we started treating MYZ that way, Marketplace payments, Zorgax purchases, legacy cleanup, receipts, idempotency, and concurrency all became parts of the same system instead of separate features.
MyZubster is open source, and we’re building this architecture in public.
Repository: MyZubster-Ecosystem/myzubster
Main implementation: PR #1286