In general, any exchange has two main components: a messaging system and a trading engine. The messaging system collects trade intentions (orders) from the users and sends them to the trading engine that checks the orders and executes them. In the current DeFi ecosystem - mostly built on Ethereum - the messaging system generally uses protocols like 0x [2], while the trading engine is a smart contract. A DEX may fail in being censorship-resistant because of two distinct conditions:
In this regard, Mintlayer users and developers can choose between six different types of DEX interactions, depending on their needs in terms of decentralization, privacy, and censorship resistance: from a fully decentralized solution in both the trading engine and messaging system to milder solutions that introduce intermediaries in the communication to increase the spectrum of possible trades.
NOTE: This feature is currently under development and will be part of a future upgrade. Please note that technical details are subject to change
The first solution is based on the atomic swap smart contract playing the part of the trading engine. It does not rely on any particular communication system: users can exchange order intentions using any communication medium.
This solution is likely the best choice for OTC trades as transactions require both parties to already be in contact and agree on the pair exchange details (the precise amount of tokens and the relative price).
The difference between other OTC trades is that this procedure is entirely trustless. The communication is facilitated via the standardized order messages (described in §5.8) that can be used to create the atomic swap transaction in the wallet automatically. This way, the trade can easily occur without requiring escrow or technical support. At the same time, notarization becomes unnecessary if the goal is to ensure the counterpart’s compliance, given that the atomic swap is fully trustless.
The privacy is guaranteed because no one needs to know about the transaction except the two parties involved, whereas blockchain analysis cannot distinguish an atomic swap from any other transaction in the blockchain.
Another benefit of the atomic swap is that it fully supports cross-chain swaps between BTC and MLS-01 tokens. The Mintlayer full node integrates an add-on to Bitcoin Core with a UI designed to specifically perform atomic swaps between the Bitcoin chain and the Mintlayer chain. The Mintlayer mobile wallet (a light wallet for managing Bitcoin and Mintlayer) also includes this functionality.
Thanks to the link between Mintlayer blocks and Bitcoin blocks, the cross-chain atomic swap is secure even in case of reorg (chain reorganization): even if a reorganization happens on Bitcoin, the Mintlayer chain reorganizes too as part of the consensus mechanism.
Like the first solution, the second one uses the atomic swap as a trading engine and also introduces a peer-to-peer communication system that allows swaps between parties that are unknown entities to each other with no prior contact. It is possible to create multiple atomic swaps, splitting a single order into multiple sub-orders, increasing the possibility of finding a match in terms of the amount and price for the pair requested. The functioning of the messaging systems (the order structure) and the multi-swap are further described in §5.3., §5.8. The communication system can also work on a TOR network so that users can communicate directly without exposing each other's IP addresses, only their DIDs (see §4.4.).
The orders broadcasted are stored by the nodes in a decentralized manner using a distributed hash table (DHT) [1]. Every full node can activate the DHT-DEX functionality: nodes are free to sync the full DHT, prune it, start partial sync only when they are online (starting from the most recent orders), or not sync at all. Once activated, the node begins syncing the Distributed Hash Table of orders from the peers.
Not all orders that reach the peer are registered on the hash table; instead, each node stores only those orders that are filtered based on their interest and will pass on to the network only what is stored, just like it happens on BitTorrent or other similar peer-to-peer systems. A bigger DHT grants more opportunities to find a successful match, but on the other hand, it takes more time and resources to be synched and stored.
It means that all nodes will never share a single equal DHT, and likely there will not be nodes who know or store the entire book history since the complete set of orders is stored only collectively in many fragmented tables in possession of different node owners.
The filters applied in the syncing phase can be set over a chosen pair, a price range, and the amount requested in the transaction. Nodes can freely prune unwelcome orders from their DHT, also stopping relaying them to other nodes.
Orders can have a due date; some are dropped by the nodes who created them, while others are closed because the swap has already been successfully finalized. To notify peers of closed or canceled orders, it is necessary to prove those orders' ownership by signing the message with the private key connected to the original order creator's DID. Nodes also notify their peers by relaying messages about closed orders.
An anti-spam filter is necessary because an attacker could populate the DHT with fake orders. For this reason, each node can configure anti-spam filters, removing old orders or directly those nodes that spread a suspiciously high amount of orders which are never fulfilled, closed, or canceled. Suppose the anti-spam would prove to be insufficient to manage a vast amount of fake orders or require too many resources. In that case, a third party can intermediate the DHT synchronization (see §5.3.).
The user creating an order may use a price ratio suggested directly by the wallet node. The user chooses between two indicators: a) the price provided by a centralized exchange/service through API or b) the price retrieved from the DHT, which is calculated in a fully decentralized way.
A messaging system based on a distributed hash table (DHT) has a few drawbacks:
For these reasons, specialized nodes can intermediate the messaging system. Nodes can subscribe to the "observer" services, which act as a quality guarantee to their subscribers. The observer aims to store the entire DHT voluntarily, plus a few additional pieces of information provided by the nodes connected to them that report the effective status of the orders.
The observer checks the status and the frequency of the operations to create a rank, which is higher when the number of finalized operations is higher when both involved users confirm that the atomic swap was successfully achieved. The observer cross-checks the DHT order book with the subscribers' data, proving that the transactions are effectively executed. It also performs a blockchain analysis to determine each user's reliability.
The observer ranks the user and their associated orders, communicating information to each subscriber about the estimated reliability of a particular order/node, reporting spam, and notifying closed or inactive orders. It may also relay orders to the subscriber that are already filtered along with the subscriber's interests and sorted according to the observer's priority set. Wallets can use the observers as "oracles" and accept or reject connections with other peers based on the reported reputation. This way, the users syncing the DHT may leave aside useless information or decide not to initiate a particular atomic swap transaction if the counterpart is not "verified" by the observer.
The observer could require a payment fee for its services. However, hypothetically it could also operate for free if it represents an entity benefiting from developing a reliable DEX, like a service that provides complimentary services connected to the DEX. Moreover, given that the observer privately gathers data from the users, it also disposes of more resources for elaborating DEX statistics, which may have an economic value or grant reputational value, allowing monetization of advertising.
The observer also collects information, such as price and timestamp, about orders that led to successful atomic swaps. Keeping track of this information may serve when calculating each pair's price ratio on the DEX, not only estimated values by the book, but actual prices of the last exchange performed on-chain.
For a node to rely on the observer services, it does not require much trust: even if the observer is shut down or does not provide any useful information, the communication between peers is not interrupted, nor the observer has any influence on the atomic swaps that are going to be performed. The only trade-off is the loss of privacy since the observer can distinguish the on-chain transactions as atomic swaps in the DEX, thus associating them to a particular owner and tracking down each ownership transfer.
A second solution to avoid the drawbacks of a DHT constructed in a peer-to-peer way is to trust special node relayers that act as book aggregators and store the DHT on behalf of the users. It is beneficial for light node/mobile wallet users as they do not have the time and resources to sync many megabytes of orders or sort and filter them.
The relayer stores and broadcasts the orders on behalf of the users and also collects all the information from the subscribed users (like any observer node). When users intend to exchange tokens, the Mintlayer wallet uses bloom filters to ask a book aggregator for a specific pair's order. Then, the node relayer provides an answer – a list of all the orders in the network that may be of interest (in terms of price and amount) and already filtered or ordered according to a rank. It also combines matches between simultaneous online users, directly suggesting how to initiate the atomic swap transactions and what parties can be involved in it.
The Mintlayer app enables a specific configuration of push notifications to let the book aggregators notify users of a contact received. This way, users avoid the "always-on-display" screen and can unlock the phone only at the moment of initiating the atomic swap.
When a user finalizes the order for the entire amount, it sends a closure notification to the book aggregator so that no more matches are proposed. It is useful as the relayer by itself never knows if the exchange transaction has been effectively carried out between parties after establishing contact through the relayer.
Such "book aggregator" relayers can be paid off using three specific fields in the order package (see peer-to-peer messaging system §5.8):
Since book aggregators centralize the communication system in a single entity, no exchange can happen if the aggregator is shut down until nodes find an alternative book aggregator. Another drawback of this solution is that the aggregators can track down all the users' operations, limiting their privacy. However, aggregators also might be highly efficient in finding matches and achieving a prolific market of exchange transactions.
The essential difference between a book aggregator and a centralized exchange is that:
There is no correct choice between a DHT, an observer, or a book aggregator; the best solution depends on the degree of trust the user is willing to give to third parties.
To participate in a programmable pool DEX, the traders need to "consolidate" one or more UTXOs in an account-based address. The programmable pool DEX offers less privacy but more efficiency than the atomic swap because of two features:
The order packages are relayed between all the users belonging to the pool, while the trades are executed through the pool's script-based smart contract rather than the atomic swap. For this reason, the programmable pool can work only with MLS-01 tokens and not bitcoins (BTC), which need to be wrapped in an MLS-01 form before being traded in the pool.
The pool may also provide a particular transaction script, allowing the construction of an order book on-chain: nodes directly lock in the tokens in a smart contract paired with a corresponding order package. When another trader sees an order of interest, the smart contract can be unlocked simply by executing the on-chain transaction required by that order package.
For example:
Trader A locks in 10.000 m-USDT in an address with the following script: the sender of a transaction who transfers 1 m-BTC to that address will be able to withdraw the 10.000 m-USDT to a different address (the balance of Trader B). In this case, trader A is the "maker" who sets the exchange price (10.000m-USDT/1m-BTC), and trader B is the taker, getting 10.000 m-USDT to his address in exchange for 1 m-BTC.
The maker's order automatically expires after n blocks after the on-chain transaction is executed. Until that order expires, no other participant in the pool accepts the locked 10.000 m-USDT for other transactions. If the order expires, nodes can freely prune the maker's on-chain transaction as if it was never broadcasted to the network, and the tokens are still considered to be in the account balance of trader A.
This functionality has the great benefit of enabling out-of-sync exchanges because two traders do not have to be simultaneously online and connected. On the other hand, if too many maker transactions are made without resulting in a successful trade (matching with a taker), it may produce on-chain pollution (higher resources committed to syncing the chain even if those orders will expire someday and therefore, in the long run, do not pollute the blockchain but require more space on disk).
More importantly, an on-chain transaction pays a fee to the blockmaker. Therefore, it is more costly and risks ending up with no successful trades. The free market economy will determine what is the more convenient solution between an off-chain DHT book with programmable pool swaps where traders connect and an on-chain book with out-of-sync makers and traders.
Order packages can be integrated into the functionality of the Mintlayer wallet to trigger Lightning Network transactions. When a user wants to execute the trade, the wallet recognizes the Lightning Network swap's specific request, thanks to the parameter lightningSwap (§5.8.). It also automatically produces the payment invoices and HTLC transactions according to that order request (exchange rate, amount of tokens, and expiring time).
The swap can be executed only if the two parties have already established a channel between them in both exchange pairs.
The benefits of Lightning Network DEX transactions are speed, privacy, near-zero fees, and no on-chain pollution. The limitation is the establishment of two different channels (for both the tokens exchanged). Even with enough liquidity, it is unlikely unless the parties involved already know each other and have agreed on those channels' specific purposes. However, this solution can be used by exchanges and services for directly trading BTC against MLS-01 tokens.
When Lightning Network usage becomes more widespread, the relevance of such a solution will likely rise, allowing for additional features to be implemented. One example would be order packages with a field for submarine swaps to enable the direct purchase of BTC or MLS-01 tokens that already exist on a Lightning Network channel.
As described in the previous paragraphs, Mintlayer's DEX mostly uses technologies that assume the parties involved are already in contact when transferring money between each other (i.e., the atomic swap described in §3.2.4.). However, while building a real marketplace, users must also be able to get in touch without knowing each other in advance. Therefore, a communication system is needed to allow them to choose between different orders in the market waiting to be fulfilled.
Carrying out this process requires a centralized book. Moreover, an atomic swap transaction is necessarily bilateral, meaning that both involved users must be online and agree on the number of tokens that shall be exchanged. It could cause issues since it is unlikely to find an exact match between the maker and taker at a precise moment.
The "request" of exchange preceding the atomic swap is a message that would need to be relayed all over the network before reaching a match. It would take time and resources and also expose the node relayers to spam attacks, while orders might never be fulfilled in the first place. It would result in an extremely inefficient and illiquid network. Mintlayer solves this puzzle by merging ideas and technologies already developed on other blockchains.
If the maker and the taker do not know each other in advance, they need to find the counterpart and communicate to perform an atomic swap. The communication is structured according to a protocol inspired by Ethereum 0x, allowing users to lean on node relayers to speed up the reconciliation process between demand and supply.
Each message is a data packet that contains order parameters concatenated and hashed to 32 bytes using the Keccak SHA3 function. The maker signs the order with the private key associated with his digital identity (DID, see §4.4.).
Once packaged, the order can be sent to the recipient using whatever medium of communication, even a direct message (i.e., using Messenger, Telegram, etc.), if the recipient already knows the maker.
A hypothetical message is structured as follows, although the final implementation may differ:
name | datatype | description |
---|---|---|
identity | uint256 | Contact (DID) of the maker |
tokenA | uint256 | ID of the token A offered by the maker |
valueA | uint256 | total units of token A offered by the maker |
tokenB | uint256 | ID of the token B requested by the maker |
valueB | uint256 | total units of token B requested by the maker |
expiration | uint256 | time at which the order expires |
priceRange | uint256 | % of deviation from the price (value A/value B ratio) accepted by the maker (optional) |
multipartySwap | uint256 |
If equal to token A, it enables only an exact match (no multiparty swap) If different from token A, it indicates the minimum amount of token accepted for a multiparty swap (it shall be less or equal to token A/2) |
feeRecipient | address | address of a relayer (optional) |
feeToken | uint256 | ID of the token used to pay the relayer (optional) |
fee | uint256 | fee paid to the relayer (optional) |
lightningSwap | uint256 | Indicates if the order has to be executed on Lightning Network (optional) |
addressPool | uint256 | Address of the maker referring to the token A account in the pool that will be used for the trade (optional, mandatory for programmable pool DEX trades) |
The data contained in the order does not reveal any confidential information that directly relates to the maker except for the maker's id, which is necessary for the taker(s) to get in touch and perform the transaction. There is an expiration time at which the offer is no longer considered valid, and the wallet will reject any match proposed by other nodes. Two additional parameters are introduced to increase the chances of having a match between maker and taker, both freely configurable by the user:
The wallet automatically prepares the message when the user selects the pair and digits, the amount of the token, desired exchange price, and the expiration date. The parameter price range is optional, set to 0,02% by default, as well as the parameter multipartySwap, set to one-fifth of the amount by default.
The nodes store the messages sent in the network in a distributed hash table. Suppose any user in the network is interested in receiving an order message (i.e., directly from the maker, relayed from a peer, or a node relayer). In that case, they will connect and initiate the atomic swap (only if both users are online). The wallet looks for possible matches until it finds the first user online, then initiates the atomic swap. In the presence of multiple available offers, the wallet will choose the ones closer to the amount requested and a more favorable price to reduce the number of atomic swap transactions required and maximize the profit.
In this type of transaction, labeling "maker" and "taker" is imprecise since all users are, or can be, either makers or takers. The order is carried out only when there is a match between two "maker" offers expressed in the same pair (but in the opposite direction) and are consistent in terms of amount and price range.
In case of low liquidity of a specific asset, users might be unsure about the possibility of finalizing a big order for its entire amount, so it shall be split into many different atomic swaps. Here comes the "traffic light" function into play, which allows for three different configurations:
[1] Lesniewski-Laas, C. A Sybil-proof one-hop DHT. Available here
[2] Warren, W., Bandaeli, A. 0x: An open protocol for decentralized exchange on the Ethereum blockchain. Available here