The first element in the off-chain state of StarkEx is the Balances tree. The Balances tree is a Merkle Tree, whose leaves are StarkEx Vaults. Each vault contains a single Stark key, which identifies the user in the off-chain state. Other elements in the vault are defined according to the business logic.
The vault contains the following fields:
starkKey- the public Stark key of the vault’s owner. Transfers and trades from this vault must be signed with this key.
assetId- The asset ID for the asset that this vault contains (only one type per vault).
amount- The amount, quantized, that this vault contains.
An empty vault has a balance of 0.
An empty vault has no owner, that is, no public Stark key is assigned to the vault. So you can assign it an owner whether it has not yet been used, or it was in use and is now empty.
Every vault contains one asset type. So limit orders have two vaults as input, as follows:
The Orders tree prevents the operator from replaying transactions in the system. To prevent this attack, the Orders tree has the following properties:
A leaf in the Orders tree represents an order that StarkEx executed.
Each leaf has an ID and a value. The ID is a hash of a signed transaction request. The value is the amount of an order that has already been fulfilled. For example, if Alice signed a transfer request for 1000 USDC, with a hash value
0xdeadbeef, StarkEx stores 1000 quantized USDC in leaf index
0xdeadbeefin the Orders tree.
If the operator tries to resubmit Alice’s order, then when validating a transfer, StarkEx checks that this transfer was not previously executed by checking that the value in leaf number
0xdeadbeefis zero. Because the value is not zero, the on-chain Cairo Verifier cannot accept this order.
StarkEx uses the Orders tree to keep track of assets that were previously minted.
The Orders tree is a Patricia tree, which is easier to update and search than a Merkle tree.
The Orders tree also supports partial fulfillment of limit orders.
On trades, the operator must provide the original user’s limit order, as well as the corresponding amount that is transferred in this settlement. StarkEx enforces that the value saved in the Orders tree, plus the new transferred amount, is still less than the amount that the user signed on in the original limit order.
The StarkEx smart contract stores the root of the Balances tree and the root of the Orders tree, which are a commitment to the off-chain state. The off-chain state is the tuple of roots. The state is updated when the contract receives a new proof that there exists a valid sequence of transactions that, when executed, changes the current state to a new state.