← Back to Blog

Building the Fee & Pricing Engine

Pricing cards, bank wires, and EVM gas transfers cleanly inside our Fiat & Crypto Settlement Hub without turning the checkout path into an unmaintainable tangle.

CARD bps FLAT WIRE EVM GAS FEE ENGINE QUOTE

This is the first build post in the Fiat & Crypto Settlement Hub series. Before we move a single dollar or token between wallets, we have to answer the first question every tenant asks at checkout: how much will this transfer cost, and how much lands on the other side?

Our Settlement Hub serves multiple partner fintechs on shared infrastructure. One partner collects card top-ups in USD, another batches high-value treasury payouts over bank wires, and a third moves USDC across EVM chains. Every time a tenant previews or submits a transfer, the hub needs an exact fee quote before touching any wallet balance.

That quote is not just a display number. It feeds straight into the append-only ledger, where the platform fee, the external network cost, and the net settled amount must balance to the smallest unit of the currency.

Four Pricing Models, One Quote Engine

Four pricing models need to live side by side in Milestone 1:

  • Card rail: percentage fee expressed in basis points (bps, where 100 bps equals 1%) plus a fixed authorization fee, such as 290 bps + $0.30.
  • Bank wire rail: a flat $15.00 fee per wire, regardless of whether the tenant sends $200 or $25,000.
  • EVM RPC rail: a platform spread in basis points (say 35 bps) plus the estimated on-chain priority gas cost converted from Gwei into the settlement currency.
  • VIP tenant waiver: select enterprise tenants have their platform markup waived to $0.00, while any underlying external network gas cost still passes through transparently.

Notice the financial constraints hiding underneath those four bullets. First, we cannot use double or float anywhere. Binary floating-point math cannot represent 0.10 or 2.90% exactly, and silent penny drift breaks ledger reconciliation. Every calculation must use BigDecimal with integer basis points and explicit RoundingMode.HALF_EVEN (banker's rounding, which avoids systematic upward bias over millions of rows). Second, fiat USD settles at scale 2 while USDC settles at scale 6, so rounding precision belongs to the rail or currency rather than a global constant.

A hasty shortcut is tempting here: drop a big switch (transfer.rail()) inside TransferService with an if (tenant.isVip()) nested inside each branch. That works for ten minutes, right up until Product adds tiered volume discounts, ACH rails, or weekend FX markups. Suddenly a single method owns pricing constants, gas unit conversions, and tenant overrides all at once. Changing card pricing risks breaking EVM gas math, and unit testing one rule requires booting the entire transfer service.

Tilted black-and-white 1950s Polaroid photograph of a deadpan office accountant staring behind four mechanical adding machines and tangled receipt tape
Every new rail taped into one switch (rail) method.

Separating Inputs, Outputs, and Pricing Math

To keep the pricing math clean and isolated, picture the calculation as a small, pure function: given a transfer snapshot, return an immutable quote. Notice what happens if we separate the inputs, the output, and the pricing formula into distinct types.

First, let's define the immutable input snapshot (TransferPricingContext) and the structured breakdown (FeeQuote). Splitting platformFee from networkFee in FeeQuote matters because the ledger credits platform revenue to our own account while network gas goes to block validators.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

enum Rail {
    CARD,
    BANK_WIRE,
    EVM_RPC
}

record TransferPricingContext(
        String tenantId,
        Rail rail,
        String currency,
        BigDecimal amount,
        boolean vipTenant,
        long estimatedGasUnits,
        BigDecimal priorityFeeGwei,
        BigDecimal nativeTokenUsdRate
) {}

record FeeQuote(
        BigDecimal platformFee,
        BigDecimal networkFee,
        BigDecimal totalFee,
        BigDecimal netSettledAmount,
        String breakdown
) {}

Next, we introduce a single contract, FeeRule, representing any pricing formula. Every concrete rule takes the exact same input and returns the exact same output, so the rest of the hub never cares whether a fee came from basis points, a flat wire schedule, or a gas calculation.

@FunctionalInterface
interface FeeRule {
    FeeQuote calculate(TransferPricingContext ctx);
}

Notice how small and readable a shared helper makes our basis-point math. Instead of converting percentages to decimals by hand inside every class, one helper divides by 10000 with explicit scale and RoundingMode.HALF_EVEN. Each rail then gets its own focused class that holds only the numbers it actually needs.

static final BigDecimal BPS_DIVISOR = new BigDecimal("10000");
static final BigDecimal GWEI_IN_ETH = new BigDecimal("1000000000");

static BigDecimal applyBps(BigDecimal amount, int bps, int scale) {
    return amount
            .multiply(BigDecimal.valueOf(bps))
            .divide(BPS_DIVISOR, scale, RoundingMode.HALF_EVEN);
}

static class CardPercentageFeeRule implements FeeRule {
    private final int rateBps;
    private final BigDecimal fixedAuthFee;

    CardPercentageFeeRule(int rateBps, BigDecimal fixedAuthFee) {
        this.rateBps = rateBps;
        this.fixedAuthFee = fixedAuthFee;
    }

    @Override
    public FeeQuote calculate(TransferPricingContext ctx) {
        BigDecimal percentFee = applyBps(ctx.amount(), rateBps, 2);
        BigDecimal total = percentFee.add(fixedAuthFee).setScale(2, RoundingMode.HALF_EVEN);
        BigDecimal net = ctx.amount().subtract(total).setScale(2, RoundingMode.HALF_EVEN);
        return new FeeQuote(
                total,
                BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN),
                total,
                net,
                rateBps + " bps + $" + fixedAuthFee + " fixed auth"
        );
    }
}

