Skip to main content

Orderbook Marketplace

The Orderbook Marketplace (OrderbookMarketplace) is the core continuous trading engine of the DEUSS ecosystem, designed to succeed the platform's initial dashboard-based offer and counter-offer negotiation system. While the initial Marketplace served as an interim solution for listing static sell offers and negotiating bilateral trades, the Orderbook Marketplace introduces a fully automated on-chain orderbook model with deterministic price-time priority matching directly on the EBSI enterprise ledger.

As the platform evolves, the Orderbook Marketplace takes over all secondary market trading and liquidity provision. The initial marketplace infrastructure remains active exclusively for its specialized Interest Discovery capabilities, which serve as a threshold-gated book-building engine for primary bond issuances and crowdfunding campaigns.


Strategic Evolution & Market Architecture​

In tokenized debt capital markets, SME bonds require efficient continuous price discovery and liquid secondary trading alongside structured mechanisms for primary capital formation. DEUSS organizes this through a clear separation between primary crowdfunding campaigns and secondary continuous trading:

  1. Primary Issuance & Crowdfunding Campaigns (Marketplace.sol - Interest Discovery): Retained specifically for crowdfunding campaigns and primary syndicated book-building, where investors express binding interest commitments toward an aggregate funding threshold before issuance deals are activated.
  2. Continuous Secondary Trading Engine (OrderbookMarketplace.sol): The permanent trading engine that supersedes manual dashboard offer negotiation, delivering continuous price discovery, price range spread execution, automated matching, transparent on-chain depth, and multi-market basket execution.

Core Business Capabilities​

1. Price-Time Priority Matching​

The marketplace organizes buy and sell interest into discrete orderbooks keyed by asset pair (tokenAddress, tokenId). Orders are strictly ordered by commercial attractiveness and timestamp:

  • Buy Orders: Sorted descending by maximum willingness to pay (maxPrice). Highest bids match first; identical prices match FIFO (First-In, First-Out).
  • Sell Orders: Sorted ascending by lowest acceptable ask (minPrice). Lowest asks match first; identical prices match FIFO.
  • Taker-Favorable Price Improvement: When incoming orders cross resting book orders, execution occurs at the most favorable price for the taker within the overlapping spread:
    • Buy Taker: Executes at max(sellMinPrice, buyMinPrice) (lowest available price in the overlap).
    • Sell Taker: Executes at min(buyMaxPrice, sellMaxPrice) (highest available price in the overlap).

2. Price Range & Spread Bidding​

Rather than restricting participants to single fixed prices, traders can submit price range orders [minPrice, maxPrice]:

  • Fixed Orders: Configured with minPrice = maxPrice.
  • Range Orders: Define an acceptable execution band. A match occurs whenever the buy range and sell range overlap (buyMaxPrice >= sellMinPrice and sellMaxPrice >= buyMinPrice).
  • Benefits: Enables market makers to provide liquidity over a wider spread, allows institutional buyers to express flexible yield targets, and protects resting orders against unnecessary slippage during partial fills.

3. Metadata-Driven Basket & Batch Orders (placeBatchOrder)​

Institutional asset managers frequently manage bond portfolios by allocation criteria (e.g., duration, yield, ESG score, rating) rather than individual ISINs.

Through the placeBatchOrder facility and the pluggable BondMarketFilter architecture:

  • A buyer defines an aggregate token-unit target (totalAmount), price bounds, and a bond metadata filter payload.
  • The contract evaluates active sell markets on-chain against criteria such as maturity range, currency allowlist/denylist (EUR, USD, etc.), coupon rate range, coupon type (Fixed, Floating, Zero-Coupon), issuer address, and nominal bond value.
  • Surviving candidate markets are dynamically sorted by lowest top-of-book ask and matched greedily until the requested amount is fulfilled.
  • Any unfilled amount is immediately discarded (Immediate-or-Cancel / IOC semantics), ensuring execution against the cheapest available bonds meeting the investor's mandate without leaving a resting order.

4. Regulated Institutional Counterparty Controls​

To satisfy strict compliance, MiFID II, and AML/KYC obligations without sacrificing trading efficiency:

  • Identity & Authorization: When EntityRegistry is configured, the caller and any represented trader wallet must be registered and ENABLED in the EntityRegistry.
  • Trading Delegation: Asset managers or custodians can trade on behalf of client accounts via granular delegation (setDelegate / onBehalfOf).
  • Bilateral Counterparty Filters: Orders can configure a TraderFilterMode:
    • NONE: Open public matching.
    • WHITELIST: Match only against approved partner/institutional counterparties (up to 50 addresses).
    • BLACKLIST: Exclude specific competitor or restricted wallets.
    • Both sides' filters must mutually permit the counterparty for a trade to execute.
  • Minimum Match Amount (minMatchAmount): Prevents order book dusting and odd-lot fragmentation by enforcing minimum executable block sizes.

