How to build your own decentralized exchange based on Atomic Swaps using Oraclize

Markus Saitmacher
Coinmonks
10 min readMar 11, 2019

--

A depiction of how currencies could be swapped directly with Etherswaps, created with this Observable

A couple of months ago I had an idea about how one could swap cryptocurrencies across different Blockchains leaving the validation to a smart contract rather than a 3rd party. I got inspired by the Cosmos Network and how they perform atomic swaps between different blockchains. (Hence the visualization).

There are multiple reliable Blockchain Explorer APIs in place that could be queried to check the validity of transactions. However, nondeterministic computations such as API requests or random number generations are not possible in the blockchain world. In fact, a blockchain would fork if two nodes calculate a different version of “reality” so I had to find a workaround, and I did…

Oraclize makes it possible to perform API requests from within Smart Contracts. I will explain how exactly their services work towards the end but for now, you should keep in mind that they offer a trustworthy way to pull data from the outside world. With this great piece of technology in my pocket, I have built a functional proof of concept Dapp that lets you swap Ether with Bitcoin and Stellar Lumens you can find at Etherswaps.co . I will actively walk you through the process of swapping Ether for Bitcoin but before that let me give you a broad overview of how it works.

Overview

As you can see a Token Swap on the decentralized exchange is performed with 3 easy steps.

  1. Bob locks up his Ether in a smart contract defining for how much Bitcoin he wants to exchange it.
  2. Alice sees that Offer in the Marketplace and pays the equivalent amount to Bob’s Bitcoin address. Then she submits the Transaction Hash to the Smart Contract using the Etherswaps Dapp.
  3. After that she submits the transaction hash to the Smart Contract it conducts an Oraclize API request to check if the transaction is valid. If the submitted amount is >= Bob’s requested amount (1 BTC) the Smart Contract sends the funds to Alice’s Ethereum address.

The very principle is that users can proof to the smart contract that they have conducted the right form of payment which entitles them to receive the locked up Ether.

Theoretically one could even use this system to exchange Fiat currencies with Ether or any other ERC20 Token as long as the verification data is public. While it cannot be regarded as completely safe and should not be used in production but only on Testnets, it does have some interesting properties. So let me walk you through the process of swapping Ether for Bitcoin and show you how you can build your own decentralized exchange that supports different currencies on top of it.

How to use it

Let me show you how the 3 steps to perform the Token Swap work in the Etherswaps Dapp. We will create an Offer in the Smart Contract and pay it out swapping Ether for Bitcoin.

First Step

Go to http://etherswaps.co and connect to the Dapp with Metamask. Then add my local blockchain instance at http://blockchain.etherswaps.co as a custom RPC. You can also use the Ropsten Testnet but it is much slower with validation at this point.

If you use my Blockchain instance import one of the following private Keys which has 100 Ether stored on them, but please be economical ;)

  • 0x7a7ce0fa57cf26a6e5064a61b1ba9135680e776956bf19d26f6964f185fcb9c7
  • 0x7fa4f9979b728b9a58c2dc7ab70f42e735a3cef135ea572f83e8a2d908b7289d
  • 0x1bc2129af5929d2772c5599d3a9da8329e1c1a020980e3028710cd6ad2f55327
Connect to the Dapp, import the Private Key and connect to the Custom RPC http://blockchain.etherswaps.co

Second Step

Continue to create an Offer and type in the desired Bitcoin Address , Bitcoin Amount (in Satoshi) and the Amount of Ether (in Wei) the offer is worth for you. The label will automatically display the latest price. Use this Bitcoin address 1MfJVqRgryFvnGSQjVt3xCAhdwmcwairYQ and define you want to lock up 2 Ether for 0.08876 BTC.

So you should type in the following:

  • Bitcoin Address : 1MfJVqRgryFvnGSQjVt3xCAhdwmcwairYQ
  • Bitcoin Amount (in Satoshi) : 700000
  • Amount of Ether (in Wei) : 2000000000000000000

A MetaMask Page will pop up and you can confirm the details of the transaction.

It is Important to mention that you should only use “fresh” Bitcoin addresses without any prior transaction because otherwise a malicious party could send the wrong transaction hash and claim your Ether for free! (more on security later). Luckily the website does an automatic check and throws an error if the address has received any prior transactions (currently deactivated for testing however).

The Dapp will update the live prices of Ether, Bitcoin and Lumens accordingly

Third Step

Next, we send the 0.007 BTC to the address and submit the transaction Hash to claim the Ether. Luckily for you, I have already done that and you can see the transaction here sending exactly 0.007 BTC to our address.

Go to the Market page and choose you just created an Offer. Ideally, you should have been redirected and the correct Offer should be highlighted. When you click on it a modal will pop up with more details allowing you to enter the transaction hash of the Bitcoin Transaction.

  • Bitcoin Transaction Hash : 014ed2e6f875da84648fb38f5b39077f8d54466aecef371a4fe5f9f754088c46

Then confirm the transaction with MetaMask. In the background, a transaction to the underlying smart contract is sent. It performs an API request using Oraclize to check if the transaction has sent the correct amount to the associated Bitcoin address. If that is the case the smart contract will payout the deposited Ether to your Ethereum address and after approximately 30 seconds you will receive a notification that the amount was paid out.

The Ether was payed out correctly!

The Tech Stack

To build the Etherswaps decentralized Exchange: I have used the following technologies:

Let me go more in depth on how the Smart contract works, how the Dapp interacts with it and what security vulnerabilities exist.

Smart Contract Deep Dive

