At Kyber, we’re always looking for ways to simplify access to our liquidity protocol. A major area for enhancement is to allow a wider range of programs to interact with our protocol.

Today we’re introducing the Kyber Trading API, a REST API that gives users access to our on-chain liquidity without much smart contract experience. Applications written in a variety of programming languages can now integrate in a much simpler way than before.

What The Trading API Enables

The Kyber Trading API allows you to perform important trading operations like getting supported tokens, conversion rates and the trade function in your applications. There are currently 7 basic functions that can be automated with the trading API.

These 7 basic functions are:

This set of functions should allow the execution of the majority of use cases from applications, with more to be added in the future.

Note: The /buy_rate and /sell_rate APIs are currently restricted to ETH <-> ERC20 token. If you want to get the rates for a conversion between token A and token B, you need to run both APIs; the first to sell token A to ETH and the second to buy token B with ETH.

How To Use The API

To interact with the trading API, the user is required to have some programming experience and basic knowledge of the web3 such as signing and broadcasting transactions to the Ethereum network.

The APIs return a JSON formatted transaction payload which the user can serialize, encode and broadcast to the Ethereum blockchain using web3. The payload is configured such that no further modification from the user is necessary.

To help you understand the basic flow, we are going to go through a simple code example of broadcasting an ETH to KNC trade on the Ropsten network. You’ll need an Ethereum wallet with at least 1 Ropsten ether. If you do not have an Ethereum wallet, you can make one here. You can also use our faucet to get some Ropsten ether.

This tutorial can be replicated on mainnet but you’ll need to use the mainnet API (api.kyber.network) instead of the Ropsten API (ropsten-api.kyber.network) and replace the token’s contract address accordingly. Also, note that your real funds will be used when performing this on mainnet.

Scenario: Trade ETH for KNC

Import the relevant libraries

For this example, we will be writing our program in Javascript. We will be using the node-fetch, ethereumjs-tx and web3 javascript libraries to interact with the API and perform the ETH to KNC trade. The node-fetch library is used to query the trading API while the ethereumjs-tx library is used to sign and serialize the transaction. The web3 library will be used to broadcast the transaction to the Ethereum blockchain.

// Import web3 for broadcasting transactions

var Web3 = require(‘web3’); // Import node-fetch to query the trading API

var fetch = require(‘node-fetch’); // import ethereumjs-tx to sign and serialise transactions

var Tx = require(‘ethereumjs-tx’);

Connect to a Ropsten node

In order for the web3 library to be able to broadcast the transaction, we need to first connect to an ethereum node. We will be using Infura’s ropsten node for this tutorial.

// Connect to Infura’s ropsten node const web3 = new Web3(new Web3.providers.HttpProvider(“https://ropsten.infura.io"));

Defining the constants

We will define some constants that will be referenced later in this tutorial. Ensure that you replace the USER_ACCOUNT and PRIVATE_KEY values with your Ethereum wallet address and private key respectively. Note that the value of some of these constants e.g. token contract addresses and number of decimal can also be obtained from the API /currencies endpoint.

// Representation of ETH as an address on Ropsten const ETH_TOKEN_ADDRESS = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'; // KNC contract address on Ropsten

const KNC_TOKEN_ADDRESS = '0x4E470dc7321E84CA96FcAEDD0C8aBCebbAEB68C6';

const ETH_DECIMALS = 18;

const KNC_DECIMALS = 18; // How many KNC you want to buy

const QTY = 300; // Gas price of the transaction

const GAS_PRICE = 'medium'; // Your Ethereum wallet address

const USER_ACCOUNT = 'ENTER_WALLET_ADDRESS_HERE'; // Your private key

const PRIVATE_KEY = Buffer.from(‘ENTER_PRIVATE_KEY_HERE’, ‘hex’);

Check that KNC is supported

We need to check if that the KNC is supported on the Kyber protocol. We can use fetch to query the API /currencies endpoint to get a list of supported tokens.