static class FlatWireFeeRule implements FeeRule {
    private final BigDecimal flatFee;

    FlatWireFeeRule(BigDecimal flatFee) {
        this.flatFee = flatFee.setScale(2, RoundingMode.HALF_EVEN);
    }

    @Override
    public FeeQuote calculate(TransferPricingContext ctx) {
        BigDecimal net = ctx.amount().subtract(flatFee).setScale(2, RoundingMode.HALF_EVEN);
        return new FeeQuote(
                flatFee,
                BigDecimal.ZERO.setScale(2, RoundingMode.HALF_EVEN),
                flatFee,
                net,
                "Flat $" + flatFee + " wire fee"
        );
    }
}

Now look at the crypto rail and the VIP waiver. EvmGasSpreadFeeRule computes the platform spread in bps at scale 6 and converts estimatedGasUnits * priorityFeeGwei from Gwei into ETH (at scale 18 so intermediate precision is never truncated early) before multiplying by the native token rate. Meanwhile, VipWaiverFeeRule wraps any base FeeRule: it runs the underlying rule to preserve exact network gas costs, then zeroes out only the platform fee.

Black-and-white 2D ink cartoon showing a bouncer waving the $0.52 networkFee bucket past a velvet rope while stamping the $17.50 platformFee bucket to $0.00 for VIP tenants
Splitting platformFee from networkFee lets VipWaiverFeeRule zero out our cut while validators still get their gas.
static class EvmGasSpreadFeeRule implements FeeRule {
    private final int spreadBps;

    EvmGasSpreadFeeRule(int spreadBps) {
        this.spreadBps = spreadBps;
    }

    @Override
    public FeeQuote calculate(TransferPricingContext ctx) {
        BigDecimal spreadFee = applyBps(ctx.amount(), spreadBps, 6);
        BigDecimal gasEth = BigDecimal.valueOf(ctx.estimatedGasUnits())
                .multiply(ctx.priorityFeeGwei())
                .divide(GWEI_IN_ETH, 18, RoundingMode.HALF_EVEN);
        BigDecimal networkFeeUsd = gasEth
                .multiply(ctx.nativeTokenUsdRate())
                .setScale(6, RoundingMode.HALF_EVEN);
        BigDecimal total = spreadFee.add(networkFeeUsd).setScale(6, RoundingMode.HALF_EVEN);
        BigDecimal net = ctx.amount().subtract(total).setScale(6, RoundingMode.HALF_EVEN);
        return new FeeQuote(
                spreadFee,
                networkFeeUsd,
                total,
                net,
                spreadBps + " bps spread + EVM priority gas"
        );
    }
}

static class VipWaiverFeeRule implements FeeRule {
    private final FeeRule delegate;

    VipWaiverFeeRule(FeeRule delegate) {
        this.delegate = delegate;
    }

    @Override
    public FeeQuote calculate(TransferPricingContext ctx) {
        FeeQuote base = delegate.calculate(ctx);
        int scale = base.networkFee().scale();
        BigDecimal waivedPlatform = BigDecimal.ZERO.setScale(scale, RoundingMode.HALF_EVEN);
        BigDecimal total = base.networkFee();
        BigDecimal net = ctx.amount().subtract(total).setScale(scale, RoundingMode.HALF_EVEN);
        return new FeeQuote(
                waivedPlatform,
                base.networkFee(),
                total,
                net,
                "VIP waiver (platform fee $0, pass-through network fee)"
        );
    }
}

Finally, FeeEngine holds an immutable lookup map from Rail to FeeRule. Notice how little branching remains here: it picks the matching rule, optionally wraps it with VipWaiverFeeRule, and delegates.

static class FeeEngine {
    private final Map<Rail, FeeRule> railRules;

    FeeEngine(Map<Rail, FeeRule> railRules) {
        this.railRules = Map.copyOf(railRules);
    }

    public FeeQuote quote(TransferPricingContext ctx) {
        FeeRule baseRule = railRules.get(ctx.rail());
        if (baseRule == null) {
            throw new IllegalArgumentException("No pricing rule configured for rail: " + ctx.rail());
        }
        FeeRule activeRule = ctx.vipTenant() ? new VipWaiverFeeRule(baseRule) : baseRule;
        return activeRule.calculate(ctx);
    }
}