Let me show you an oversimplified version of the Smart Contract with no security mechanisms in place to give you a good overview of how it works. You can find the complete contract code here. As I have mentioned it is still not fully audited and should not be used in production by any means.

Code example can not be compiled

Pretty simple right?

1. Ether is stored in the contract and a struct that represents the offer is stored inside a Map so it can be referenced later (note that the _bitcoinAddress variable s acts as an identifier for the Offer struct)

2. The getTransaction function is called when a user submits his transaction hash which in turn performs the Oraclize API request via the oraclize_query function. Both the sender address and the oraclizeID and bitcoinAddress value pair is stored inside Maps.

3. Behind the scenes, Oraclize performs an API request to this Blockchain.info API endpoint which has the form https://blockchain.info/q/txresult/<txHash>/<address> returning a single string with the transferred amount. Oraclize does allow you to perform some form of JSON parsing beforehand because parsing JSON in Solidity is very expensive. In fact, any string operation in Solidity consumes a lot of gas as you can see here. Upon receiving the Data, Oraclize sends it to the __callback function. If the amount is higher or equal to the predefined bitcoinWithdrawAmount the locked up Ether is paid out to the Ethereum address that submitted the transaction Hash. Note how it gets the right recipientAddress from the Map setting the Offer struct key exists to false so it cannot be paid out again. A little tricky, but totally works! 🙂

With this concept, one could integrate any other currency as long as there is a trustworthy and public API in place to lookup transactions. To fully understand the last part and how to integrate other currencies we need to understand how Oraclize works in the background.

Oraclize (Source)

From their website:

The solution developed by Oraclize is instead to demonstrate that the data fetched from the original data-source is genuine and untampered. This is accomplished by accompanying the returned data together with a document called authenticity proof. The authenticity proofs can build upon different technologies such as auditable virtual machines and Trusted Execution Environments.

Essentially Oraclize runs a node monitoring a special smart contract that receives queries for API requests. When another smart contract calls a specific function with the API query, the Oraclize node notices it and performs the API request. An authenticity proof is created and then they call the __callback function in your smart contract passing it the returned result of the API request as an input. You can test your Oraclize queris beforehand at this site.

To sum it up, Oraclize offers a trustworthy and reliable way to pull Data from the Outside world. The README of my Github repository goes in depth on how to test it and how to use Oraclize on your local machine, I highly encourage you to try it out yourself.

Some words on React and Web3

I have used to React to build the client Front-end and Express for the Back-End. With the JavaScript Web3 library, the Front-End is able to interact with the contract allowing users to use Metamask and get notifications once transactions went through. For testing, I recommend using the web3 provider of Ganache though. I also highly recommend to always check if you are using the correct version of Web3. There has been some breaking changes in the 1.0 release and using the wrong version can lead to some very strange errors.

Altogether Web3 is a fairly new library and relying purely on it to display smart contract data is still not very intuitive and hacky at this point. Hence I used MongoDB in combination with an express API to store the Offer data locally.

While this makes it more centralized and leaves a security vulnerability, it can still easily be replaced with the decentralized IPFS file storage system. You can find out more about the Inter Planetary File System and how it stores Data in a decentralized way here and how to implement it here.

Security considerations

Of course, centralized data storage is not the only security vulnerability. Besides the usual problems of double spending attacks, smart contract bugs could occur as the contract is not fully audited. There are three security aspects I want to point out though.

  1. I left a backdoor to pay out the original owner of an Offer if he decides he does not want to swap his Ether anymore. Because this leaves an additional security vulnerability (a user could try to redeem a nonexisting offer if data is updated too late) I have not implemented it in the UI but only in the smart contract code at this point.
  2. Some of you may have found another security vulnerability which is grounded in the asynchronous nature of creating the bitcoin transaction first and then submitting it to the smart contract. A malicious party could wait for transactions to the bitcoin address and claiming the Ether before you by submitting the transaction hash first. To solve this problem a user would have to write his Ethereum address in the transaction metadata (like such) so the Smart Contract can verify that the correct address tries to claim the Ether. This again is implemented in the smart contract but is not in the UI yet to keep things simple.
  3. Another security vulnerability I left open for testing purposes is to out-comment the following line:
All offers are stored in the deposit map

This allows all users to create multiple offers with the same address.

Lastly, another important aspect to mention is that Block Explorer data could be inaccurate or the servers could be down. While unavailable servers are not a problem since the transaction hash can be submitted later, there is still a good amount of trust required in Block Explorer services which leads me to my last Topic:

Whom you need to trust

As with any financial service, there is still trust required when interacting with it. In fact, there are 4 parties anyone using Etherswaps has to trust:

1. Oraclize services to display the data correctly. However they have done a pretty good job on making it publicly verifiable. You can find out more about it here

2. The Block Explorer API, the contract is currently using Blockchain.info and the official Horizon Stellar API which other big exchanges rely upon as well

3. The smart contract itself. Notice that it has not undergone security audits and should not be used in the production

4. The server the website is running on, to display the data correctly. However anyone could host it themselves.

Conclusion

As you can see this decentralized exchange is not free of trust. One still has to trust different parties. However, it effectively reduces middleman and transaction costs while offering a simple and cheap way to swap tokens on the blockchain. With a smart contract doing the verification asynchronously it is much more decentralized than any major exchange and even other decentralized exchanges. No signups or regulation required to swap your Coins and anyone could host this service isn’t that awesome?

Lastly, I want to mention that the project was a great learning experience for me and I want to give a big shout out to Oraclize, they have been really helpful answering all kinds of questions in their Gitter channel. Please note that I am not associated with Oraclize in any form and the opinions stated above are my own.

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

Also, Read

--

--