Kriya Tech: Why we chose Sui
Our experience building a fully on-chain orderbook
Developers and traders forever have debated whether an orderbook is better for trading or an AMM. Turns out, like most other things, it depends on context. Within Efficacy Labs’ whole suite of DeFi products, KriyaDEX is meant to be the platform where degen traders and institutions both come to trade margined derivative products (like perpetuals, options, dated futures etc.). The important thing to note about derivatives is:
These assets are volatile
These are leveraged products: users might loose more than they bet
In this specific context, we felt an orderbook might be more appropriate. If built with sufficiently low latency, it is the most flexible and granular form of price discovery which is almost a necessity when trading severely uncorrelated assets with size.
So from a technical perspective, our goals were now:
Build a low-latency order-matching engine
Build a scalable margin engine (Collateral management system)
The solvency of this whole system is dependent on the consistency of communication between the margin engine and the orderbook. This brings us to the first reason why we picked Sui.
Flexible asset ownership with Move
Sui’s version of move adds many superior capabilities when handling ‘escrowed’ or borrowed assets. On EVM chains, assets are represented as entries in a
<owner_address> → <asset_byte_code> hashMap, stored in the contract’s storage. These assets cannot cross the contract boundary and be used as parameters in other contracts.
Move assets are represented as typed objects in Sui’s global storage and can flow across contract boundaries. they can be passed in functions as arguments, returned from functions & can be stored inside other assets. This makes it highly composable and secure.
One can program levels of custody of assets with a few lines of move code.
With derivative DEXs, architecture isn’t similar to a one-time asset swap. Rather, derivative protocols need partial custody of user assets. Ideally, the user should be able to withdraw funds in a permissionless way but shouldn’t be able to incur a loss greater than their deposit.
For instance, this is what the KriyaDEX margin wallet architecture looks like:
Users call the deposit function of our smart contract. A field tracking user balance is updated and the actual coins are stored securely in a combined pool.
How much a user can withdraw from the pool, and how much of it is locked for trading are tracked in separate fields. These fields are updated every time a user deposits/withdraws funds or trades on the orderbook.
Structuring it this way, users can withdraw free capital even if the orderbook faces downtime or experiences a hack.
Given these are fields of a smart contract (and not actual user assets) they can be conveniently and deterministically altered by the protocol in special cases (ie liquidations)
For complete transparency on access control, insurance_fund and fee_treasury are also labeled fields with on-chain conditions for the approved use of funds collected in them
Since EVM assets are stored inside hashMap in the contract’s storage, validators cannot know which assets(storage) the transaction is intended to change. Hence, all the transactions can be processed only sequentially(even when the txns do not touch the same asset). With Move & Sui’s global storage, validators & consensus protocol have this information available before submitting the txn which enables parallel processing capabilities. This way, for example, someone with no active positions can seamlessly and cheaply withdraw their funds even when the orderbooks might be choked with traffic and high gas prices.
The next piece of our puzzle was building the orderbook. Orderbooks are accurate because they are the most iterative form of price discovery. A common price is agreed upon by bidders and askers quoting and canceling order intents at high frequencies. This makes them very gas intensive.
Gas optimization via dynamic fields
Sui allows the dynamic addition of fields & properties to objects at run-time & not fixed at publish. This makes objects infinitely scalable theoretically while users pay gas for only the fields accessed in the transaction.
Objects wrapped in a dynamic field are indexed independently in Sui storage & hence can be viewed by the explorers.
This is KriyaDEX’s Orderbook data structure:
We’ve implemented a heap & a linked list, which are completely indexed as dynamic fields inside the parent object with each node being mapped as a field. This helps to dynamically scale the heap object post publish & pay for gas only for the nodes traversed.
The above heap & linked list data structures are combined to store orders sorted by price & time. Each tick price represents an entry in the heap as key, while the orders at that price are stored in the linked list as value
(”tick_size” → LinkedList(orders))
This hybrid approach substantially reduces gas while only loading dynamic field object locations that the transaction will touch while matching. When compared with conventional vector implementations of heap & linked list, we were able to slash max gas price used by a market order on our CLOB by 5 times!
14k MIST → 3.1k MIST on devnet
Mostly, orderbooks also face issues of inconsistently high traffic during peak volatile hours. This makes gas an even more necessary problem to solve. On the Sui chain, gas prices are agreed upon by the validators at the beginning of each epoch. This keeps a check on gas price surges when the network is unusually busy.
These custody and gas optimizations combined with the Narwhal mempool + Bullshark DAG consensus of Sui yielded us some really promising performance numbers on devnet.
No of concurrent users: 2000
Market/Limit order ratio: 1:1
TPS: 90 txns/sec
Avg latency: 9 secs
Max gas: 3100 MIST
Avg gas: 1500 MIST
You’ll be hearing more from the tech team 👩💻 as we keep experimenting. For now, we’re looking to brutally test this architecture in Sui’s testnet epoch 3 and explore options of open-sourcing the matching engine as a move package for the community🙂
Make sure to try out our perpetuals DEX here: perp.kriya.finance 🧮
Please do share feedback on #tech-discussions on our discord
We’re looking to partner with more wallet providers, oracle partners, and market makers as we approach mainnet. If this interests you, do raise a ticket on our discord
DM us on twitter: @KriyaDEX
Ain’t that too fast for a fully on-chain orderbook? 🤯