// Querying the API /currencies endpoint

let tokenInfoRequest = await fetch('https://ropsten-api.kyber.network/currencies'); // Parsing the output

let tokens = await tokenInfoRequest.json(); // Checking to see if KNC is supported

let supported = tokens.data.some(token => {return 'KNC' == token.symbol}); // If not supported, return.

if(!supported) {

console.log('Token is not supported');

return

}

Get the ETH / KNC buy rates

Next, we’re going to get the KNC’s buy rates in terms of ETH. The API /buy_rate endpoint is used to get buy rates. The parameters required for this API endpoint are:

Destination token contract address (KNC_TOKEN_ADDRESS) Destination token quantity (QTY).

The src_qty represents how many ETH is needed to buy the specified amount (QTY) of KNC.



let ratesRequest = await fetch(' // Querying the API /buy_rate endpointlet ratesRequest = await fetch(' https://ropsten-api.kyber.network/buy_rate?id=' + KNC_TOKEN_ADDRESS + '&qty=' + QTY); // Parsing the output

let rates = await ratesRequest.json(); // Getting the source quantity

let srcQty = rates.data[0].src_qty;

Make the ETH to KNC trade

Similarly, we’re going to use fetch to query the API /trade_data endpoint to get the entire transaction payload to be broadcasted. The parameters required for this API endpoint are:

User’s Ethereum wallet address Source token contract address (ETH_TOKEN_ADDRESS) Destination token contract address (KNC_TOKEN_ADDRESS) Source token quantity (srcQty) Minimum destination token quantity (QTY * 0.97) Gas price (choose between low, medium or high)

Note that for minimum destination token quantity, it is up to you to decide what is the minimum acceptable destination quantity you’re willing to accept for the trade. For this example, I’ve decided to go with 97%.

Additionally as mentioned earlier, the user is not required to modify the transaction payload. He simply needs to sign it, serialize it, encode it and then broadcast it to the Ethereum blockchain.



let tradeDetailsRequest = await fetch(' // Querying the API /trade_data endpointlet tradeDetailsRequest = await fetch(' https://ropsten-api.kyber.network/trade_data?user_address=' + USER_ACCOUNT + '&src_id=' + ETH_TOKEN_ADDRESS + '&dst_id=' + KNC_TOKEN_ADDRESS + '&src_qty=' + srcQty + '&min_dst_qty=' + QTY*0.97 + '&gas_price=' + GAS_PRICE); // Parsing the output

let tradeDetails = await tradeDetailsRequest.json(); // Extract the raw transaction details

let rawTx = tradeDetails.data[0]; // Create a new transaction

let tx = new Tx(rawTx); // Signing the transaction

tx.sign(PRIVATE_KEY); // Serialise the transaction (RLP encoding)

let serializedTx = tx.serialize(); // Broadcasting the transaction

txReceipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).catch(error => console.log(error)); // Log the transaction receipt

console.log(txReceipt);

Full code example

For the full code example, please visit our KyberDeveloper website.

Start Building With Kyber!

From the tutorial in the previous section, you can see how easy it is for a user (without much smart contract experience) to write a program, in any language of their choice, and interact with the API to perform a trade.

This example is only the tip of the iceberg of what you can do with our trading API. We are very excited to see what you can build! For additional resources, the full API reference and trading API guide can be found on our Kyber Developer Portal. If you have any feedback or questions, you can find us in the Kyber Developer telegram group.

About Kyber Network

Kyber’s on-chain liquidity protocol allows decentralized token swaps to be integrated into any application, enabling value exchange to be performed seamlessly between all parties in the ecosystem. Using this protocol, developers can build innovative payment flows and applications, including instant token swap services, ERC20 payments, and financial DApps — helping to build a world where any token is usable anywhere.

Telegram group: https://telegram.me/kybernetwork

Reddit: https://www.reddit.com/r/kybernetwork/

Twitter: https://twitter.com/kybernetwork/

Website: https://kyber.network/