Home

Awesome

NOTE: This open-source client will be deprecated in December 2023. If you use this client to interact with rhino.fi for any reason please join our Discord and let us know so that we can continue to ensure you are supported https://discord.com/invite/V93Bxn7hAY or email support@rhino.fi

<img src="https://avatars1.githubusercontent.com/u/56512535?s=200&v=4" align="right" />

Rhino.fi Javascript Trading API

A js client library for Rhino.fi - StarkWare orders

Note: This library is for Rhino.fi. A test version of the platform to use during integrations is connected to the Goerli test network and hosted at:

Contents

<!--ts--> <!-- Created by https://github.com/ekalinin/github-markdown-toc --> <!-- Added by: adrian, at: Mon 6 Feb 11:54:24 GMT 2023 --> <!--te-->

Setup

Pre Requisites

Instatiating

Using MetaMask or a local node

// In case of MetaMask make sure you call ethereum.enable() before using it
const RhinofiClientFactory = require('@rhino.fi/client-js')
const rhinofi = await RhinofiClientFactory()

Using a private key

const HDWalletProvider = require("@truffle/hdwallet-provider");
const Web3 = require("Web3")

const privateKey = '8F085...' // Account's private key
const rpcUrl = 'https://mainnet.infura.io/v3/9e28b...'

const provider = new HDWalletProvider(privateKey, rpcUrl)
const web3 = new Web3(provider)

rhinofi = await RhinofiClientFactory(web3)

For more, see examples and their README.

Configuration

It's possible to overwrite values on the configuration on a per instance basis.

The default configuration can be overwritten with an optional parameter userConf when calling the RhinofiClientFactory function.

Parameters

For instance:

  rhinofi = await RhinofiClientFactory(web3, {
    api: 'https://your-custom-api-address',
    gasStationApiKey: 'a1b2c3...'
  })

The configuration is also merged with the configuration provided by the exchange on the HTTP endpoint /v1/trading/r/getConf which at the moment looks similar to this:

{
   "RhinofiClientFactory":{
      "defaultFeeRate":0.002,
      "deversifiAddress":"0xaf8ae6955d07776ab690e565ba6fbc79b8de3a5d",
      "starkExContractAddress":"0x5d22045DAcEAB03B158031eCB7D9d06Fad24609b",
      "withdrawalBalanceReaderContractAddress":"0x650ca2dca7e2e2c8be3bb84e0a39dd77891d4d1e",
      "exchangeSymbols":[
         "ETH:USDT",
         "MKR:ETH",
         "MKR:USDT"
      ],
      "tempStarkVaultId":1,
      "minDepositUSDT":1
   },
   "tokenRegistry":{
      "ETH":{
         "decimals":18,
         "quantization":10000000000,
         "minOrderSize":0.05,
         "starkTokenId":"0xb333e3142fe16b78628f19bb15afddaef437e72d6d7f5c6c20c6801a27fba6"
      },
      "MKR":{
         "decimals":18,
         "quantization":10000000000,
         "minOrderSize":0.025,
         "tokenAddressPerChain": {
            "ETHEREUM": "0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2"
         },
         "starkTokenId":"0x1a4af39d27ce2e3445ed084809e5bc36d03918df04b7e2b6ee3c769a9892600"
      }
   }
}

The complete compiled configuration is accessible through rhinofi.config, for instance:

const rhinofi = await RhinofiClientFactory()

const config = rhinofi.config

API Authentication

Authentication to make all authenticated requests is done by signing a nonce using an Ethereum private key. Signing is handled by the Rhino.fi client library if the account is available and unlocked or if the web3 provider supports it. Otherwise the message and signature need to be prepared separately.

Parameters
const nonce = (Date.now() / 1000).toString()
const signature = await rhinofi.sign(nonce)

Registering

This method is used to register a stark public key that corresponds to an Ethereum public address or a trading key.

Parameters

Returns Promise<UserConfigResponse>

Approving Tokens

When depositing an ERC20 Ethereum-based token for the first time from a specific account, you are required to approve it to interact with the smart contracts, this is not required for ETH.

Parameters

Returns Promise<PromiEvent>

const token = 'ETH'
await rhinofi.contract.approve(token)

This step does not need to be repeated again, and subsequently you are required only to call the deposit function.

Depositing tokens

This method is used to deposit the tokens to the smart contract and submit a signed notification of a new deposit made to the API.

