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

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 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

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

Above listed features of 0x protocol empower decentralised exchange.

Benefits of using 0x protocol –

0x protocol uses 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 an extensible APIs.

Efficient Design

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

0x protocol can be used in multiple use-case like games and collectibles, prediction markets, order book for decentralised exchange, decentralised 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 business logic of 0x protocol, exchange contracts is entry point for –

  1. Filling orders
  2. Cancelling 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 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 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 0x protocol. By using this library you can easily call smart contracts to create, cancel or validate order, check allowance and balance of ERC20 and ERC721 token holders.

To deep dive into 0x protocol and to know how 0x smart contracts work we need 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 counter party 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)

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

  1. Taker submits signed order to exchange smart contract, Using fillOrder() function of exchange smart contract.
  2. Exchange contract pass the order to settle on blockchain to corresponding ERC20Proxy contract, actual transfer of tokens will take place at 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 proxy contract.
  4. Revert on failure of ERC20 token contract of maker.
  5. Revert from ERC20Proxy contract to exchange contract.
  6. Exchange contract pass the order from exchange contract to ERC20Proxy contract.
  7. transferFrom() function is called of corresponding taker’s token contract from proxy contract.
  8. Revert on failure of ERC20 token contract of 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 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 smart contract will be owner of smart contract.

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 smart contract will be owner of smart contract.

Owner will be able to set 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 smart contract will be owner of smart contract.

Owner will be able to set exchange contract address in ERC20Proxy contract .

After deploying above contracts you need to set 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 address of assetproxy contract where actual transaction will take place to exchange tokens.

This function can be called by owner of 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 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 subprovider to interact with blockchain.

To interact with 0x.js library we need to import relevant packages as shown below, 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 address of smart contracts from 0x.js library.

Now maker(holder of tokenA) will create an offer and taker(holder of token B) will submit or fill 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 string
const 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 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 approves 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 maker
takerAddress: taker,//address of taker
senderAddress: taker,//address of sender
feeRecipientAddress: NULL_ADDRESS,//fee in the form of native currency of platform
expirationTimeSeconds: randomExpiration,//expire time of order
salt: generatePseudoRandomSalt(),//random no to differentiate order
makerAssetAmount,//maker asset amount
takerAssetAmount,//taker asset amount
makerAssetData,//encoded address of tokenA
takerAssetData,//encoded address of tokenB
makerFee: ZERO,//fee if required
takerFee: 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 hash of a 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 learnt till now and then will finalise 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 create an offer using 0x.js
  • Taker submit 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


How to integrate 0x(ZRX) Protocol to setup your own Decentralized Exchange (DEX) was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.