How to integrate 0x(ZRX) Protocol to setup your own Decentralized Exchange (DEX)

By Rajat Gahlot on ALTCOIN MAGAZINE

Rajat Gahlot
The Dark Side
Published in
8 min readMay 11, 2019

--

What is the 0x protocol and how does it work? Learn more about the 0x protocol, its off-chain order relays, and its decentralized exchange relayers here and how to use 0x smart contracts to make your own decentralized Exchange (DEX) on Ethereum public or private network.

Ref — https://cdn-images-1.medium.com/max/800/1*1SkgYeGxQ6nn_WF6zgWVpQ.gif

What is the 0x protocol?

0x is an open protocol that enables a peer-to-peer exchange of assets on the Ethereum blockchain.

Open-source infrastructure empowers developers and businesses to build products that enable purchasing and trading of crypto tokens including all ERC-20 and ERC-721 assets.

Let’s start with discussing features of 0x protocol.

Features of 0x protocol

  • Secure Non-custodial trading
  • Flexible Order types
  • Build a Business

Secure Non-custodial Trading

Enable tokens to be traded wallet-to-wallet with no deposits or withdrawals.

Flexible order types

Choose to sell assets at a specific “Buy it now” price or allow potential buyers to submit bids.

Build a business

Monetize your product by charging fees on each transaction and join a growing number of relayers in the 0x ecosystem.

Above listed features of 0x protocol empower decentralized exchange.

Benefits of using 0x protocol -

The 0x protocol uses a modular approach to trade assets on Ethereum blockchain.

  • Robust Smart Contracts
  • Extensible Architecture
  • Efficient Design

Robust Smart Contracts

0x Protocol’s smart contracts have been put through two rounds of rigorous security audits.

Extensible Architecture

0x’s modular pipeline enables you to plug in your own smart contracts through extensible APIs.

Efficient Design

0x’s off-chain order relay with an on-chain settlement is a gas efficient approach to P2P exchange.

The 0x protocol can be used in multiple use-cases like games and collectibles, prediction markets, the order book for decentralized exchange, decentralized loans and many more.

Moving on, “The smart contracts of 0x protocol”. 0x uses modular smart contracts of Ethereum blockchain that can be upgraded via governance without affecting other components of the system and without causing disruption in active markets.

Smart contracts of 0x protocol

  • Exchange Contract
  • ERC20 Proxy contract
  • ERC721 Proxy contract

Exchange Contract

Exchange contract contains the business logic of 0x protocol, exchange contracts is the entry point for -

  1. Filling orders
  2. Canceling orders
  3. Executing transactions
  4. Validating signatures
  5. Registering new AssetProxy contracts into the system

ERC20 Proxy contract

This contract is responsible to transfer ERC20 tokens on behalf of users. Thus each user (ERC20 token holder) must approve this contract to transfer tokens on the behalf of the token holder.

ERC721 Proxy contract

This contract is responsible to transfer ERC721 tokens. Thus each user (ERC721 token holder) must approve this contract to transfer tokens on the behalf of the token holder.

In order to deploy and use 0x smart contracts, you need to install 0x.js. 0x.js is a JavaScript library to interact with the 0x protocol. By using this library you can easily call smart contracts to create, cancel or validate the order, check allowance and balance of ERC20 and ERC721 token holders.

To deep dive into the 0x protocol and to know how 0x smart contracts work we need to understand 0x protocol’s Architecture

0x protocol uses an approach we refer to as off-chain order relay with on-chain settlement. In this approach, cryptographically signed orders are broadcast off the blockchain through any arbitrary communication channel. An interested counterparty may inject one or more of these orders into 0x protocol’s exchange contract to execute and settle trades directly on the blockchain.

Exchange ERC20-ERC20 tokens — 0x-github(source)

