Constructing Multi-Rail Transfer Instructions
Assembling immutable transfer payloads across fiat and blockchain rails in our Fiat & Crypto Settlement Hub without 15-parameter constructors or half-valid objects.
In Milestone 2, we decoupled post-settlement side effects from the ledger. Before any transfer reaches the ledger or pricing engine, though, callers have to construct a TransferInstruction that tells the Settlement Hub what to move and where.
At first glance, a transfer looks simple: a tenant, a wallet, an amount, a currency, and a rail. Then real payment rails arrive. A bank wire wants an optional destinationMemo, an idempotencyKey, a complianceRef, and a callbackUrl. A scheduled treasury sweep sets scheduledAt. An EVM token transfer needs a chain, gasLimit, priorityFeeGwei, and sometimes an fxQuoteId or negotiated feeOverride.
Pretty soon our TransferInstruction has 5 core fields and 10 optional fields. Every endpoint and background job populates a different subset of those optional fields.
What a Transfer Instruction Must Guarantee
We need to construct a TransferInstruction that obeys four strict rules:
- Required fields cannot be forgotten:
tenantId,sourceWalletId,amount,currency, andrailmust always be supplied upfront. - Optional fields stay readable: calling code sets only the 2 or 3 optional properties relevant to its rail (
idempotencyKey,fxQuoteId,chain,gasLimit,priorityFeeGwei,destinationMemo,callbackUrl,scheduledAt,feeOverride,complianceRef). - Cross-field invariants are enforced once: an
EVM_RPCinstruction without achainmakes no sense, and aBANK_WIREcarrying agasLimitorpriorityFeeGweiis a caller bug that should fail immediately before touching a rail or ledger. - Immutability after creation: once constructed, no downstream service may mutate the instruction in flight.
Look at why the usual shortcuts break down. A telescoping 15-argument constructor like new TransferInstruction(t, w, amt, cur, rail, key, null, null, null, null, memo, url, null, null, ref) is unreadable and makes swapping two adjacent String or BigDecimal fields a silent financial bug. On the flip side, a no-arg constructor with JavaBean setters (setAmount(), setGasLimit()) leaves the object mutable and lets half-configured instructions wander around the codebase until they crash deep inside a gateway adapter.
Even if an incoming REST controller deserializes a flat JSON payload with all fifteen fields nullable, our core settlement domain should never pass raw, unverified DTOs downstream. We want one crisp boundary where an instruction becomes valid, complete, and frozen in memory.
Separating Staging From the Final Record
What if we separate the mutable staging area from the immutable finished instruction? Imagine filling out a form on a clipboard: you write the 5 required fields at the top, jot down only the optional lines that apply to your rail, and then hand the clipboard to a single checkpoint that validates the whole form before stamping an immutable TransferInstruction.
Draft, validate cross-rail rules once, and stamp out a frozen TransferInstruction.Let's lock down TransferInstruction first. Making it a final class with a private constructor ensures nothing outside can bypass the validation checkpoint, and exposing only read accessors keeps every field immutable once created.
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Objects;
enum Rail {
CARD,
BANK_WIRE,
EVM_RPC
}
public static final class TransferInstruction {
private final String tenantId;
private final String sourceWalletId;
private final BigDecimal amount;
private final String currency;
private final Rail rail;
private final String idempotencyKey;
private final String fxQuoteId;
private final String chain;
private final Long gasLimit;
private final BigDecimal priorityFeeGwei;
private final String destinationMemo;
private final String callbackUrl;
private final Instant scheduledAt;
private final BigDecimal feeOverride;
private final String complianceRef;
private TransferInstruction(Draft draft) {
this.tenantId = draft.tenantId;
this.sourceWalletId = draft.sourceWalletId;
this.amount = draft.amount;
this.currency = draft.currency;
this.rail = draft.rail;
this.idempotencyKey = draft.idempotencyKey;
this.fxQuoteId = draft.fxQuoteId;
this.chain = draft.chain;
this.gasLimit = draft.gasLimit;
this.priorityFeeGwei = draft.priorityFeeGwei;
this.destinationMemo = draft.destinationMemo;
this.callbackUrl = draft.callbackUrl;
this.scheduledAt = draft.scheduledAt;
this.feeOverride = draft.feeOverride;
this.complianceRef = draft.complianceRef;
}
public static Draft draft(
String tenantId,
String sourceWalletId,
BigDecimal amount,
String currency,
Rail rail
) {
return new Draft(tenantId, sourceWalletId, amount, currency, rail);
}
public String tenantId() { return tenantId; }
public String sourceWalletId() { return sourceWalletId; }
public BigDecimal amount() { return amount; }
public String currency() { return currency; }
public Rail rail() { return rail; }
public String idempotencyKey() { return idempotencyKey; }
public String fxQuoteId() { return fxQuoteId; }
public String chain() { return chain; }
public Long gasLimit() { return gasLimit; }
public BigDecimal priorityFeeGwei() { return priorityFeeGwei; }
public String destinationMemo() { return destinationMemo; }
public String callbackUrl() { return callbackUrl; }
public Instant scheduledAt() { return scheduledAt; }
public BigDecimal feeOverride() { return feeOverride; }
public String complianceRef() { return complianceRef; }
Notice the static factory method TransferInstruction.draft(...). It accepts the 5 mandatory fields in its constructor, so the compiler itself prevents anyone from omitting tenantId, sourceWalletId, amount, currency, or rail.
Now let's write the nested Draft class. Each of the 10 optional fields gets a fluent method returning this, so calling code reads like a clean sentence specifying only what that transfer actually uses. At the end of the chain, build() acts as our single validation gate: checking positive amounts, HTTPS callback URLs, non-negative fee overrides, and the cross-field rules between EVM_RPC and fiat rails. Because all checks run together inside build(), no service deeper in the hub ever has to wonder whether a BANK_WIRE instruction accidentally carried an EVM gasLimit.
public static final class Draft {
private final String tenantId;
private final String sourceWalletId;
private final BigDecimal amount;
private final String currency;
private final Rail rail;
private String idempotencyKey;
private String fxQuoteId;
private String chain;
private Long gasLimit;
private BigDecimal priorityFeeGwei;
private String destinationMemo;
private String callbackUrl;
private Instant scheduledAt;
private BigDecimal feeOverride;
private String complianceRef;
private Draft(
String tenantId,
String sourceWalletId,
BigDecimal amount,
String currency,
Rail rail
) {
this.tenantId = requireText(tenantId, "tenantId");
this.sourceWalletId = requireText(sourceWalletId, "sourceWalletId");
this.amount = Objects.requireNonNull(amount, "amount is required");
this.currency = requireText(currency, "currency");
this.rail = Objects.requireNonNull(rail, "rail is required");
}
public Draft idempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; return this; }
public Draft fxQuoteId(String fxQuoteId) { this.fxQuoteId = fxQuoteId; return this; }
public Draft chain(String chain) { this.chain = chain; return this; }
public Draft gasLimit(long gasLimit) { this.gasLimit = gasLimit; return this; }
public Draft priorityFeeGwei(BigDecimal priorityFeeGwei) { this.priorityFeeGwei = priorityFeeGwei; return this; }
public Draft destinationMemo(String destinationMemo) { this.destinationMemo = destinationMemo; return this; }
public Draft callbackUrl(String callbackUrl) { this.callbackUrl = callbackUrl; return this; }
public Draft scheduledAt(Instant scheduledAt) { this.scheduledAt = scheduledAt; return this; }
public Draft feeOverride(BigDecimal feeOverride) { this.feeOverride = feeOverride; return this; }
public Draft complianceRef(String complianceRef) { this.complianceRef = complianceRef; return this; }
public TransferInstruction build() {
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalStateException("amount must be greater than zero");
}
if (feeOverride != null && feeOverride.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalStateException("feeOverride cannot be negative");
}
if (callbackUrl != null && !callbackUrl.startsWith("https://")) {
throw new IllegalStateException("callbackUrl must use https://");
}
if (rail == Rail.EVM_RPC) {
if (chain == null || chain.isBlank()) {
throw new IllegalStateException("chain is required for EVM_RPC transfers");
}
if (gasLimit != null && gasLimit <= 0) {
throw new IllegalStateException("gasLimit must be positive");
}
if (priorityFeeGwei != null && priorityFeeGwei.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalStateException("priorityFeeGwei cannot be negative");
}
} else {
if (chain != null || gasLimit != null || priorityFeeGwei != null) {
throw new IllegalStateException("EVM gas/chain fields are invalid on " + rail);
}
}
return new TransferInstruction(this);
}
private static String requireText(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " is required");
}
return value;
}
}
}
Notice how clean calling code becomes in Main. A wire transfer mentions only wire fields, an EVM transfer mentions only EVM fields, and mixing rail fields fails loudly inside build():
public static void main(String[] args) {
TransferInstruction wire = TransferInstruction
.draft("tenant-acme", "wal-usd-01", new BigDecimal("12500.00"), "USD", Rail.BANK_WIRE)
.idempotencyKey("idem-991a")
.destinationMemo("Invoice #4082")
.complianceRef("AML-2026-88")
.callbackUrl("https://api.acme.example/webhooks/settle")
.build();
TransferInstruction evm = TransferInstruction
.draft("tenant-nova", "wal-usdc-04", new BigDecimal("2500.000000"), "USDC", Rail.EVM_RPC)
.idempotencyKey("idem-992b")
.chain("base-mainnet")
.gasLimit(65_000L)
.priorityFeeGwei(new BigDecimal("1.8"))
.fxQuoteId("fx-usd-usdc-11")
.build();
System.out.println("Valid Wire: " + wire);
System.out.println("Valid EVM: " + evm);
try {
TransferInstruction
.draft("tenant-acme", "wal-usd-01", new BigDecimal("500.00"), "USD", Rail.BANK_WIRE)
.gasLimit(21_000L)
.build();
} catch (IllegalStateException ex) {
System.out.println("Rejected invalid instruction: " + ex.getMessage());
}
}
Observed output from Java 21:
Valid Wire: TransferInstruction[tenant=tenant-acme, wallet=wal-usd-01, amount=12500.00 USD, rail=BANK_WIRE, chain=null, gasLimit=null, idempotencyKey=idem-991a] Valid EVM: TransferInstruction[tenant=tenant-nova, wallet=wal-usdc-04, amount=2500.000000 USDC, rail=EVM_RPC, chain=base-mainnet, gasLimit=65000, idempotencyKey=idem-992b] Rejected invalid instruction: EVM gas/chain fields are invalid on BANK_WIRE
Spot the Pattern
Pause for a second and examine why this felt so much cleaner than either a giant constructor or mutable setters. We split construction into two phases: a fluent, mutable staging object (Draft) that enforces mandatory arguments at entry, followed by a single validating step (build()) that produces a locked-down, immutable domain object.
In design patterns terminology, this is the Builder pattern (specifically Joshua Bloch's Effective Java variant, where the staging class is usually named Builder and entered via .builder(...)).
When NOT to Use It
If an object has 3 or 4 fields and all of them are required, a plain Java record with a compact constructor is strictly better. Writing a nested staging class for record Money(BigDecimal amount, String currency) adds 40 lines of noise where a one-line constructor is crystal clear. Similarly, if your rail fields never overlap and you want compile-time separation rather than runtime checks inside build(), consider distinct record WireInstruction(...) and record EvmInstruction(...) types behind a sealed interface.
Cost & Trade-offs
- Field duplication: Every optional field is declared twice (once on
TransferInstruction, once on the builder), plus a fluent setter method. - Validation timing: Putting required arguments in
draft(...)gives compile-time safety for core fields, while cross-field rules (such as rejectinggasLimitonBANK_WIRE) are checked at runtime insidebuild(). - Worth it when fields grow: Once an instruction crosses roughly 5 optional parameters or carries conditional rail constraints, the caller clarity far outweighs the extra class body.
Real-World Appearances
- Java JDK:
java.net.http.HttpRequest.newBuilder(),StringBuilder, andLocale.Builder. - Libraries & Frameworks: Lombok
@Builder, Jackson / OkHttpRequest.Builder, and Spring'sUriComponentsBuilder/ResponseEntity. - Fintech & Payments: Stripe's
PaymentIntentCreateParams.builder(), Adyen SDK request objects, and Web3j / ethers transaction request assembly.