5. On-Chain TWAP Oracle (Time-Weighted Average Price)​

The contract maintains an independent, gas-efficient 256-slot circular observation buffer for every active asset pair (tokenAddress, tokenId):

  • Each executed match records an instantaneous cumulative price observation: Pcum = PcumPrev + Plast * deltaTime.
  • Provides time-weighted average price queries (getTWAP(token, tokenId, secondsAgo)) over the observations retained in the ring buffer. Requests older than the retained history use the oldest available observation as the starting point.
  • The TWAP is an informational executed-trade oracle for off-chain consumers such as net asset value (NAV) calculations, portfolio mark-to-market accounting, and surveillance by the IDA Agent. Executed trades can influence it; the current contracts do not consume it for matching, settlement, collateral, or other value-sensitive decisions.

6. DvP Fiat Settlement & Dispute Window​

DEUSS bonds settle off-chain in fiat (EUR/CHF/USD) via regulated Payment Service Providers (PSPs) while maintaining on-chain cryptographic delivery:

  • Pre-Funded Token Custody: Sell orders lock bond tokens in EscrowManager upon placement.
  • Trade Execution: Matching instantly reserves the token amount into deal status (inDeals), establishing an immutable claim.
  • Off-Chain Payment Confirmation: The Core Payment Service coordinates bank transfers and triggers markTradePaid(tradeId).
  • Settlement Finalization: Anyone or automated worker services can execute settleTrade(tradeId), releasing tokens to the buyer's wallet.
  • Grace Periods & Disputes: Unpaid trades past their paymentDeadline can be marked unpaid (markTradeUnpaid). A configurable dispute window (disputeBufferPeriod, deployed with a 24-hour default) allows buyers to raise an on-chain dispute (initiateDispute) for human arbitration (resolveDispute), ensuring buyer protection against bank transmission delays while guaranteeing sellers can safely reclaim unsold liquidity.

7. Regulatory Compliance: Freezing & Asset Seizure​

