🧱Typescript SDK
We've open sourced our SDK for Devnet and Mainnet. Our SDK is a typescript library that can be used to interact with our Zeta program smart contract.
This page will go over the basics - loading up everything, seeing exchange state, placing/cancelling orders as well as some advanced functionality such as callbacks and events. For extra information, check out:
Install
Devnet variables
Key | Value |
---|---|
NETWORK_URL | https://api.devnet.solana.com |
PROGRAM_ID | BG3oRikW8d16YjUEmX3ZxHm9SiJzrGtMhsSR8aCw1Cd7 |
SERVER_URL | https://dex-devnet-webserver-ecs.zeta.markets |
Mainnet variables
Key | Value |
---|---|
NETWORK_URL | https://api.mainnet-beta.solana.com |
PROGRAM_ID | ZETAxsqBRek56DhiGXrn75yj2NHU3aYUnxvHXpkf3aD |
PROGRAM_ID is subject to change based on redeployments.
Native numbers are represented with BN to the precision of 6 d.p as u64 integers in the smart contract code.
They will need to be divided by 10^6 to get the decimal value.
Use our helper functions in src/utils.ts
to convert.
Setting up a wallet
Before we start writing any code, we need a fresh Solana wallet - skip this if you already have your own wallet.
.env file
At this point there will be .env file with your freshly created private key. Open it up with your favourite text editor and add the following two lines:
Note that the default Solana RPC will probably rate-limit you. Now's a good time to find a better one - for starters check out Runnode, Alchemy or RPCPool.
Basic setup boilerplate
Now that you're set up, we can start loading the Zeta exchange! Start with the following code, which will set up all necessary connections, airdrop you some SOL + USDC (devnet only) and load the exchange.
User margin accounts
A user's state is represented by a CrossMarginAccount
in the Zeta program. This is one account for all assets.
It stores all the state related to a user's balance, open orders and positions.
Creation is baked into the deposit
function if you don't have one already.
Structure
The details are abstracted away into client.getOrders(asset)
and client.getPositions(asset)
in the SDK.
Basic script setup to place a trade and view positions
For examples sake, we want to see the orderbook for SOL perps
Placing an order.
Placing an order on a new market will create an OpenOrders
account. This is handled by the SDK.
The minimum price is $0.0001.
The minimum trade tick size is 0.001.
See client order.
Now that our order is placed we should see it on the orderbook. Either check in the SDK or navigate to https://devnet.zeta.markets/ to see it visually.
Place bid order in cross to get a position
Let's trade! Instead of just placing a resting order, send a bid order with a higher price to cross the orderbook and execute a trade.
We have a position of 1, with cost of trades 9530000 / 10^6 = $19.53.
Cancel order.
Cancel all orders.
See src/cross-client.ts
for full functionality.
Check market mark price
This is the price that we receive from on-chain Oracles.
Calculate user margin account state
At any point you can view your account state without having to dig through the account definitions yourself, using the riskCalculator
.
Priority Fees
Additional priority fees can be set to maximise your transaction's chance of success. The units are microlamports per Compute Unit.
Versioned Transactions
Can't fit all the instructions you want into a single transaction? Try using Address Lookup Tables (ALTs)! By setting lutAccs = utils.getZetaLutArr()
when calling utils.processTransaction
, you'll utilise features from Solana's Versioned Transactions to drastically minimise the accounts you pass in, increasing how many instructions you can sandwich together.
A full Versioned Transactions example is available in the examples subpage.
Zeta market data
Zeta market data is available through Exchange.getZetaGroupMarkets(asset)
, which simplifies the data in Exchange.getZetaGroup(asset)
to be more easily understood.
Markets are indexed, and due to a legacy with options+futures, perps are index 137.
See src/markets.ts
to see full functionality.
Viewing perp funding information
Perp markets have a unique mechanic - funding rates (Gitbook). These values are stored in the Pricing account.
Viewing oracle price
The Exchange
object creates an oracle subscription to any assets (eg SOL/USD or BTC/USD) on load. You can access the latest oracle prices like so:
See callbacks to update state live.
Callbacks and state tracking
Due to the number of changing states in the Zeta program, the SDK makes use of Solana websockets for users to receive callbacks when accounts are polled and/or changed.
There are two categories of callbacks, one relating to user state and the other to non-user based state (program state).
The callback function is passed in either
Exchange.load
- for non user events.CrossClient.load
- for user events.
You can see these EventType
in src/events.ts
.
NOTE: Some callbacks are done on poll so don't always reflect a change in state.
Event | Type | Meaning | Change |
---|---|---|---|
EXCHANGE | Program | Exchange polling update | Exchange polling |
PRICING | Program | When pricing is updated (mark prices) | Exchange's pricing or Exchange.riskCalculator |
ORDERBOOK | Program | When an orderbook poll occurs. | Exchange.markets |
ORACLE | Pyth oracle | Pyth price update. | Exchange.oracle |
CLOCK | Solana clock | Solana clock account change. | Exchange.clockTimestamp |
TRADEV3 | User | On user trade event. | client.account |
ORDERCOMPLETEEVENT | User | User order is fully filled or cancelled. | client.account |
USER | User | When the user's crossMarginAccount changes, which can occur on inserts, cancels, trades, withdrawals, deposits, settlement, liquidation, force cancellations | client.account |
These callbacks should eliminate the need to poll for most accounts, unless you need certainty on the state, in which case there are polling functions available in Exchange
and CrossClient
.
asset
in each callback can potentially be null
if the callback applies to all assets, such as clock callbacks which are common.
Event data
The function definition of a callback is (asset: assets.Asset, event: EventType, data: any) => void
Only ORACLE
and ORDERBOOK
events have data in them.
ORACLE:
ORDERBOOK:
After receiving an orderbook update, you can assume Exchange.getOrderbook(asset)
is the latest state.
Native polling in SDK
There is polling natively built into the SDK Exchange
and CrossClient
objects since state relies quite heavily on websockets.
This was to ensure that:
SDK program state would correct itself on websocket issues.
There was a mechanism for users to poll state on some defined interval (and get a callback when it happened, see below).
Exchange polling
Exchange
has a default poll interval of constants.DEFAULT_EXCHANGE_POLL_INTERVAL
(set to 30 seconds).
You can change this via setting Exchange.pollInterval
.
This will poll Pricing
and zeta State
accounts.
Client polling and throttle
CrossClient
has a default poll interval of constants.DEFAULT_CLIENT_POLL_INTERVAL
(set to 20 seconds).
You can change this via client.setPollInterval()
.
This is almost how often the SDK will call await client.updateState()
, which is the manual way of polling user state.
There is a timer that on default fires every 2 seconds, checking the last poll timestamp. If time greater than client.pollInterval has elapsed or there is a pending update, it will poll.
Pending update refers to a margin account websocket change callback. (The SDK subscribes to user CrossMarginAccount
on CrossClient.load
.)
This will do multiple things (client.updateState()
):
Fetch user margin account (
client.account
).Update user orders (this will poll the market orderbook for each market that the user has a non zero position or open orders in -
client.getOrders(asset)
).Update user positions (
client.getPositions(asset)
).
This timer can be modified via client.setPolling(intervalSeconds)
.
Tying into this, the motivation behind this complexity is that if a user is asynchronously placing and cancelling orders across multiple markets, you may receive multiple margin account callbacks across consecutive slots.
If each call back polls relevant markets for the latest user order state (2 polls per market), you can easily hit rate limits.
If throttle
is set to true
, in CrossClient.load
, then this timer allows users to batch client polling to the next timer interval (i.e. optimistically, 5 consecutive slot updates will only trigger 1 poll).
Alternatively, throttle
can be set to false
, and client.updateState
will be called on every margin account change and ensure you have the latest state at all times.
Shutting down
When you want to shut down or restart the client, call this to disconnect the respective websockets.
Ready to start trading?
Last updated