How to build a distributed exchange based on atomic interchange technology using Oraclize

A few months ago, I had an idea of ​​how to exchange cryptocurrencies between different blockchains, leaving verification to smart contracts, not third parties. I was inspired by the Cosmos Network and how they inspire atomic exchange between different blockchains.

The Blockchain Explorer API is available for queries to check the validity of the transaction. However, in the blockchain world, uncertainty calculations such as API requests or random number generation are not possible. In fact, if two nodes calculate different versions of "reality", the blockchain will fork, so I have to find a solution.

Oraclize can execute API requests from smart contracts. I will explain how their services work, but for now, you should remember that they provide a reliable way to extract data from the outside world. With this great technology in my pocket, I have built a functional proof of concept Dapp that allows you to exchange Ethereum with Bitcoin and Stellar Lumens you find on Etherswaps.co. But before that, I will give you an overview of how Bitcoin works.

As you can see, the exchange of tokens on a distributed exchange is performed in 3 easy steps:

  • Bob locks his Ethereum in a smart contract and defines how many bitcoins he wants to redeem.
  • Alice sees the transaction in the market and pays the amount equivalent to Bob's bitcoin address. She then uses Etherswaps Dapp to submit the transaction hash to the smart contract.
  • She then submits the transaction hash to the Smart Contract, which executes the Oraclize API request to check if the transaction is valid. If the submitted amount >= Bob's request amount (1 BTC), the smart contract will send the funds to Alice's Ethereum address.

The principle is that users can prove to smart contracts that they have taken the correct payment method and that they have the right to obtain locked Ethereum.

In theory, as long as the verification data is public, one can even use the system to exchange fiat money with Ether or any other ERC20 token. Although it can't be considered completely safe, it shouldn't be used in production, it should only be used on the test web, but it does have some interesting features.

How to operate

We will create an offer in the smart contract and pay it to Bitcoin for exchange of Ethereum.

first step

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

If you use my blockchain instance, import one of the following private keys, which already has 100 ethers stored, but use them as they are;)

  • 0x7a7ce0fa57cf26a6e5064a61b1ba9135680e776956bf19d26f6964f185fcb9c7
  • 0x7fa4f9979b728b9a58c2dc7ab70f42e735a3cef135ea572f83e8a2d908b7289d
  • 0x1bc2129af5929d2772c5599d3a9da8329e1c1a020980e3028710cd6ad2f55327

Second step

Continue to create a quote and enter the desired bitcoin address, bitcoin amount (Satoshi) and quoted E-dollar amount (Wei). The label will automatically display the latest price. Use this bitcoin address 1mfjvqrgryfvngsqjvt3xcahdwmcwairyq and define to lock 2 Ethereum for 0.08876 BTC.

Therefore, you should type the following:

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

The MetaMask page will pop up and you can confirm the details of the transaction.

It's important to mention that you should only use the "new" bitcoin address without any prior transactions, otherwise the malicious party may send the wrong transaction hash and apply for your Ethereum for free! Fortunately, if the address has received any previous transactions (currently disabled for testing), the site will automatically check for and throw an error.

third step

Next, we send 0.007 BTC to the address and submit a transaction Hash to declare the Ethereum. Fortunately, I have done it, you can see that the transaction here just sent 0.007 BTC to our address.

Go to the market page and select the quote you just created. Ideally, you should be redirected and the correct quote should be highlighted. When you click on it, a mode will pop up with more details, allowing you to enter a trading hash of the Bitcoin transaction.

  • Bitcoin Transaction Hash : 014ed2e6f875da84648fb38f5b39077f8d54466aecef371a4fe5f9f754088c46

Then use MetaMask to confirm the transaction. In the background, the transaction of the underlying smart contract is sent. It uses Oraclize to execute an API request to check if the transaction has sent the corresponding amount to the relevant bitcoin address. If this is the case, the Smart Contract will pay the deposited Ethereum to your Ethereum address. After approximately 30 seconds, you will receive a notification indicating that the amount has been paid.

Code writing

Building an Etherswaps Distributed Exchange: I used the following techniques:

  • Solidity writing smart contracts
  • Truffle, Ganache, Remix IDE and Oraclize Ethereum-Bridge for local testing and development
  • Web3Js and MetaMask interact with Blockchain in JavaScript
  • React and Materialize front-end Css
  • Express, Nginx and MongoDB are used to serve websites and store auxiliary data (I plan to replace MongoDB with IPFS)

Let me take a deeper look at how smart contracts work, how Dapp interacts with them, and what security vulnerabilities exist.

Smart contract deep mining

Let me show you a simplified version of the smart contract that doesn't have any security mechanisms to give you a good idea of ​​how it works. You can find the complete contract code here. As I mentioned, it has not been fully audited and should not be used for production in any way.

  • Ether is stored in the contract, indicating that the structure of the item is stored in the Map for later reference (note that the _bitcoinAddress variable s is the identifier of the Offer structure)
  • When the user submits its transaction hash, the getTransaction function is called, and the transaction hash executes the Oraclize API request through the oraclize_query function. The sender address and the oraclizeID and bitcoinAddress value pairs are stored in Maps.
  • Oraclize executes an API request to this Blockchain.info API endpoint in the format https://blockchain.info/q/txresult/ <txHash> / <address>, returning a single string with the transfer amount. Oraclize allows you to perform some form of JSON parsing in advance, because parsing JSON in Solidity is very expensive. In fact, as you can see here, any string manipulation in Solidity consumes a lot of gas. After receiving the data, Oraclize sends it to the __callback function. If the amount is higher than or equal to the predefined bitcoinWithdrawAmount, the locked Ethernet will be paid to the Ethereum address that submitted the transaction hash. Note how it gets the correct recipientAddress from the Map settings. The Offer struct key exists as false, so it cannot be paid again. A bit tricky, but completely effective!