Let's wire all four scenarios in a runnable Main and inspect the exact numbers:

public static void main(String[] args) {
    FeeEngine engine = new FeeEngine(Map.of(
            Rail.CARD, new CardPercentageFeeRule(290, new BigDecimal("0.30")),
            Rail.BANK_WIRE, new FlatWireFeeRule(new BigDecimal("15.00")),
            Rail.EVM_RPC, new EvmGasSpreadFeeRule(35)
    ));

    var cardTx = new TransferPricingContext(
            "tenant-acme", Rail.CARD, "USD", new BigDecimal("1000.00"),
            false, 0, BigDecimal.ZERO, BigDecimal.ZERO
    );
    var wireTx = new TransferPricingContext(
            "tenant-acme", Rail.BANK_WIRE, "USD", new BigDecimal("25000.00"),
            false, 0, BigDecimal.ZERO, BigDecimal.ZERO
    );
    var evmTx = new TransferPricingContext(
            "tenant-nova", Rail.EVM_RPC, "USDC", new BigDecimal("5000.000000"),
            false, 65_000, new BigDecimal("2.5"), new BigDecimal("3200.00")
    );
    var vipEvmTx = new TransferPricingContext(
            "tenant-vip", Rail.EVM_RPC, "USDC", new BigDecimal("5000.000000"),
            true, 65_000, new BigDecimal("2.5"), new BigDecimal("3200.00")
    );

    printQuote("Card $1,000.00", engine.quote(cardTx));
    printQuote("Bank Wire $25,000.00", engine.quote(wireTx));
    printQuote("EVM USDC $5,000.00", engine.quote(evmTx));
    printQuote("VIP EVM USDC $5,000.00", engine.quote(vipEvmTx));
}

Running that with Java 21 produces:

Card $1,000.00 -> platform=29.30, network=0.00, total=29.30, net=970.70 (290 bps + $0.30 fixed auth)
Bank Wire $25,000.00 -> platform=15.00, network=0.00, total=15.00, net=24985.00 (Flat $15.00 wire fee)
EVM USDC $5,000.00 -> platform=17.500000, network=0.520000, total=18.020000, net=4981.980000 (35 bps spread + EVM priority gas)
VIP EVM USDC $5,000.00 -> platform=0.000000, network=0.520000, total=0.520000, net=4999.480000 (VIP waiver (platform fee $0, pass-through network fee))

Spot the Pattern

Take a quick pause before moving on and look at the shape of what we just wrote. Notice that FeeEngine holds no pricing math of its own. Instead, every pricing algorithm lives behind a single interchangeable interface (FeeRule), and the engine picks and runs whichever implementation fits the transfer at runtime.

In software design, that shape is the Strategy pattern (with VipWaiverFeeRule acting as a lightweight wrapper around any chosen strategy). Each fee formula is encapsulated in its own small type, making it easy to swap, test, and extend without editing existing formulas.

FeeEngine Context / Selector quote(ctx) <<interface>> FeeRule calculate(ctx) CardPercentageFeeRule bps + fixed auth FlatWireFeeRule flat wire fee EvmGasSpreadFeeRule spread bps + gas Gwei VipWaiverFeeRule zeroes platform fee
Strategy pattern: FeeEngine delegates pricing to interchangeable FeeRule implementations.

When NOT to Use It

If your platform has only two static pricing formulas that never vary per tenant, rail, or gas model, creating a separate class hierarchy adds boilerplate without payoff. A simple table-driven lookup (a Map<Rail, FeeSchedule> storing a record FeeSchedule(int bps, BigDecimal flatFee)) plus a single 10-line calculation method is cheaper to read and maintain until an algorithm genuinely diverges in structure, as EVM gas math did here.

Cost & Trade-offs

  • More types to navigate: One formula becomes an interface plus N classes, though Java lambdas or method references can shrink trivial rules down to one line.
  • Context bloat risk: Notice how TransferPricingContext carries both card-agnostic fields and EVM gas fields. If rules diverge even further, splitting rail-specific metadata into a sealed sub-record prevents unused fields from piling up.
  • Selection logic still lives somewhere: Strategy eliminates branching inside the math, not the lookup that picks the rule. Keeping that selection declarative (via a map or database-backed pricing tier) keeps FeeEngine tidy.

Real-World Appearances

  • Java JDK: java.util.Comparator<T> passed to List.sort(), and java.nio.file.CopyOption strategies.
  • Spring Framework: AuthenticationProvider in Spring Security and HandlerMapping in Spring MVC.
  • Fintech & Payments: Payment service provider routing (selecting Stripe vs. Adyen fee models), FX markup tiers, and blockchain gas-estimation policies across L1/L2 networks.