Owners of digital assets use crypto exchanges to trade their cryptocurrencies, and interest in all varieties of cryptocurrency continue to rise. Crypto exchanges should perform transactions in a trusted and secure way. However, in 2019 alone, there were 12 major cryptocurrency exchange hacks: over $292 million and over 500,000 pieces of customer data were stolen.
There are two major types of crypto exchanges, and each tries to address these challenges in various ways. A centralized cryptocurrency exchange (CCE) acts as an intermediary and takes care of transactions for a commission. But in the event of malicious intent, a CCE can leave its users without any digital assets. Even a trusted centralized exchange has a single point of failure, making it vulnerable by design.
On the contrary, a decentralized cryptocurrency exchange (DEX) allows users to be in charge of their transactions. However, there might be issues with directly exchanging crypto due to a lack of trust between users. Some DEXs use trusted third-party escrow services. However, this approach may lead to scalability and privacy problems.
Another advanced way to resolve the issues mentioned above is by implementing the atomic swap protocol. It aims to help users securely perform exchanges even if they don’t trust each other. Also, with an atomic swap, parties fully control their cryptocurrency at each step of the exchange, eliminating the risk of hacking that exists when an exchange acts as an intermediary.
In this article, we briefly overview centralized and decentralized crypto exchanges and explore a few ways that atomic swaps can enhance the decentralized exchange model. We also introduce our own demo version of a DEX powered by atomic swaps and provide its source code.
Cryptocurrency exchanges are similar to traditional fiat exchanges but with a focus on cryptocurrency tokens. Users of crypto exchanges buy and sell cryptocurrency assets based on current market prices. Some crypto exchanges also allow users to trade fiat for cryptocurrency and vice versa.
You can find three types of cryptocurrency exchanges:
- Centralized cryptocurrency exchanges
- Decentralized cryptocurrency exchanges
- Hybrid cryptocurrency exchanges
With this information in mind, let’s move to a detailed description of how a CCE and DEX work. Note that in this article, we won’t bring up hybrid cryptocurrency exchanges because they’re a combination of the previous two types and can be implemented in various ways.
Centralized crypto exchanges
Centralized crypto exchanges are online platforms used to buy and sell cryptocurrencies and are fully controlled and maintained by a central authority. The most famous CCEs are Binance, Bittrex, and Coinbase.
Unlike decentralized exchanges, CCEs can be used to conduct trades from fiat to cryptocurrency and vice versa.
These exchanges are centralized in the sense that a company owns the exchange and serves as an intermediary between exchange participants. This means that CCE users have to trust the exchange with keeping their funds safe. In case an exchange is hacked by malicious actors or compromised by its owners, users will lose their money and tokens stored there.
Let’s explore how CCEs work with a simple example. Say Alice would like to exchange 1 BTC for 200 ETH using a centralized crypto exchange.
In this case, Alice sends her 1 BTC to the exchange address and the CCE records that 1 BTC among all BTC on its service address belongs to Alice. The same happens with Bob and his 200 ETH.
Afterwards, Alice and Bob exchange their assets following conventional exchange trading logic. What really happens is that the exchange records that Bob now owns 1 BTC and Alice owns 200 ETH. However, from the perspective of the Bitcoin and Ethereum networks, all those funds have just been sent to the exchange’s accounts.
When Alice would like to withdraw her 200 ETH from the exchange, she’ll be sent 200 ETH from the exchange account. To do so, she first has to initiate a funds withdrawal by typing in her external Ethereum address and confirming its correctness. Then the exchange will send her 200 ETH to the specified address, charging its own commission.
In this approach, the trading platform is a bookkeeper and source of truth. Users trust the platform to handle transactions correctly since it holds control over users’ funds most of the time.
On the other hand, users have no control over their own funds. Exchanges are performed on the CCE and users only actually own their funds after they withdraw them.
Let’s define the advantages and disadvantages of this centralized approach:
Centralized crypto exchanges
|Users aren’t responsible for safely storing their private keys.||Users have no control over their own funds.|
|Since all funds remain on the exchange’s service accounts, exchanges are typically fast because no cryptocurrency transaction actually occurs.||The platform can be shut down or taken over, since there’s a single point of failure.|
|Users may exchange fiat currencies for cryptocurrencies.||Privacy may be low due to regulations and enforcement of know your client guidelines.|
|Some CCEs offer additional features and bonuses like trading on credit and discounts for high-volume trading.||CCEs are vulnerable to hacking.|
Now let’s explore what decentralized exchanges are and learn the difference between a CCE and DEX.
Decentralized crypto exchanges
Unlike a centralized exchange, a decentralized exchange doesn’t belong to a certain company or organization that fully controls it. Any exchange user may deploy a smart contract, and DEX owners have no influence over it. Basically, a DEX is a source of information about existing orders and exchange possibilities. It works as a matchmaker rather than a trading platform. Examples of decentralized exchanges are AirSwap and IDEX.
The DEX approach is usually implemented in the following way:
Let’s assume again that Alice wants to exchange 1 BTC for 200 ETH, only this time with the help of a DEX.
Using the exchange functionality, Alice creates an order. Bob sees the terms of this order and can respond to it. After that, Alice and Bob can exchange their crypto directly rather than using the exchange as an intermediary.
Note that in this approach, at no point in time are Bob’s and Alice’s funds controlled by the exchange. Users perform all cryptocurrency transactions themselves since the DEX has no power to do so. A decentralized exchange doesn’t own private keys to access users’ funds in the first place.
Pros and cons of the DEX approach:
Decentralized crypto exchanges
|Users don’t delegate the power to control their funds to a third-party service.||Users’ funds won’t be refunded in case something goes wrong — for example, if a user stores a secret insecurely and someone steals it.|
|A DEX can’t be shut down or banned by regulators.||Doesn’t accept payments in fiat.|
|Great level of privacy and no risk of identity theft.||Offers lower trade volumes compared to a CCE.|
However, there might be issues with directly exchanging crypto because of a lack of trust between users. To encourage parties to exchange crypto and eliminate the risk of fraud, exchanges use various methods.
Some implement escrow, involving a trusted third party as a guarantor. This escrow agent controls the entire exchange process and makes sure the commitments from all parties are fulfilled. Although this approach to securing crypto exchanges seems legit, there are still chances that a third party may have malicious intentions. Not to mention commissions for escrow services. On the bright side, the Ethereum network suggests using smart contracts as escrow, which can help solve the problems mentioned above.
Another possible solution to overcome the lack of trust is to use atomic swaps. We’ll take a closer look at how atomic swaps can power the peer-to-peer and trustless exchange part of the DEX mechanism in the next section.
An atomic swap, also known as cross-chain trading, is a protocol that allows for exchanging cryptocurrencies across different ledgers using cryptography. The “atomic” part tells us that the exchange either executes fully or doesn’t happen at all. This means there’s no possibility that one party receives funds while the other doesn’t.
A core technique used in atomic swaps is called the Hash Time Locked Contract, or HTLC. This technology requires a hashlock key to only distribute traded crypto to users when all parties have signed off on their respective transactions and a timelock key to safely return traded crypto to users if the exchange isn’t completed within the specified time period. When different currencies are simultaneously submitted in these contracts, HTLCs eliminate the danger of an “accidental collision” by making sure the amount to be exchanged is ensured and can’t be outbid.
Atomic swaps can be used to build decentralized exchanges that allow you to work with several account systems, each with its own blockchains. A DEX using atomic swaps requires a solid protocol that allows for creating an order book in a decentralized way so that anyone can place an offer to sell or purchase crypto.
The main idea behind the atomic swap protocol is to help users securely perform an exchange even if they don’t trust each other. Therefore, this protocol has several requirements:
- Counterparties should use smart contracts with hashlocks and have the opportunity to set various time delays.
- To perform a transaction between two different systems, parties should use the same cryptographic hash function so the contract executes correctly.
- Users must have a safe communication channel to discuss the exchange conditions off-chain.
Major benefits of atomic swaps are:
- True decentralization so crypto owners can trade digital assets without third-party arbitration.
- The opportunity to be either directly executed between separate blockchains with different native coins or executed via off-chain channels that are offshoots of the main blockchain.
- Lower trading fees, as atomic swaps are only associated with standard blockchain transaction fees and charges for third-party services are eliminated.
- An opportunity for users to fully control their cryptocurrency at each step, eliminating the risk of hacking that exists with centralized exchanges.
Let’s break down a simple version of this protocol in detail and call it Protocol #0. Then we’ll identify its shortcomings and try to eliminate them. Instead of BTC, we’ll use ONT, because the Ontology network supports smart contracts, while the Bitcoin network operates with scripts.
Let’s assume that Alice has some ONT and Bob has some ETH. They want to exchange their crypto, but they don’t trust each other enough to simply send coins to each other.
- Alice generates some sort of secret that only she knows. Let’s say it’s a secret number.
- Alice creates a hash of this secret number. You can’t tell what the secret number is by looking at the hash, but you can quickly and easily confirm that the secret corresponds to the hash.
- Alice puts her coins in an Ontology smart contract with the condition that whoever knows the secret corresponding to the provided hash can withdraw coins from the contract. This type of smart contract is called a hashlock.
- Bob locks his ETH in an Ethereum contract with the same condition using the same hash Alice did. Bob could have received the hash from Alice through the exchange UI or externally if they agreed upon an atomic swap without using an exchange as an intermediary.
- Alice now sends her secret number to the Ethereum smart contract. The smart contract checks that the provided number corresponds to the hash provided by Bob. If the secret number is correct, Alice receives her ETH.
- The secret number is now published and visible to everybody. Bob can look up this number and send it to the Ontology smart contract. The Ontology smart contract will check that the secret is correct and let Bob claim his ONT.
Looks good, doesn’t it? We managed to exchange crypto between Alice and Bob by securing the transaction with some cryptography and smart contracts that are native to the Ethereum and Ontology networks.
However, this example has some significant flaws and can only work in a perfect world. If either Alice or Bob have malicious intentions or there’s a so-called man in the middle, the protocol will fail to provide an honest and fault-tolerant exchange process.
Let’s take a closer look at how this system could be abused:
- Alice doesn’t provide a secret. In this scenario, step 6 of our Protocol #0 never happens. It may not even be intentional — Alice might forget or lose her secret. In this case, Alice will lose access to her ONT and Bob will lose access to his ETH.
- Alice claims both ETH and ONT. This could easily happen since after step 5, Alice is the only person who knows the secret number. She could claim ETH and ONT simultaneously before Bob notices.
- Alice or a middleman could claim ONT instead of Bob. Since right now there’s no information about who has the right to claim the coins, anybody with the secret can do so. Therefore, Alice could take advantage of the situation by creating a new address and using a secret number to claim ONT instead of Bob. Then she could claim ETH as well. Even if Alice behaves honestly, there’s always the possibility of a middleman who knows the secret number after Alice claims ETH and uses it before Bob does.
The first two issues can be fixed by introducing timelocks to our protocol alongside hashlocks.
A timelock is a type of smart contract that locks coins for a certain amount of time. Let’s say there’s a smart contract and someone has sent some number of coins to it. This contract also contains information about a certain address (any address at all) that can claim those coins for itself, but only after a certain time passes.
In this example, we use timelocks to introduce refund logic, providing Alice and Bob with 24 hours to exchange their coins. If they don’t, they’re free to request their coins back to their own addresses.
Now let’s see what our new protocol looks like and what happens if certain steps aren’t performed.
Once again, Alice has some ONT and Bob has some ETH and both of them want to exchange their coins.
1. Alice generates a secret number.
2. Alice creates a hash of the secret number.
3. Alice puts her coins in an Ontology smart contract with the condition that whoever knows the secret corresponding to the provided hash can claim the ONT. In case nobody claims it, she’ll receive her ONT back in 48 hours.
4. Bob locks his ETH in an Ethereum contract with the same hashlock as Alice and with a 24-hour timelock. If nobody claims his ETH, he’s free to take it back in 24 hours.
If Bob never responds to the order, Alice and her locked ONT will be perfectly safe. She can claim it back in 48 hours.
5. Alice now sends her secret number to Bob’s Ethereum smart contract. Alice has claimed her coins.
If Alice never reveals the secret number, things will also be fine. Bob will be able to refund his ETH in 24 hours, and Alice will regain access to her ONT in 48 hours.
The important thing here is that Alice has only 24 hours to safely claim her ETH. Afterwards, the ETH will become accessible to Bob. If 24 hours have already passed, it’s in Alice’s interest not to claim the ETH and wait until she can refund her ONT. Otherwise, Bob will have an opportunity to claim Alice’s coins as well as his.
6. Bob claims his ONT using the published secret.
As you may notice, the timelocks in the Ethereum and Ontology smart contracts have different durations. This is done intentionally to protect Bob from fraud.
What if those timelocks had the same duration? This would mean that Alice had 24 hours to claim ETH, and once those 24 hours had passed, she could ask for a refund of her ONT. She could potentially wait almost 24 hours, successfully claim her coins, and then immediately ask for her ONT back before Bob used his secret to claim the coins.
By making the refund timelock longer for Alice, we ensure that even in the worst case scenario Bob will have at least 24 more hours to claim the ONT using the revealed secret before Alice asks for a refund.
As we can see, protocol #1 is much more resistant to cases when either Alice or Bob doesn’t follow the rules. If Alice deviates from the protocol, nothing bad happens to Bob, and vice versa. There’s no way that a misbehaving user can dishonestly benefit.
But there’s still one vulnerability that we can’t solve using only timelocks. Here’s the last weak spot remaining in our protocol:
- Alice or a middleman could claim ONT instead of Bob.
So how can we deal with this issue? It’s pretty straightforward: let’s add functionality for saving Alice’s and Bob’s addresses in Protocol #2.
Once again, Alice has some ONT and Bob has some ETH and they want to exchange their coins.
1. Alice generates a secret number.
2. Alice creates a hash of the secret number.
3. Alice puts her coins in an Ontology smart contract with the condition that she can claim them back at any time. The hash of the secret is also saved in the contract, but nobody can claim coins using her secret yet. Unlike in Protocol #1, this time users need to know both the secret and the address of the counterparty. At this step, the counterparty’s address is still unknown. The exchange can be performed only after Bob specifies Alice as the counterparty, and vice versa.
If Alice changes her mind or finds nobody to exchange with, she can simply claim back her ONT.
4. Bob puts his coins in an Ethereum smart contract with the condition that he can claim them back at any time. The secret’s hash taken from Alice is also saved in the contract, but nobody can claim coins using the secret yet.
Much like Alice, Bob can change his mind at this point and claim his ETH back.
5. Alice sends Bob’s Ontology address to an Ontology contract and it’s saved there. Only Bob can claim this ONT now, and he must know the secret number to do so. Now the refund timelock for Alice is set to 48 hours.
If Bob doesn’t respond, Alice can wait 48 hours and claim back her ONT.
6. Bob validates that his Ontology address in the Ontology contract is correct.
If the address isn’t correct, Bob should request a refund, as he won’t be able to claim ONT using the secret anyways.
7. Bob sends Alice’s Ethereum address to the Ethereum contract and it’s saved there. Now only Alice can claim ETH from that contract. A 24-hour refund timelock is set for Bob. Yet again, Alice should claim her funds in those 24 hours, as it won’t be safe to do so afterwards as Bob can already ask for a refund after that time.
8. Alice validates that her Ethereum address in the Ethereum contract is correct.
If the address isn’t correct, Alice should request a refund.
9. Alice reveals her secret in order to claim ETH. She should perform a claim transaction from the address written by Bob into the contract during step 8. Otherwise, the transaction won’t succeed.
10. Bob claims his ONT using the published secret. He should perform his transaction from the address Alice has recorded in the Ontology contract during step 6 or the transaction will fail.
Protocol #2 solves some significant issues of the previous protocols. However, it isn't perfect either. With this protocol, it’s up to the participants to follow the recommendations and keep themselves safe.
Here are the three main drawbacks of Protocol #2:
1. Alice and Bob need to keep up with timelocks:
- Alice should reveal the secret number within 24 hours.
- Bob should lock Alice’s address within 24 hours of Alice’s locking his address. Why 24 hours? If Bob waits longer, these 24 hours will be taken away from him, and the timelocks for Alice and Bob will become of the same duration.
In either of these cases, it’s unsafe to continue the swap, so the participants should request refunds.
2. Validation must be performed at almost every step, so Alice and Bob have to be extra attentive:
- Alice and Bob should check the number of coins locked.
- Alice and Bob should each check the address their exchange partner has recorded into the contract before continuing to the next step.
It’s up to Alice and Bob to check everything and keep themselves safe, so the UI of the decentralized exchange has to provide tools for conveniently validating those values.
3. The whole swap now takes 6 transactions.
With so many transactions, this exchange obviously requires much more time and attention than with previous protocols. Also, Alice and Bob have to pay commission to the network for handling each transaction. On the bright side, there’s no commission charged by the DEX.
As you can see, with great privacy comes great responsibility. Let’s implement Protocol #2 into our DEX demo and see a real-life example of using atomic swaps on a decentralized exchange.
Now we’ll illustrate how atomic swaps can be useful in a DEX. As mentioned above, the main purpose of our decentralized exchange is to:
- help Alice declare her intention to exchange ONT to ETH
- let Bob know Alice’s order details and respond to the order
- facilitate all further exchange steps.
In this section, we propose an architecture for a decentralized exchange powered with atomic swaps, introduce our demo of a simple DEX, and show how it works. At the end of the article, you’ll find a link to the demo source code.
Note that in this example, we assume that matchmaking has already occurred. Alice and Bob know the order details and wish to proceed with the transaction.
Let’s take a look at how an atomic swap-powered DEX works in our example.
We need to create Ontology and Ethereum smart contracts that will implement atomic swap exchange logic as described in Protocol #2. They will provide a trustless way to lock assets and for exchange parties to claim them.
Interacting with bare smart contracts can be challenging and requires both technical skills and patience. We also have to make smart contracts user-friendly by presenting order data in a convenient way and providing a way of interacting with smart contracts with the help of a frontend application.
Also, order data should be collected and stored somewhere before it’s presented to anybody. In other words, we need an order book. Smart contracts (Ontology and Ethereum contracts, in our example) could be candidates for the role, but this approach would put the contract under a significant additional load.
A more efficient way of organizing an order book is to create an application that will collect data from the contracts and present it in an organized way. This will require contracts to emit events once an exchange step has occurred. An order book application will scan the network for those events and update the order database.
Of course, before trusting data from the order book, users should verify it directly by querying smart contracts, since any external application can temper with sensitive data.
Our demo consists of Ethereum and Ontology smart contracts and a frontend application to interact with them.
The frontend demo is not a fully functional DEX but rather a way to facilitate the interaction with smart contracts in order to see how atomic swaps work.
We haven’t implemented an order book in order to keep our demo simple. The demo also suggests that Alice and Bob have a safe communication channel and can provide each other with the order hash once it's created and their addresses.
Our prototype interacts with Ontology smart contracts (deployed to the Ontology testnet at the
14972f644a4c43a9e097ee55968f877ce799754d address) and Ethereum smart contracts (deployed to the Ropsten testnet at the
We have two hardcoded users: Alice and Bob. Alice wants to sell some amount of ONT for ETH, and Bob wants to exchange his ETH for ONT. Private keys and addresses are located in the hardcoded users object.
Note: If you wish to experience the demo yourself, it would be best to replace default data with your own test accounts.
Our demo also has a Check order data page that allows you to check the state of the order. It also can be handy to monitor what’s going on with smart contracts using Ontology and Ethereum testnet block explorers.
5 Security Tips for Writing Smart Contracts
Let’s go through the entire exchange process to show how our demo works. First, we go to the Create order page to initiate an exchange with Alice.
When the transaction is completed, the respective amount of ONT will be transferred from Alice to a smart contract. The following message will appear:
It’s important to securely save the hashlock and secret number; otherwise, you can permanently lose access to your locked ONT.
Let’s assume Alice has safely stored the following data:
Now it’s time for Bob to respond to Alice’s order. We assume that Bob knows the hashlock and order details already (i.e. through using some public order book aggregator), but that is not significant in terms of our demo.
At this point, Bob goes to the Respond to order page:
Here, Bob inputs the hashlock of the order he wants to respond to. The amount of ETH to be locked in Bob’s Ethereum smart contract is automatically set from the value in the corresponding Ontology contract.
Now both Alice and Bob can assure themselves that the order has been initiated correctly:
Notice that the Ontology contract holds Alice’s Ontology address (presented in hex), and the Ethereum contract holds Bob’s Ethereum address.
If either party changes his or her mind at any point before locking the address of the other party, he or she can request a refund. A refund is also possible if the other party’s address is locked, but only after the refund timelock is up.
Both Alice and Bob can request refunds from their accounts. Refunding will only work if assets have not been claimed by the other party.
Now that Bob has already responded to Alice’s order, she should lock the buyer Ontology address. It’s a good idea for her to check the order data first and verify that the appropriate amount of ETH was indeed locked.
After making sure the amount of ETH is correct, Alice can go to the Lock buyer address page to add Bob’s Ontology address to the smart contract:
Notice that Bob’s Ontology address (hex representation) is inputted beforehand for convenience.
Now Bob should check the order data and make sure his Ontology address is correct.
After that, Bob should go to the Lock initiator address page and lock Alice’s Ethereum address (inputted beforehand as well).
The exchange is almost completed. At this point, the secret should be revealed and the assets claimed.
Please note that the timelocks in our deployed testnet contracts are set to 10 and 20 seconds for the purposes of quick proof of concept testing. In real life, DEX timelocks should be longer — for example, 24 and 48 hours instead of the 10 and 20 seconds in our Ethereum and Ontology contracts, respectively. It’s also unsafe to perform a claim after a refund timelock is up in a real exchange.
Alice now ensures that her Ethereum address is correct:
Alice uses this address to send her secret to the Ethereum smart contract and claim her ETH from the Claim ETH page:
Once the secret is revealed, Bob can get this value from the Check order data page:
Bob can now copy the value of the secret and input it on the Claim ONT page:
That’s it! Once all the steps mentioned above are completed, the exchange is successfully performed.
You can find the demo source code and setup instructions on our GitHub page. If you’d like to go through the exchange process with the help of atomic swaps, feel free to download the repo and play around.
Make sure to read the README.md file and follow its recommendations and instructions.
When developing a decentralized crypto exchange, users’ security is always the top priority. Atomic swaps allow us to eliminate several significant vulnerabilities and help users perform crypto exchanges securely even if they don’t trust each other.
As we can see from examples in this article, the most secure and reliable way of performing a decentralized exchange based on atomic swaps requires users to follow strict instructions and perform steps in time. Although it may seem inconvenient, this allows users to control their funds and minimize the risk of fraud.
At Apriorit, we have an experienced team of blockchain developers who are ready to consult about your dream project, offer the most convenient and efficient platforms and frameworks, and develop a robust solution. Contact us to start building your blockchain solution right away.