Tokenising energy plants: how the Finexswiss backend is built
A platform for shares in solar plants under the Swiss DLT Act. Why the blockchain only does one job, how EventFlow models orders as event-sourced aggregates and why the money stays off-chain.
The task
Finexswiss digitalises co-ownership of renewable energy plants. A project owner develops a solar plant, the plant is divided into shares, and the owner decides whether to keep them or offer part of them to investors. After that the plant has to be operated: dividends, votes, reports.
Legally the shares are ledger-based securities under the Swiss DLT Act (Art. 973d OR). That sounds like “build everything on the blockchain”. It isn’t.
The blockchain does exactly one job
The ledger is the register of who owns which shares. The law requires that, and that is all it does.
Everything else is a normal business application: project workflows with several roles, documents and signatures, orders, payments, notifications, reports. None of this belongs on a chain. It changes often, contains personal data and has to be fast and searchable. So it lives in a .NET backend with a relational database on Azure.
The rule I keep coming back to: the chain is the source of truth for ownership, the database is the source of truth for everything else. The backend keeps a read model of the token balances, so a portfolio page never waits for a node.
One backend, three apps
Users work in three apps: Flow for developing a project up to the contract, Market for buying and selling shares, Operations for running the plant. They feel like separate products, but they share one backend and one domain model.
That matters because the rules overlap. Whether a share can be sold depends on the project phase from Flow, the lock-up rules and the current orders in Market. If each app had its own backend, those rules would exist three times and drift apart.
Orders as aggregates with EventFlow
The domain is built with EventFlow, a .NET library for CQRS and event sourcing. Instead of saving the current state of an order, the backend saves what happened to it: the order was placed, the shares were reserved, the payment arrived, the shares were transferred. The current state is the sum of those events.
For a platform that moves ownership of securities, that is a good fit. Every change has a reason, a time and an author, and the full history of an order or a project is available without a separate audit log.
An EventFlow application has four building blocks:
- Commands express what a user wants, for example “confirm payment for order X”.
- Aggregates decide whether that is allowed and emit events. An order is an aggregate, and so is a project.
- Events are stored in the event store and never change.
- Read models are built from the events and serve the apps: order lists, portfolios, project overviews.
The order aggregate is also the state machine. Each method checks the current state and either emits an event or rejects the command:
public class OrderAggregate : AggregateRoot<OrderAggregate, OrderId>,
IEmit<OrderPaid>,
IEmit<SharesTransferred>
{
private OrderStatus _status = OrderStatus.Created;
private int _quantity;
public OrderAggregate(OrderId id) : base(id) { }
public IExecutionResult ConfirmPayment(DateTimeOffset paidAt)
{
if (_status != OrderStatus.AwaitingPayment)
return ExecutionResult.Failed($"Order is {_status}, payment can't be confirmed.");
Emit(new OrderPaid(paidAt));
return ExecutionResult.Success();
}
public IExecutionResult MarkTransferred(string transactionHash)
{
if (_status != OrderStatus.Paid)
return ExecutionResult.Failed($"Order is {_status}, shares can't be transferred.");
Emit(new SharesTransferred(_quantity, transactionHash));
return ExecutionResult.Success();
}
public void Apply(OrderPaid aggregateEvent) => _status = OrderStatus.Paid;
public void Apply(SharesTransferred aggregateEvent) => _status = OrderStatus.Transferred;
// PlaceOrder, ReserveShares, Cancel, Expire ...
}
The command handler stays thin, it loads the aggregate and calls the method:
public class ConfirmPaymentCommandHandler
: CommandHandler<OrderAggregate, OrderId, IExecutionResult, ConfirmPaymentCommand>
{
public override Task<IExecutionResult> ExecuteCommandAsync(
OrderAggregate aggregate, ConfirmPaymentCommand command, CancellationToken cancellationToken)
{
return Task.FromResult(aggregate.ConfirmPayment(command.PaidAt));
}
}
The rules live in one place, the aggregate. Whether a payment comes in through the bank import, an admin screen or a test, it goes through the same check. And because Apply only sets state and never decides anything, replaying old events always gives the same result.
Read models listen to the events. The portfolio of an investor, for example, is updated when SharesTransferred arrives:
// one row per investor and project, found through a read model locator
public class PortfolioReadModel : IReadModel,
IAmReadModelFor<OrderAggregate, OrderId, SharesTransferred>
{
public int Shares { get; private set; }
public Task ApplyAsync(
IReadModelContext context,
IDomainEvent<OrderAggregate, OrderId, SharesTransferred> domainEvent,
CancellationToken cancellationToken)
{
Shares += domainEvent.AggregateEvent.Quantity;
return Task.CompletedTask;
}
}
That is the read model mentioned above: the apps read portfolios and order lists from tables that are already in the right shape, and never have to query the chain or replay events on a page load.
The money stays off-chain
The obvious design for a token platform is delivery versus payment on-chain: the token and the money swap in one transaction. For Swiss francs that is not realistic today. Investors pay by bank transfer, and banks don’t settle in a smart contract.
So settlement works like this: the buyer pays into an escrow account, the payment is confirmed, and only then does the backend trigger the token transfer. If the payment doesn’t arrive within the deadline, the order expires and the reserved shares are released. Less elegant than DvP on a slide, but it works with real banks and real money.
Custody behind an interface
In the pilot, investors hold their own wallets. In production, a regulated custodian takes over and the wallets are managed like a bank account. That change must not ripple through the whole backend.
That is why everything that touches wallets goes through one interface. Orders, dividends and votes only know “transfer these shares from A to B”, not who signs the transaction. Switching from self-custody to a custodian means a new implementation, not a rewrite.
The outbox: no transfer gets lost
Once OrderPaid is stored, the shares have to move on the chain. Doing both directly in the command handler, first saving the event and then calling the chain, is the classic dual-write problem. If the process crashes in between, the payment is recorded but the shares never move. If the chain call comes first and the save fails, shares move for an order that is not marked as paid.
The backend solves this with the outbox pattern. The event and an outbox entry “transfer these shares” are written in the same database transaction, so either both exist or neither does. A background dispatcher then reads the pending entries, sends them and marks them as sent. If the node is unavailable, the entry stays pending and is sent again later.
A retry can happen after the chain has already executed the transfer, for example when the confirmation got lost in a timeout. That is why every outbox entry carries an idempotency key, and the transfer uses it: sending the same entry twice still moves the shares only once. When the transaction is confirmed, the dispatcher sends MarkTransferred to the aggregate, and the order is closed.
Preventing duplicate transactions
Moving shares twice is the worst bug this platform can have. A user double-clicks, a bank file is imported twice, a dispatcher retries after a timeout. Every one of these is normal, so the protection doesn’t rely on one place but on several layers:
| Layer | Risk | Protection |
|---|---|---|
| API | Double click, client retry | Every command carries a request ID. The same ID returns the first result instead of running again. |
| Payment import | Same bank file read twice | Payments are matched by their bank reference, which has a unique index. A second import finds the payment already booked. |
| Aggregate | Two commands at the same time | EventFlow stores events with the aggregate version. If two commands change the same order in parallel, the second commit fails and is retried against the new state, where ConfirmPayment is rejected because the order is already paid. |
| Outbox | Two dispatchers pick the same entry | Entries are claimed with a row lock, and there is only one outbox entry per order and transfer, enforced by a unique index on the idempotency key. |
| Chain | Retry after a lost confirmation | The transfer carries the idempotency key. Before sending again, the dispatcher checks whether a transaction with that key already exists. |
Claiming outbox entries on SQL Server looks like this. READPAST skips rows another dispatcher has locked, and the lease makes sure an entry is picked up again if a dispatcher crashes while sending:
UPDATE TOP (10) Outbox WITH (UPDLOCK, READPAST, ROWLOCK)
SET Status = 'Sending',
LeaseUntil = DATEADD(MINUTE, 5, SYSUTCDATETIME())
OUTPUT inserted.Id, inserted.IdempotencyKey, inserted.Payload
WHERE Status = 'Pending'
OR (Status = 'Sending' AND LeaseUntil < SYSUTCDATETIME());
None of these layers is enough alone. Together they make sure that a duplicate request ends up as “already done” instead of a second transfer.
Security
Shares in a tokenisation platform are securities, so the backend is built on the assumption that every input can be wrong or hostile.
- Authorisation on every command, not in the UI. The command handler checks the user’s role and project before the aggregate is even loaded. A hidden button is not a permission.
- Prices and quantities are calculated on the server. The client sends “buy 50 shares of project X”. The price, the fees and the availability come from the backend, never from the request.
- Payments are confirmed by the bank, not by the user. A payment counts only after the bank import or a signed webhook from the payment provider, checked against the expected amount and reference.
- Signing keys never live in the application. In the pilot they sit in Azure Key Vault and the backend reaches them with a managed identity. With a custodian, the keys stay with the custodian and the backend only sends signed transfer requests.
- Least privilege. Only the dispatcher’s identity may trigger transfers. The API that users talk to can write commands and outbox entries, but it can’t sign anything.
- The dispatcher checks again before sending. Even an entry from the outbox is validated against the current state: the order is paid, the shares are reserved, no lock-up period applies.
- The smart contract enforces its own rules. Only the platform role may move shares, and locked shares can’t be transferred, even if a bug in the backend tried to.
- Everything is traceable. Every change is an event with user, time and reason. Manual corrections are commands like any other and need a second person to approve them.
- Differences raise an alarm. The regular comparison between chain and read model sends an alert as soon as a balance doesn’t match.
The chain is slow and can fail
A database write takes milliseconds. A blockchain transaction takes seconds, sometimes longer, and a node can be unavailable. The backend treats every chain call as something that can fail or arrive late:
- A user action ends as soon as the transaction with event and outbox entry is committed. Nobody waits for the chain.
- A regular job compares the balances on the chain with the read model and reports differences instead of hiding them.
What I take away
Use blockchain for the part that really needs a shared, tamper-proof register, and build everything else like a well-made business application. Model processes as aggregates that emit events, put external systems behind interfaces, send every call to them through an outbox, and expect them to be slow or unavailable. Most of the effort in a tokenisation platform is not in the smart contract, but in everything around it.