With this concept, you can integrate any other currency as long as you have a trusted public API to find the transaction. To fully understand the last part and how to integrate other currencies, we need to understand how Oraclize runs in the background.

Essentially, Oraclize runs a node that monitors a special smart contract that receives queries for API requests. When another smart contract invokes a particular function using an API query, the Oraclize node notices it and executes the API request. Create a proof of authenticity, then they call the __callback function in the smart contract and pass the result of the API request as input to it. You can test your Oraclize queris on this site in advance.

All in all, Oraclize provides a reliable and reliable way to extract data from the outside world.

Some words about React and Web3

I am used to React to build client-side Front-end and Express for the backend. Using the JavaScript Web3 library, the front end can interact with the contract, allowing users to use Metamask and receive notifications when the transaction is complete. For testing, I recommend using Ganache's web3 provider. I also strongly recommend that you always check that you are using the correct version of Web3. There are some major changes in the 1.0 release, and using the wrong version can lead to some very strange bugs.

All in all, Web3 is a fairly new library, and relying solely on it to display smart contract data is still not very intuitive and simple at this point. Therefore, I use MongoDB with the Express API to store the data provided locally.

While this makes it more focused and leaves a security hole, it can still be easily replaced with a decentralized IPFS file storage system.

Safety considerations

Of course, centralized data storage is not the only security hole. In addition to the common problems of double-spending attacks, smart contract vulnerabilities may also occur because the contract has not been fully audited. However, I would like to point out three security aspects.

  • If he decides not to exchange his ether, I will leave a back door to pay the original owner of the offer. Because this leaves an extra security hole (if the data is updated too late, the user may try to redeem the non-existent offer) I have not implemented it in the UI, but only in the smart contract code.
  • Some of you may have discovered another security vulnerability based on the asynchronous nature of creating Bitcoin transactions and then submitting them to smart contracts. A malicious party can wait for a transaction to the bitcoin address and declare the Ethernet by submitting a transaction hash before you. To solve this problem, the user must write his Ethereum address in the transaction metadata (so) so that the smart contract can verify that the correct address is attempting to declare Ethernet. This is again implemented in smart contracts, but it has not been kept simple in the UI.
  • Another security hole I opened for testing purposes was to comment on the following lines:

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

Finally, another important aspect is that the Block Explorer data may be inaccurate or the server may be down. Although the server that is not available is not a problem, because the transaction hash can be committed later, there is still a lot of trust in the Block Explorer service, which leads me to the previous topic:

Who is trustworthy?

As with any financial service, you still need to trust when interacting with it. In fact, anyone who uses Ether Exchange must trust the following four aspects:

  • The Oraclize service displays the data correctly. However, they have done a very good job in publicly verifiable;
  • The Block Explorer API, the contract is currently using Blockchain.info and the official Horizon Stellar API that other large exchanges rely on.
  • Smart contract itself. Please note that it has not been audited for safety and should not be used in production.
  • The server running on the website to display the data correctly. But anyone can host it by themselves.
to sum up

As you can see, this decentralized exchange is not immune to trust. People still have to trust different parties. However, it effectively reduces middleman and transaction costs while providing a simple and inexpensive way to exchange tokens on the blockchain. Smart contracts are verified asynchronously, and they are more fragmented than any major exchange or even other decentralized exchanges.

This article reprints the public number: Blockchain Research Laboratory. Welcome to contact the author: csschan1120

We will continue to update Blocking; if you have any questions or suggestions, please contact us!

Share:

Was this article helpful?

93 out of 132 found this helpful

Discover more

Blockchain

Blockstream CEO Adam Back: Bitcoin sidechain may destroy competitive coins

Adam Back, an early cryptocurrency developer and cryptographer, gave a speech on the bitcoin sidechain during a publi...

Market

Bitcoin's price decreases by 1.3% within an hour as US payrolls exceed predictions.

Bitcoin quickly responds to U.S. jobs data, causing a temporary price decrease below the $43,000 level.

Blockchain

QKL123 market analysis | Buffett cuts his face, the global epidemic slows down, is it good for Bitcoin to halve? (0407)

Summary : Yesterday, the global capital market has soared, Bitcoin is linked, and altcoins have performed strongly. T...

Blockchain

NASDAQ: Joined Bitcoin's "Wish List" this year

The bitcoin of the previous day showed a rise of 5,500. According to the "rice law", the rise is sure to fi...

Market

Bitcoin has finally returned to $8,000, but why is it not recommended to chase?

The stock market is cold and the currency market is rejuvenating. Starting on May 10, bitcoin prices are all the way ...

Blockchain

With the reduction of Bitcoin production and the surge of computing power, the "year of mining disaster" of the 16nm mining machine is bound to come?

Around May 11, the third reduction in Bitcoin will come as scheduled. At that time, the Bitcoin block reward will be ...