The 0x protocol can be used in order to exchange any ERC20 or ERC721 asset. The above picture shows how the actual transfer of tokens take place when taker submit the order in exchange for the smart contract.

  1. Taker submits signed order to exchange smart contract, Using fillOrder() function of exchange smart contract.
  2. Exchange contract passes the order to settle on blockchain to corresponding ERC20Proxy contract, the actual transfer of tokens will take place at the proxy contract. Note: maker and taker must approve ERC20Proxy contract before submitting an order to exchange.
  3. transferFrom() function is called of corresponding maker’s token contract from the proxy contract.
  4. Revert on the failure of ERC20 token contract of the maker.
  5. Revert from ERC20Proxy contract to exchange contract.
  6. Exchange contract passes the order from exchange contract to ERC20Proxy contract.
  7. transferFrom() function is called of corresponding taker’s token contract from the proxy contract.
  8. Revert on the failure of ERC20 token contract of the taker.
  9. Revert from ERC20Proxy contract to exchange contract.
  10. Return fill result.

Now we shall discuss about working and deployment of 0x smart contracts to trade assets on Ethereum using 0x.js library.

Use npm install 0x.js — save to install and save 0x.js library

Deployment steps of 0x smart contracts

To interact with smart contracts, we need to deploy 0x smart contracts and use the address of smart contracts to interact with smart contracts through 0x.js library.

Exchange smart contract

Source code available on git, deploy exchange smart contract where constructor of exchange contract doesn’t require any parameters and deployer (msg.sender) of the smart contract will be the owner of the smart contract.

The owner will be able to set assetProxy contract address in exchange contract.

ERC20 proxy contract

Source code available on git, deploy ERC20proxy contract where constructor of proxy contract doesn’t require any parameters and deployer (msg.sender) of the smart contract will be the owner of the smart contract.

The owner will be able to set an exchange contract address in ERC20Proxy contract.

ERC721 proxy contract

Source code available on git, deploy ERC20proxy contract where constructor of proxy contract doesn’t require any parameters and deployer (msg.sender) of the smart contract will be the owner of the smart contract.

The owner will be able to set an exchange contract address in ERC20Proxy contract.

After deploying above contracts you need to set the address of exchange contract to asset proxy contract and asset proxy contracts address to exchange contract. Call function registerAssetProxy(address ERC20/ERC721 proxy contract) function of exchange smart contract will store the address of asset proxy contract where the actual transaction will take place to exchange tokens.

This function can be called by the owner of the exchange smart contract only.

  • To register exchange contract on ERC20Proxy contract call function addAuthorizedAddress(address ExchnageContract).
  • To remove exchange contract from ERC20Proxy contract call function removeAuthorizedAddress(address ExchnageContract).

Use the address of exchange and asset proxy contracts to interact via 0x.js library.

let contractConfig = {contractAddresses: {erc20Proxy: proxyAddress.toLowerCase(),erc721Proxy: "0x1d7022f5b17d2f8b695918fb48fa1089c9f85401",exchange: exchangeAddress.toLowerCase() },networkId: networkId};const contractWrappers = new ContractWrappers(holderEngine, contractConfig);

Now you can interact 0x protocol smart contracts deployed on your private or test network. Remember to add RPC sub provider to interact with the blockchain.

To interact with 0x.js library we need to import relevant packages as shown below, the final goal is creating an order from maker account using 0x.js library and taker will submit using fillOrder() function to exchange tokens.

const {assetDataUtils,BigNumber,ContractWrappers,generatePseudoRandomSalt,orderHashUtils,signatureUtils,} 
= require(‘0x.js’);
const TX_DEFAULTS = { gas: 400000 };const { RPCSubprovider, Web3ProviderEngine } = require(‘0x.js’);let newWallet = new ethers.Wallet(wallet.signingKey.privateKey, prov);const holderWallet = new PrivateKeyWalletSubprovider(wallet.signingKey.privateKey.slice(2));

Add RPC Sub Provider

const holderEngine = new Web3ProviderEngine();holderEngine.addProvider(holderWallet);holderEngine.addProvider(new RPCSubprovider(providerUrl));holderEngine.start();In new RPC sub provider add custom URL to connect with blockchain that may be ethereum main net, test net or private blockchain.

Get contract address and instantiate contract wrapper

/ Instantiate ContractWrappers with the provider
const contractWrappers = new ContractWrappers(holderEngine, contractConfig);
const web3Wrapper = new Web3Wrapper(providerEngine);const contractAddresses = getContractAddressesForNetworkOrThrow(100);//networkID