Parameters

Returns Promise<{...PromiEvent, ...DepositResponse}>

const token = 'ETH'
const amount = 100

const deposit = await rhinofi.deposit(token, amount, tradingKey)

Placing an order

This authenticated endpoint is used to place an order.

Parameters

Returns Promise<SubmitOrderResponse>

const symbol = 'NEC:ETH'
const amount = -15
const price = 0.0025

const orderId = await rhinofi.submitOrder(symbol, amount, price)

Getting Orders

This method allows you to get a specific order by orderId or cid.

Parameters

Returns Promise<CancelOrderResponse>

const orderID = '123'
const customID = 'cid-123'

const order = await rhinofi.getOrder({ orderId: orderID })
// or
const order = await rhinofi.getOrder({ cid: customID })

Cancelling Orders

This method allows you to cancel a specific order by orderId or cid.

Parameters

Returns Promise<CancelOrderResponse>

const orderID = '123'
const customID = 'cid-123'

const response = await rhinofi.cancelOrder({ orderId: orderID })
// or
const response = await rhinofi.cancelOrder({ cid: customID })

Withdrawing tokens

Requesting a withdrawal

This method submits a request for a new withdrawal.

Parameters

Returns Promise<WithdrawResponse>

const token = 'ETH'
const amount = 100
const withdrawal = await await rhinofi.transferAndWithdraw({
  recipientEthAddress: address,
  token,
  amount
})

Withdraw on chain

This method calls the contract and withdraws the tokens to your wallet

Parameters

Returns Promise<{ transactionHash: string }>

const token = 'ETH'
const txHash = await rhinofi.withdrawOnchain(token, recipientEthAddress)

Authenticated data endpoints

If you already have an unlocked wallet available to web3 to use for signing, you can simply get data from the API as follows:

Note: You should reuse the nonce and signature and pass them to these methods while they are valid to avoid unnecessary signing

Parameters
// Get all open orders
const openOrders = await rhinofi.getOrders()

// Get all historical orders
const historicalOrders = await rhinofi.getOrdersHist()

// Get specific order
const id = "123"
const order = await rhinofi.getOrder(id)

// Get exchange balances
const balance = await rhinofi.getBalance()

// Get deposits
const deposits = await rhinofi.getDeposits()

// Get withdrawals
const withdrawals = await rhinofi.getWithdrawals()

// Get user config
const userConfig = await rhinofi.getUserConfig()

More Examples

Aside from these examples, there are complete examples in the examples folder

Gas Price

You can setup a default custom gas price by setting up the 'defaultGasPrice' property

const rhinofi = await RhinofiClientFactory()

rhinofi.set('defaultGasPrice', web3.utils.toWei('2', 'gwei'))

RhinofiClientFactory calls https://ethgasstation.info API to get the current gas prices and calculate a safe gas price for Ethereum transactions. Access to the ETH Gas Station API is free, but rate limited if you are not using an API key. If a ETH Gas Station API key is not provided then a recommended gas price is used which is available in rhinofi.recommendedGasPrices.

To configure your api key with rhinofi client please pass this as a userConf parameter when initialising RhinofiClientFactory:

javascript
  rhinofi = await RhinofiClientFactory(web3, {
    gasStationApiKey: 'a1b2c3...'
  })

or by setting the 'gasStationApiKey' property:


rhinofi.set('gasStationApiKey', 'a1b2c3...')

Custom order ID

Property cid can be used to give order custom identificator for further tracking.

const symbol = 'ETH:USDT'
const amount = -1.42
const price = 3000

const customOrderID = `short-` + Math.random().toString(36).substring(7)

await rhinofi.submitOrder({
  symbol,
  amount,
  price,
  cid: customOrderID,
})

// ...
// Later we can use `cid` to get order
const order = await rhinofi.getOrder({cid: customOrderID})

// or cancel it
await rhinofi.cancelOrder({cid: customOrderID})

Troubleshooting

A list of error codes returned by the API and reasons are available here. Some more detailed explanations can also be found in the API Documentation.

If you have suggestions to improve this guide or any of the available documentation, please raise an issue on Github, or email feedback@rhino.fi.

Links

Developing

Setup

  1. install nix
  2. enter nix shell:
$ nix-shell
  1. install js deps
$ yarn

Implementing a new feature and Testing

TODO

License

MIT