To comply with judicial orders, anti-money laundering (AML) investigations, and international sanctions:

  • Granular Freezing: Addresses with FREEZE_ROLE can freeze specific resting orders (setOrderFrozen) or in-flight trades (setTradeFrozen) with a non-zero compliance reason hash (bytes32 reason) recorded in the emitted event. Frozen orders are excluded from matching and hidden from public orderbook views.
  • Asset Seizure & Redirection: Under strict governance (SEIZURE_ROLE, assigned to the protocol's TimelockController), frozen escrowed assets can be seized (seizeOrder, seizeTrade) and transferred directly to a court-appointed custodian or legal beneficiary, preventing stranded assets while preserving complete cryptographic auditability.

Technical Design & Architecture​

The OrderbookMarketplace contract interacts with core DEUSS protocol contracts to ensure separation of concerns, gas safety, and upgradeability:

Data Storage Architecture​

  1. Namespaced State & Sorted Order Arrays: Mutable state is held in ERC-7201 namespaced storage. Each (tokenAddress, tokenId) pair maintains dynamic sorted arrays of orderIds for BUY and SELL books. Insertion shifts storage-array elements to preserve price-time priority; externally returned books are best-price first.
  2. Active Market Registry: An internal array plus a one-based index mapping tracks markets with active sell liquidity, bounded to MAX_ACTIVE_SELL_MARKETS = 100 to cap batch sweeps.
  3. Escrow Linkage: Each SELL order stores the separate EscrowManager identifier allocated for its custody position. Integrations can resolve it with getEscrowIdByOrderId; it must not be assumed to equal the order ID.
  4. Synthetic Batch Records: Batch execution uses a non-book BUY record (tokenAddress = 0, tokenId = 0) to link its resulting trades. A zero-match record is deleted immediately; a matched record remains only while linked trades are unresolved and is deleted after the final trade reaches a terminal state.

Stress Testing & Performance Analysis​

To validate the orderbook's throughput, resilience, and operational limits under institutional workloads, DEUSS executed comprehensive benchmark runs on a remote EBSI-equivalent devnet (Besu 25.11, Chain ID 1993) and compared them against dedicated local test harness baselines.

1. Benchmark Setup​

  • Workload: 16 independent bond instruments, 256 simulated institutional accounts, active matching, resting limit orders, cancellations, and DvP settlements.
  • Depth Cap: Client-side depth throttled to 200 orders per book side.
  • Reference Duration: 30-minute sustained continuous execution.

2. Key Empirical Findings​

MetricTarget / RequirementMeasured Devnet PerformanceLocal Node (Fast Sealing)Operational Status
Sustained Throughput186.6 tx/s8.0 tx/s (~0.69M ops/day)~70.0 tx/s (~9×)Governed by block cadence
Peak Throughput1,866 tx/s~15–20 tx/s~85+ tx/sRPC gateway bottleneck
Trade Execution Integrity100%100% Correct100% CorrectZero escrow leaks, zero false fills
Settled Trades44,160 / day~5,900 / day~52,000 / dayFully operational
Mean Block Gas Used144M gas/s target5.7M gas/s (observed peak 297.6M)N/AEVM compute was 16× idle

3. Bottleneck Analysis & Technical Decisions​

  1. Block Production is the Primary Devnet Bottleneck:
    • On the remote devnet, blocks were sealed on-demand at an average interval of approximately 3.15 seconds (21.5 tx/block / 3.15 s, or approximately 6.8–8.0 tx/s).
    • The EVM was largely idle: single blocks successfully processed up to 297.6M gas (approximately 94M gas/s capability), proving that EVM compute capacity is not the constraint.
    • Running the exact same contract codebase on a local node with sub-second block production achieved approximately 70 tx/s without any contract modifications.
  2. Orderbook Depth & Gas Scaling:
    • Because the orderbook maintains sorted arrays on-chain, transaction gas scales linearly with the depth of the price book:
      • Simple resting order (shallow book): approximately 0.54M gas.
      • Matching order (crossing 1–3 levels): approximately 1.32M–2.57M gas.
      • Deep book insertion (approximately 250 depth): approximately 2.14M gas.
      • Pathological uncapped removal (approximately 600+ depth): up to 12.95M gas.
    • Formula: Execution cost scales at approximately 0.40M gas + 0.0071M gas per scanned price level.
  3. Latency Profiles:
    • End-to-end confirmation latency on the devnet averaged approximately 3.2–7.0 seconds, strictly bound by block sealing times.
    • For high-frequency trading (HFT) requirements below 1 ms, on-chain execution is intentionally complemented by off-chain quote aggregation and broker-level pre-routing, using the on-chain orderbook for deterministic, binding settlement.

System Evolution: Transition to the Orderbook Trading Engine​

The table below outlines the transition from the initial dashboard-style marketplace to the comprehensive Orderbook Marketplace:

Feature / DimensionInitial Marketplace (Marketplace.sol)Orderbook Marketplace (OrderbookMarketplace.sol)
Ecosystem RoleInterim dashboard negotiation (to be phased out); retained permanently for Interest Discovery & CrowdfundingPermanent Core Trading Engine for all secondary bond market liquidity
Primary Use CasesCrowdfunding campaign book-building (INTEREST_DISCOVERY), issuer redemptionsContinuous secondary trading, market making, institutional portfolio rebalancing
Matching MechanismManual offer browsing, direct acceptance, and bilateral counter-offer negotiationFully automated on-chain orderbook matching (Price-Time FIFO)
Pricing ModelStatic unit price with sequential counter-offer proposalsFlexible limit orders and continuous price range spread orders
Multi-Asset AllocationSingle-offer acceptance per transactionMetadata-driven batch orders (placeBatchOrder via BondMarketFilter)
Price Discovery & OracleNone (discrete trade history)On-chain 256-observation cumulative TWAP oracle
Asset CustodyPer-offer escrow via EscrowManagerGlobal order-linked escrow via EscrowManager
Settlement CoordinationCore Payment Service (DvP fiat confirmation via PSP)Core Payment Service (DvP fiat confirmation via PSP) with dispute window
Dispute ResolutionHandled through off-chain payment status updates & admin holdsDedicated on-chain dispute window (disputeBuffer) & ARBITRATOR resolution
Compliance ControlsOffer/deal freezing and timelocked escrow seizureGranular order/trade freezing and timelocked escrow seizure

Strategic Roadmap & Scalability Optimizations​

Based on stress test telemetry and institutional feedback, the following roadmap items are established for the orderbook infrastructure:

  1. On-Chain Depth Bounding (MAX_BOOK_DEPTH): Enforce an on-chain parameter limiting active resting orders per price tier, preventing pathological array traversal gas costs during extreme volatility.
  2. Dedicated Fast-Sealing Consensus Nodes: Configure EBSI / Besu enterprise validator nodes with fixed 1.0-second block sealing intervals, raising baseline on-chain throughput from 8 tx/s to at least 70 tx/s.
  3. High-Availability RPC Gateway Tier: Implement connection-pooled, load-balanced RPC proxy infrastructure to eliminate client timeout thresholds observed past 20 tx/s.
  4. Hybrid Off-Chain Matching / On-Chain Settlement: For institutional tiers demanding sub-second execution, introduce signed EIP-712 off-chain intent matching with batch on-chain DvP cryptographic settlement.