Choose network id to get the address of smart contracts from 0x.js library.

Now maker (holder of token A) will create an offer and taker (holder of token B) will submit or fill the order to exchange tokens.

//contract Addresses
const tokenAAddress = contractAddresses.tokenA;
const tokenBAddress = contractAddresses.tokenB;const exchange = contractAddresses.exchange;

All the address are fetched from 0x.js library.

//encode all the necessary information about an asset into a single hexadecimal stringconst makerAssetData = assetDataUtils.encodeERC20AssetData(tokenAAddress);const takerAssetData = assetDataUtils.encodeERC20AssetData(tokenBAddress);const makerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(100), DECIMALS);const takerAssetAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(200), DECIMALS);const NULL_ADDRESS = ‘0x0000000000000000000000000000000000000000’;const ZERO = new BigNumber(0);
const DECIMALS = 18;

Now maker and taker should approve the corresponding asset proxy contract to transfer tokens on the behalf of maker and taker.

//Allow ERC20 Proxy to move tokenA on behalf of makerAccount
const makerApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(
tokenAAddress,
maker,
);
await web3Wrapper.awaitTransactionSuccessAsync(makerApprovalTxHash);
// Allow ERC20 Proxy to move tokenB on behalf of takerAccount
const takerApprovalTxHash = await contractWrappers.erc20Token.setUnlimitedProxyAllowanceAsync(
tokenBAddress,
taker,
);
await web3Wrapper.awaitTransactionSuccessAsync(takerApprovalTxHash);

After maker and taker approve asset proxy contract to transfer token on behalf of maker and taker respectively. Now maker will create an offer and sign the offer off chain and taker will submit the offer to exchange tokens.

Create Order

const order = {exchangeAddress: exchangeAddress,makerAddress: maker,//address of makertakerAddress: taker,//address of takersenderAddress: taker,//address of senderfeeRecipientAddress: NULL_ADDRESS,//fee in the form of native currency of platformexpirationTimeSeconds: randomExpiration,//expire time of ordersalt: generatePseudoRandomSalt(),//random no to differentiate ordermakerAssetAmount,//maker asset amounttakerAssetAmount,//taker asset amountmakerAssetData,//encoded address of tokenAtakerAssetData,//encoded address of tokenBmakerFee: ZERO,//fee if requiredtakerFee: ZERO,//fee if required};

Now we have created an offer; we will sign the offer after the order hash will be obtained by calling getOrderHash() function of 0x.js library. An order is hashed according to the EIP712 specification.

const orderHashHex = orderHashUtils.getOrderHashHex(order);

After obtaining the hash of an order maker will sign the order using ecSignHashAsync() function of 0x.js library.

const signature = await signatureUtils.ecSignHashAsync(providerEngine, orderHashHex, maker);const signedOrder = { …order, signature };await contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(signedOrder, takerAssetAmount, taker);try{txHash = await contractWrappers.exchange.fillOrderAsync(signedOrder, takerAssetAmount, taker, {TX_DEFAULTS,});var transaction = await web3Wrapper.awaitTransactionSuccessAsync(txHash);}catch(error){}}

Let’s take a quick recap of what we have learned till now and then will finalize our discussion by introducing projects that have already build on 0x.

Recap

  • Overview of 0x protocol
  • Features of 0x protocol
  • Working of 0x smart contracts
  • Maker creates an offer using 0x.js
  • Taker submit an offer to exchange

Projects that have already used 0x protocol to implement DEX and order book are listed below.

Decentralized exchange

Radar Relay, paradex, Star bitex, LedgerDex

Order Book

open relay

Thanks for reading. Hopefully this guide has been useful to you and will help you to understand the process to integrate 0x(ZRX) Protocol to setup your own Decentralized Exchange (DEX) and Also do check out my earlier blog posts.
At QuillHash, we understand the 0x protocol and have a team of developers who can develop blockchain applications like dApp, DeFi, DEX on the top of 0x(ZRX) Protocol.
Let’s discuss more on 0x(ZRX) Protocol, ping me on my telegram handle — https://t.me/bigrkg

--

--