Crypto order exchange
Implementing a cryptocurrency order exchange system with the Blnk Ledger.
Overview
This guide demonstrates how to implement a secure and efficient cryptocurrency order exchange system with the Blnk Ledger. You’ll learn how to handle order creation, escrow management, order matching, and atomic settlements.
A cryptocurrency exchange operates in three main steps:
- Order Creation: Users express their intent to trade by creating orders
- Order Matching: Compatible orders are paired together
- Settlement: Assets are exchanged atomically between parties
To illustrate this flow, let’s work with a practical example where two users want to exchange different cryptocurrencies:
Designing your map
Before writing code, it’s crucial to design a money movement map that outlines how money moves in your system. This serves as the blueprint for your implementation.
For our order exchange system, here’s how funds will flow:
Step 1: Order creation
Each customer initiates their order by starting a transaction in an inflight state, temporarily holding their assets (e.g., ETH or MATIC) in escrow (@ETH_Escrow
or @MATIC_Escrow
) until the order is matched or finalized:
- John deposits ETH into
@ETH_Escrow
(inflight). - Emily deposits MATIC into
@MATIC_Escrow
(inflight).
Step 2: Order matching
Order matching occurs when the system pairs John’s inflight ETH transaction in @ETH_Escrow
with Customer B’s inflight MATIC transaction in @MATIC_Escrow
, linking them under a shared . This step confirms compatibility and prepares the orders for settlement, keeping funds securely held in escrow until the final exchange.
- John’s ETH in
@ETH_Escrow
matches Emily’s MATIC order (and linked by a root id:root_id_123
). - Emily’s MATIC in
@MATIC_Escrow
matches John’s ETH order (and linked by a root id:root_id_123
).
Step 3: Order settlement
- Inflight MATIC transaction to
@MATIC_Escrow
commits and settles to John’s MATIC balance. The settlement transactions are linked to matched orders with theroot_id
. - Inflight ETH transaction to
@ETH_Escrow
commits and settles to Emily’s ETH balance. The settlement transactions are linked to matched orders with theroot_id
.
Prerequisites
Before starting, ensure you have:
- A running Blnk server instance (e.g. at
http://localhost:5001
). - An API key for Blnk (replace
YOUR_API_KEY
in the code examples). Required for authenticated requests. - The Blnk CLI installed or a connected Blnk Cloud workspace to view your ledger data.
Setting up your ledger
Before implementing the exchange logic, we need to establish the foundational structure in your Blnk Ledger. Let’s set up separate ledgers for each cryptocurrency and create the necessary balances:
Create customer ledgers
Create two ledgers to segregate different cryptocurrencies:
Create customer balances
Create balances for both users in each ledger:
Fund the initial balances
In this example, we use a precision of 100 for simplicity (e.g., 1 ETH = 100 units). In production, cryptocurrencies like ETH use a precision of 10^18 (1 ETH = 10^18 wei). Adjust the precision
parameter in all transaction calls accordingly and ensure amount calculations reflect this precision.
Phase 1: Order Creation
When John or Emily creates an order, we need to:
-
Confirm that they have sufficient funds to successfully place the order.
-
Initialize it via inflight on your Ledger and reserve the funds in escrow until the order is matched or canceled.
-
Record in our order book.
-
Bringing it all together.
Add inflight_expiry_date
to automatically roll back the inflight transaction if an order isn’t matched within a timeout period.
Phase 2: Order Matching
When two orders are matched (e.g., John and Emily), we want to link them together with a common matching ID. This helps us track which orders in our Ledger were matched with each other.
Phase 3: Settling the Matched Orders
Finally, we need to execute the exchange of assets between the matched orders — John & Emily. Here’s how we do it:
- We need to commit these transactions to move the funds to escrow.
- Then we create new transactions to move funds from escrow to the respective recipient balances (John’s MATIC balance and Emily’s ETH balance).
Best Practices
-
Balance Validation: Always verify available balances before creating orders. Remember to consider both actual balances and inflight amounts to prevent over-commitment of funds.
-
Transaction References: Always use meaningful reference prefixes (‘order_’, ‘match_’, ‘settlement_’) combined with UUIDs. This makes it easier to track and audit transactions throughout their lifecycle.
-
Metadata Management: Ensure metadata consistency across all related transactions. The matching ID should flow through all transactions involved in an exchange, creating a clear chain of linked operations.
-
Error Handling: Implement comprehensive error handling at each step. If any part of the process fails, you need to be able to identify where the failure occurred and handle it appropriately.
Additional Considerations
-
Rate Limiting: Consider implementing rate limits for order creation to prevent system overload and potential abuse. See advanced configuration.
-
Currency Precision: Different cryptocurrencies might require different precision settings. Ensure to use consistent precision value per currency in your Ledger.
-
Escrow Management: Regularly audit escrow accounts to ensure they zero out correctly after settlements. Any remaining balance could indicate failed or incomplete settlements.
Can’t find your use case?
If you’re searching for a specific tutorial that isn’t included here, you’re welcome to contribute to our documentation by sharing your expertise or requesting a new tutorial in our Discord community.
We’re always thrilled to expand our resources with the help of our developer community!