This article continues on the topic started in Explaining DMEX — Part 1.
In the previous article we have established the 3 main components of the DMEX trading mechanism:
` — Futures Contract
` — Position
These 3 components form a nested tree, where Futures Contracts are created under Assets and Positions are created under Futures Contracts. A Futures Contract cannot be created without having an Asset created first, and a position cannot be created without having a Futures Contract created first.
When a user creates an order, the traded “thing” is the futures contract. The position holds the amount of the futures contract traded as a result of the user order.
DMEX is comprised of three smart contracts running on the Ethereum Blockchain:
- Custody Contract — this contract holds users funds and balance details (reserved and available balances). Link to GitHub.
- Trading Contract — performs the trades between users and holds the Assets, Futures Contract, Positions, and order fills. Link to GitHub.
- Oracle Contract — is the interface to the Provable.xyz decentralized Oracle service that brings in the settlement price for the futures contract when it expires or the price limit is breached. Link to GitHub.
In order to trade, the user first needs to deposit funds to the Custody contract. All withdrawals are performed from the Custody contract as well.
Once a user places an order and the order is matched with an order from another user, the DMEX servers will send both orders to the Trading contract that will create 2 opposite positions, one long and one short.
Once the contract expires or the price limit is breached, the DMEX server calls the closeFuturesContract() function on the Oracle Contract, providing the futuresContactHash as a parameter. This function verifies if the Futures Contract is not already closed and requests the price from the Oracle.
In reality, the Oracle is asked to return the output of the priceUrl (discussed in Part 1), the Oracle is not aware of the sort of information it is providing, it just returns the contents of the URL along with the proof that the snapshot was taken by their “black box” machine. The contents of the URL are returned through a callback function that can only be called by the Oracle.
When the price is received by the callback function, it checks if the price is outside the Futures Contract range, and if so it uses the Floor or Cap price as the Closing Price and sets the contract as closed.
Once the contract is closed, the DMEX server initiates the settlement of the positions on the closed Futures Contract through batchSettlePositions() function on the Trading Contract. Note that this step can be performed by the user directly, it is performed by DMEX for convenience only.