DeversiFi Trading API Client Library for Node.JS
A Node.JS client for the DeversiFi API
Note, DeversiFi evolved from Ethfinex Trustless, and this client library is due to be replaced at the end of February 2020 with an updated version.
- Placing an Order
- Cancelling Orders
- Account History
- Unlocking Tokens
- More examples
- Useful Links
npm i efx-api-node
Prebuild for browser
Alternatively on the browser you can use the standalone build
Authentication to make all the following requests is done by signing using an Ethereum private key. Signing is handled by the DeversiFi client library if the account is available and unlocked. However if signing using a hardware wallet, or using a raw private key, the message and signature need to be prepared separately.
- An ethereum wallet
- A web3 provider with your account or a private key
- Such as MetaMask, keystore file, hardware wallet or raw private key
Using MetaMask or a local node
// In case of MetaMask make sure you call ethereum.enable() before using itconst EFX =const efx = await
Using a remote node
const EFX =const web3 = ""const efx = await
const HDWalletProvider = ;const Web3 =const privateKey = '8F085...' // Account's private keyconst infuraKey = '9e28b...' // Your Infura API KEYconst infuraURL = '' + infuraKeyconst provider = privateKey infuraURLconst web3 = providerefx = await
View the full example: /examples/node_sell_eth_infura.js
It's possible to overwrite values on the configuration on a per instance basis.
The default configuration can be overwriten with an optional
userConf when calling the EFX function.
efx = await
The configuration is also merged with the configuration provided by the exchange
on the HTTP endpoint
/v1/trading/r/get/conf which at the moment looks similar
The complete compiled configuration is accessible through
efx.config, for instance:
const efx = awaitconst config = efxconfig
You can setup a custom gas price by setting up the 'gasPrice' property
const efx = awaitefx
Placing an Order
Before placing an order, you are required to lock tokens into the DeversiFi wrapper contracts. This allows for guaranteed execution and ensures DeversiFi orders can be added directly onto the centralised order book, and matched against trades from centralised users.
The first time locking an ERC20 Ethereum-based token from a specific account, you are required to approve it to interact with the time-lock smart contracts.
const token = 'ZRX'efxcontract
This step does not need to be repeated again, and subsequently you are required only to call the lock function. This transfers tokens into the wrapper token contract, ready to trade.
const token = 'ZRX'const amount = 15 // Number of tokens to lockconst forTime = 48 // Time after which unlocking does not require permissionconst response = await efxcontract
The time limit specified when locking is a maximum - tokens can always be unlocked after this time limit (in hours) expires. In order to unlock tokens before this expires, you must request a signed permission from DeversiFi.
This is always returned if you have no orders open involving those tokens.
Submitting an order
const symbol = 'ZRXETH'const amount = -15const price = 00025const orderId = await efx
Orders are generated and submitted, returning either an
orderId or error. A
full list of possible errors and their associated explanation is available here.
When submitting this order we use the 3 first parameters:
symbolis the pair which you wish to trade
amountis specified in the first currency in the symbol (i.e. ZRXETH). For a sell, amount is negative. Amount accepts either maximum 8 d.p, or as many decimals as are available on the relevant token's smart contract if it is fewer than 8.
priceis specified in the second currency in the symbol (i.e. ZRXETH). Prices should be specified to 5 s.f. maximum.
Warning: DeversiFi orders will always be settled at the exact price you specify, and can never be adjusted by DeversiFi, even if it is at a worse price than the market.
For example, when placing a sell order, if the
price specified is below the highest bid available on the order book, the order will be executed instantly at market. However, the amount you receive will reflect only the
price that you entered, and not the market price at the time of execution.
You can additionally provide
gid- Group ID for your order
cid- Client order ID
signedOrder- A previously signed order, in case you're handling signing
validFor- optional amount of hours this order will be valid for, default to 3600 seconds as specified on the default configuration
Tether market shift
The XXX/USDT markets on DeversiFi build on the liquidity of XXX/USD markets on centralised exchanges. However since there is often not a direct 1:1 rate between USD and USDT, a shift must be applied to the order books.
The configuration for DeversiFi returns a
settleSpread is indicative of the current USDT/USD exchange rate. When orders are placed
on USDT markets, the settlement price in the signed order must be shifted by the
parameter before the order is accepted.
For example, if placing a buy order on the ETH/USD(T) market at a price of 100 USD relative to the centralised exchange the order will be settled on DeversiFi at a price of 102 USDT. Equally a sell order at 100 USD would receive 102 USDT when settled on DeversiFi.
efx // => settlementPrice = price * (1 + settleSpread)
settleSpread parameter is set dynamically as a 30 minute rolling mean of the USDT/USD
market exchange rate. When placing orders using
submitOrder or generating them with
createOrder the shift is applied for you.
Cancelling orders requires the
orderId you wish to cancel to be signed by the
address which created and placed the order.
In case you're not signing the requests yourself
In case you're signing the requests yourself:
const sig = await efxconst sigConcat = ethUtilsawait efx
If you already have an unlocked wallet available to web3 to use for signing, you can simply get open orders and order history from the API as follows:
// Get all open ordersconst openOrders = await efx// Get all historical ordersconst historicalOrders = await efx
If an unlocked account is not available to sign with, for example when using a
raw private key or hardware wallet, authentication
signature must be
pre-signed and passed into the calls.
nonce is required to be a timestamp less
than 3 hours in the future.
signature is the
nonce signed using the relevant
private key for the address who's orders you wish to view.
const ethUtils =const privKey = /* Your Private Key */const nonce = Date / 1000 + 10800 + ''const hash = ethUtilsconst signature = ethUtils// Get all open ordersconst openOrders = await efx// Get all historical ordersconst historicalOrders = await efx
If tokens are not used in active orders they can always be unlocked. If unlocking after the time specified when locking has expired, no permission is required. When unlocking before this, DeversiFi must sign a release permission, after verifying that you have no orders currently active which require that token.
If you need permission the library will automatically call the expected endpoint on DeversiFi API to ask for such permission.
const token = 'ZRX'const amount = 15const response = await efxcontract
When a particular token's lock time has not yet expired, permission is required from DeversiFi to unlock early. This permission can be requested directly from DeversiFi using an API call.
The request must be authenticated using a nonce and signature, and the response contains a signed permission from DeversiFi. This permission will always be granted if DeversiFi is online and your address has no open orders involving those tokens. In case you're signing the requests yourself you could use the following code:
// This example shows how to generate the signature from a raw private key// Signing using hardware wallets such as Ledger or Trezor can be done using their documentationconst ethUtils =const privKey = /* Your Private Key */const nonce = Date / 1000 + 350 + ''const hash = ethUtilsconst signature = ethUtilsconst response = await efxcontract
const token = 'ZRX'const amount = 0001const response = await efxcontract
Aside from these examples, there are complete examples in the examples folder
Submitting a buy order
const symbol = 'ETHUSD'const amount = 1const price = 100efx
Submitting a sell order
const symbol = 'ETHUSD'const amount = -1const price = 100const orderId = await efx
Fetching info about specific order
const id = 1const order = await efx
If you have suggestions to improve this guide or any of the available documentation, please raise an issue on Github, or email email@example.com.
bash <(curl https://get.parity.io -L) # install parity
Run a node
parity --chain kovan --jsonrpc-apis=all --geth
- note the jsonrpc set to all
- note the
--gethin order to be compatible with
geth's unlock 'duration' parameter
geth --testnet --fast --bootnodes "enode://firstname.lastname@example.org:30303,enode://email@example.com:30303" --rpc --rpccorsdomain "*" --rpcapi "eth,web3,personal,net"
Alternatively, thanks to ganache-cli we can easily run an eth rpc node emulator. (NOTE: currently tests will fail using ganache)
Implementing a new feature
Starting by watching the test files ( you will need a node running )
$ npm run test:watch
- Write the tests for your new features on the
- Add your tests to './test/index.js' file if necessary
- Create your features on ./src/ folder
- You will need a ropsten node to do blockchain related tests
$ npm run test
On a headless browser ( using browserify and mochify )
$ npm run test:web
Manually on your browser on a browser console
- Very useful in case you want to issue commands from Google Chrome while using MetaMask !
$ npm run build:web:run
- Open your browser on http://localhost:2222
Building for browers
- This will build the whole library as one big ugly standalone js file ( uses browserify )
$ npm run build
Allow blockchain tests without relying on a local testnet node by using npm run test:rpc ( ganache ) and deploying mocked contracts at the beginning of the test.
Setup Travis-ci to test node.js, browser and standalone build. see this page