Connecting a custodian bank: interface design for share transfers
In the pilot, investors hold their own wallets. In production, a bank does. How the Finexswiss backend talks to a custodian, using a fictional Bank XYZ as the example: workflow, interface, webhooks and failure cases.
From self-custody to a bank
In the Finexswiss pilot, investors control their own wallets. That is fine for a test with a handful of people who know what a private key is. It is not fine for a pension fund, a municipality or a retired neighbour who wants five shares in the solar plant on the school roof.
So after the pilot a regulated custodian takes over. Investors get an account at the bank, the bank holds the keys and signs the transactions, and the shares sit in that account like securities in a normal custody account. For the investor it feels like banking. For the backend it changes who signs, but it must not change how orders, dividends or votes work.
In this article the custodian is a fictional Bank XYZ. Real custodians have their own APIs and processes, but the shape of the integration is the same.
Who does what
The first design step is not code, it is drawing the line between the platform and the bank:
| Finexswiss | Bank XYZ |
|---|---|
| Projects, phases, contracts | Customer onboarding and KYC |
| Orders, reservations, prices | Custody accounts for investors |
| Who may buy, sell or vote | Keys and signing of transactions |
| Dividend calculation | Execution of transfers on the chain |
| Read model of all holdings | Official custody statements |
The platform decides what should happen. The bank decides whether it is allowed from its regulatory point of view and executes it. Neither side does the other’s job, and neither side trusts the other blindly.
The workflow for one transfer
- The outbox dispatcher sends a transfer instruction to Bank XYZ, with the outbox entry’s ID as idempotency key.
- The bank answers right away with “accepted” and its own reference. Nothing has been transferred yet.
- The bank runs its checks (are both accounts active, is the investor allowed to hold this security) and signs with its own key.
- The bank submits the transaction to the chain.
- The chain confirms it.
- The bank calls the platform’s webhook with the status “settled”. The message is signed.
- The backend verifies the signature and sends
MarkTransferredto the order aggregate.
Two things stand out. The call in step 1 doesn’t return the result, only a promise to work on it. And the real answer arrives later, on a different channel, possibly after minutes.
The interface
The rest of the backend never sees Bank XYZ. It sees an interface that describes custody in the platform’s own terms:
public interface ICustodyGateway
{
Task<CustodyAccount> OpenAccountAsync(InvestorId investorId, CancellationToken ct);
Task<TransferReceipt> SubmitTransferAsync(TransferInstruction instruction, CancellationToken ct);
Task<TransferStatus> GetTransferStatusAsync(TransferId transferId, CancellationToken ct);
Task<IReadOnlyList<Holding>> GetHoldingsAsync(CustodyAccountId accountId, CancellationToken ct);
}
public sealed record TransferInstruction(
TransferId TransferId,
CustodyAccountId From,
CustodyAccountId To,
ShareClassId ShareClass,
int Quantity);
public sealed record TransferReceipt(
TransferId TransferId,
string ExternalReference,
TransferStatus Status);
public enum TransferStatus { Submitted, Accepted, Rejected, Settled, Failed }
A few decisions behind it:
SubmitTransferAsyncreturns a receipt, not a result. The method name and the return type say it: this is an instruction. Code that calls it can’t accidentally assume the shares have moved.TransferIdis the idempotency key. It comes from the outbox entry, so a retry sends the same ID and the bank recognises it.- Statuses are the platform’s statuses. Bank XYZ might call it
EXECUTED, another bankBOOKED. The gateway translates, the domain only knowsSettled. GetTransferStatusAsyncexists for when the webhook doesn’t come. Webhooks get lost. A job asks for the status of transfers that have beenAcceptedfor too long.GetHoldingsAsyncis for reconciliation. Every night the platform compares its read model with the bank’s holdings.
The Bank XYZ implementation
The implementation is an anti-corruption layer: it speaks the bank’s language on one side and the platform’s language on the other. Bank DTOs never leave this class.
public sealed class BankXyzCustodyGateway(HttpClient http) : ICustodyGateway
{
public async Task<TransferReceipt> SubmitTransferAsync(
TransferInstruction instruction, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "v1/transfers")
{
Content = JsonContent.Create(BankXyzTransferRequest.From(instruction))
};
request.Headers.Add("Idempotency-Key", instruction.TransferId.Value);
using var response = await http.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<BankXyzTransferResponse>(cancellationToken)
?? throw new InvalidOperationException("Bank XYZ returned an empty transfer response.");
return new TransferReceipt(instruction.TransferId, body.Reference, MapStatus(body.State));
}
private static TransferStatus MapStatus(string state) => state switch
{
"RECEIVED" => TransferStatus.Submitted,
"ACCEPTED" => TransferStatus.Accepted,
"REJECTED" => TransferStatus.Rejected,
"EXECUTED" => TransferStatus.Settled,
"FAILED" => TransferStatus.Failed,
_ => throw new InvalidOperationException($"Unknown Bank XYZ transfer state '{state}'.")
};
// OpenAccountAsync, GetTransferStatusAsync, GetHoldingsAsync ...
}
An unknown status throws instead of being mapped to something that sounds close. If the bank adds a status, we want to find out from a log entry, not from a wrong balance.
The HttpClient gets its base address, mutual TLS certificate and timeouts from configuration. The certificate comes from Azure Key Vault, like every other secret.
The webhook
The way back is a small endpoint. It accepts nothing it can’t verify:
app.MapPost("/webhooks/bank-xyz", async (
HttpRequest request,
BankXyzWebhookVerifier verifier,
ITransferLookup transfers,
ICommandBus commandBus,
CancellationToken cancellationToken) =>
{
var notification = await verifier.ReadVerifiedAsync(request, cancellationToken);
if (notification is null)
return Results.Unauthorized();
if (notification.State != "EXECUTED")
return Results.Ok();
var orderId = await transfers.FindOrderAsync(notification.TransferId, cancellationToken);
await commandBus.PublishAsync(new MarkTransferredCommand(orderId, notification.Reference), cancellationToken);
return Results.Ok();
});
ReadVerifiedAsync checks the signature against the bank’s public key and rejects messages that are older than a few minutes, so a recorded webhook can’t be replayed. Because MarkTransferred is a command on the aggregate, a duplicate webhook is harmless: the order is already transferred and the second command is rejected.
When things go wrong
| Situation | What happens |
|---|---|
| Bank API not reachable | The outbox entry stays pending and is sent again later with the same idempotency key. |
| Bank rejects the transfer | The webhook or the status query returns Rejected. The order is cancelled, the reserved shares are released and the buyer gets a message with the reason. |
| Webhook never arrives | A job queries the status of transfers that have been Accepted for too long. |
| Webhook arrives twice | The second MarkTransferred is rejected by the aggregate. |
| Holdings don’t match at night | Alert to the operations team. Nothing is corrected automatically, a person looks at it. |
One interface, three implementations
| Implementation | Used for |
|---|---|
SelfCustodyGateway |
The pilot: signs with keys from Azure Key Vault |
BankXyzCustodyGateway |
Production with the custodian |
FakeCustodyGateway |
Tests: settles immediately or fails on purpose |
Which one is used is a configuration setting per environment. The same set of contract tests runs against the fake and against the bank’s sandbox. If both pass, switching from the pilot to the bank is a deployment, not a project.
What I take away
Design the interface around what the platform needs, not around the first bank’s API. Make the asynchronous nature visible in the types, so nobody mistakes “sent” for “done”. Translate everything at the border, verify everything that comes back, and plan for the messages that never arrive. Then the custodian becomes a replaceable part instead of something the whole backend depends on.