Get Started with MakerDAO CDPs and Dai.js

Exploring decentralised finance with MakerDAO CDPs and Dai.js Javascript library

Ross Bulat
Feb 22 · 11 min read

MakerDAO: The Emerging Winner of Decentralised Open Finance

The concept of an I.O.U has been around since the early days of civilisation, allowing us to gain leverage from another party and in exchange owe them some sort of value — the process of which may last a period of time. Most of us today will be familiar with this concept in the form of bank loans, mortgages, student finance, seed funding or investment rounds — but these I.O.Us all have something in common: they rely on a centralised monetary system. Not only this, a trusted third party entity must be introduced to manage the I.O.U and ensure the agreement is enforced and maintained on both sides.

And this is for good reason. The centralised monetary system we use today allows us to scale the concept of an I.O.U, to bring it to corporations as well as the individual for a multitude of assets — both tangible and intangible — while maintaining an acceptable level of trust and enforcement of the I.O.U contract.

Considering 2 billion people on the planet are still “unbanked” with no real means for them to gain access to financial services, the prospect of an open financial system is a big deal. Up until now there have not been contenders for replacing such a system on a global scale. That is until the advent of the blockchain.

What we are now witnessing is the concept of the I.O.U being implemented in a decentralised manor, on the blockchain, whereby the trusted entity to manage them is the blockchain and the smart contracts created to automate the lending process.

MakerDAO provides us with such a solution, allowing anyone with an Ethereum balance to open a form of debt called a CDP, or a Collateralised Debt Position.

MakerDAO and the CDP

Maker has been around since the early days of Ethereum with the project starting back in 2016. Their concept of a CDP is now one the most thoroughly tried and tested methods of decentralised lending, and the most widely adopted means of doing so today. A streamlined CDP Portal was launched by the company in November 2018 — a web app anyone can use to set up and manage CDPs. This has greatly improved the adoption rates and ease of use of the system.

We will go through the CDP creation process and terminology in relation to MakerDAO in this article, as well as the use cases that can be applied today.

Open Finance with Dai.js

We will also take a look at Dai.js, a Javascript library allowing us to integrate the Maker CDP process (as well as system stats, events, exchange prices, and more) into our own apps. Gone are the days where banks need to be relied upon to set up and manage a debt position.

Now, an essential part of the CDP process is the DAI stablecoin; we effectively put ETH up as collateral in exchange for DAI — a token that is pegged against USD and maintained in a reliable manor by governance protocols — which in turn gives you the freedom to exchange your DAI into another Cryptocurrency, or into Fiat.

But is ETH our only option as our means of collateral? Currently it is — but Maker are intending to expand the system to become a multi-collateral platform in the near future.

Before jumping into Dai.js, let’s overview the CDP process and characteristics of the system to fully understand its capabilities, and also its drawbacks.

MakerDAO CDP Process

The CDP Portal can be accessed on cdp.makerdao.com:

The CDP Portal is a modern app with some impressive integration with web3 and blockchain state, and also provides some friendly usage instructions on the homepage that are well worth reading over.

The portal is able to connect to browser based wallets such as MetaMask, as well as hardware wallets including the Trezor and Ledger Nano wallets. Connecting to a wallet will open the CDP management UI.

CDP: Lock up ETH in exchange for DAI

The general idea behind a CDP is that DAI stablecoin is minted in response to locking up ETH, which will only become available again upon you paying back the DAI generated.

There is no fixed time limit for paying back your generated DAI, but you are charged (at the time of last update) a 7% stability fee on an annual basis until your position is closed. This 7% stability fee can be paid in DAI, or paid via the MKR token — another token in the MakerDAO ecosystem that plays another important role in the governance of the system. MKR is the number 16 Crypto in terms of market cap at writing time, highlighting the popularity of the platform.

Note: If you are interested in learning more about the inner workings of MakerDAO governance, the whitepaper is a great place to start. The MKR Token Governance section explains in more detail how the MKR token is used to incentivise system maintainers to keep doing a good job — a lot of which are automated processes. The rules around choosing maintainers are also governed by more rules, or internal governance variables, restricting what is humanly possible in order to manipulate the system.

In addition to this leeway, you are also free to top-up your locked up ETH, at any time, to either boost your collateralized value to avoid liquidation (more on this next), or to be able to generate more DAI.

The value of DAI available to take out is always less than the value of ETH you lock up; this is reflected in the CDP Portal UI, providing handy metrics as you configure the CDP.

Collateralization Ratio

The consequences of your locked-up ETH value falling under a certain threshold is liquidation; the process of your CDP closing and the system charging you a 13% fee of your deposited funds along the way. The terminology Maker use for this threshold is the Collateralization Ratio, the value of which is currently at 150%.

Therefore, the ETH value I am collateralising must be worth at least 150% of the DAI I am taking out, at all times.

This is clearly displayed in the CDP Portal, where the ratio updates in real-time as you update your desired DAI amount to be generated. We also have the liquidation price of ETH in USD handy to give further insights into the position:

Configuring a CDP using the Maker CDP Portal

In the above example I am collateralizing 0.05 ETH in exchange for 1 DAI. The collateralization ratio of my ETH to DAI at this stage is at 725.049%, way above the 150% liquidation threshold.

Furthermore, I know that ETH will need to fall to $30 USD for this position to be liquidated — I can refer to historical ETH price charts to determine that it is unlikely that ETH will fall to this value; there was a price crash from ~$410 to ~$115 in mid 2017, and a more severe crash from ~$1300 to a low of ~$86 that took place from January 2018 to December 2018. But ultimately it is your decision on what collateralization ratio you choose, and the level of risk you are willing to accept.

CDP Portal will indeed flag a warning when it deems a collateralization ratio risky, prompting you to amend the DAI amount.

ETH to PETH

At this stage it is important to mention that your deposited ETH will actually be converted into a token named Pooled ETH, or PETH. PETH represents a percentage share of the total ETH deposited into the Maker system. In the event there is a severe market crash leading to CDP liquidations, PETH will be sold in order to recapitalise the DAI taken out.

Pooled Ether is a temporary solution for single-collateral Dai, with plans to phase out this mechanism when multi-collateral Dai is introduced in Q1- Q2 2019.

The generation of PETH happens behind the scenes. In fact, the entire process of setting up a CDP position involves a 7 step process. Accepting the terms of service and submitting the CDP will start the creation process, which can take a few minutes to complete.

CDP Portal Creating the CDP, waiting for blockchain transactions to process

Once created, the CDP Portal dashboard will update and display the relevant information to the CDP, including the history of CDP activity.

Below is an overview of my CDP in the portal, where I have deposited 0.04 ETH and generated 2 DAI, which yielded a 290.020% collateralization ratio:

In this example I can still generate up to 0.1855 more DAI without the collateralization ratio dropping below 150% — but doing so will decrease the ratio and consequently increase liquidation risk.

On the other side of the coin I also have 0.019 ETH available to withdraw, as this amount is not currently being collateralized with DAI. Again, withdrawing ETH value from my CDP will decrease the collateralization ratio and increase liquidation risk.

Closing and transferring ownership

In the top right corner of the Portal we also have options to close the CDP, allowing us to pay back all owed DAI and unlocking our PETH back into native ETH currency. Interestingly, we can also transfer ownership of the CDP to another Ethereum address, opening up the possibility of buying and selling CDPs.

The CDP Portal does indeed provide an easy-to-use app to take advantage of the Dai infrastructure on the blockchain; prior to its release the community were using third party tools as a means to interact with the smart contracts providing the backbone of the MakerDAO system. But we are not limited to these means alone; you could indeed create your own Portal, along with other tools to automate CDPs, with Dai.js.


Dai.js Introduction

The Dai.js library, a promise-based Javascript wrapper library for interacting with the system, gives us the ability to integrate everything we have explored above, into our own apps. The project can be found here on Github, and Maker have provided a comprehensive API Reference on their website to ease integration.

Instantiating a Maker Object

The API consists of a range of services. In order to set up a CDP position, a simple workflow is required, starting by instanitating a Maker object. This instantiation process also consists of connecting to an Ethereum client, where we have 3 options:

  • http based, with a service such as Infura or private Ethereum node to connect to over HTTP.
  • browser based, relying on a plugin such as MetaMask to get access to the Ethereum network. This is the most realistic method for scaling blockchain communication, by giving the end user responsibility to provide the means to do so.
  • Or over a local test network running on your machine, such as Ganache. This is very handy during development stages.

The Maker services documentation then prompts us to run an authenticate() method on the Maker object, which ensures all services are initialised and connected to the required APIs in a secure manor.

Once authenticated we can then create a new CDP or retreive an existing CDP with newCdp() and getCdp(<cdp_id>) respectively. A cdp object is returned:

const cdp = await maker.openCdp();

A very simple workflow here, allowing us to firstly instantiate a CDP object before doing any work on it, like depositing ETH, generating DAI, paying back or closing the CDP. All this is done with thecdp object returned from one of the above 2 methods.

From here, the CDP section of the API reference breaks down what we have at our disposal for interacting with a CDP.

The API itself is elegant and simple to understand. One liners of code are all that’s needed to perform the majority of important tasks. Here are some examples:

// lock 100 ETH into a CDP
let result = await cdp.lockEth(100, ETH);
// take some DAI from my CDP position
let result = await cdp.drawDai(100, DAI);
// repay some DAI
let result = await cdp.wipeDai(100, DAI);
// free some available PETH from my CDP
let result = await cdp.freePeth(100, PETH);
// transfer ownership of CDP to another address
let result = await cdp.give('0x0...');

Consistently keeping users up to date with their positions is vital and will install confidence in your app. The getLiquidationPrice() and getCollateralizationRatio() methods provide you with these vital statistics.

Other Dai.js Services

The CDP methods are indeed the bulk of Dai.js, but there are other useful services available that I will briefly document here:

  • Price service — Easily retrieve prices from Maker.
  • ETH CDP services — Easily retrieve CDP related stats.
  • Exchange service — This exchange service allows the buying and selling of DAI, MKR, and other tokens. The default OasisExchangeService implementation uses the OasisDEX OTC market for this service.
  • System status API — Retrieve system level stats.
  • Events: Allowing you to track blockchain events as they happen.
  • Transactions: Allowing you to track transaction status and propagation on the blockchain with a built in Transaction Manager.
  • Multiple Accounts: Manage multiple CDPs in a linear manor by using the maker.addAccount() and maker.switchAccount() methods.

WETH — Wrapped Ethereum

You may have noticed an additional WETH token being mentioned in the Dai.js documentation.

The CDP section provides a getWethToPethRatio() method, and we also have a price/WETH_PETH Event to listen out for.

WETH is an ERC-20 token representation of native ETH that allows smart contracts to exchange the two. The website weth.io provides a great explanation of WETH.

When creating a CDP with Maker, your ETH has to be converted into WETH, which is then converted into PETH. Finally, your Pooled Ethereum is locked as collateral and your CDP becomes active.

Summary

MakerDAO is becoming an increasingly viable solution to open finance, putting governance of CDPs on the blockchain with an incentive model for system maintainers to effectively and reliably maintain the system.

At the time of writing, 1.97% of the total supply of Ethereum is locked into DAI CDPs, equating to around $297 million. Keep track of these figures and other vital platform statistics at a dedicated webpage, at MKR Tools.

Dai.js is still in it’s early stages of development. The NPMJS statistics show that the package is not currently being over-utilised, but it is my firm belief that integrations will increase as the platform evolves and the Cryptocurrency market in general recovers from the prolonged bear market.

The community are discussing ways to further leverage the MakerDAO system when it comes to supporting Multi-Collateral Dai — the system of which is now in active development.

Ecosystem considerations

Consider the Uniswap exchange, who provide liquidity tokens upon contributing to exchange pool funds, which would make a good candidate as a type of collateral with MakerDAO. The thought is that one could add to the Uniswap liquidity pools and enjoy the commissions made with their pool shares, while leveraging the liquidity tokens via a CDP, allowing the owner to convert liquidity tokens into a more suitable means of value.

The caveat here is that you will need to unlock your liquidity tokens (pay back your CDP in full) in order to withdraw your Uniswap pool funds. But nonetheless, this strategy would provide a way to utilise tokens that would otherwise have no usage beyond proving your stake in a Uniswap pool.

The Maker platform and DAI stablecoin are emerging as winners in the decentralised finance space, and now is a great time to jump into this ecosystem.

Talks and hands-on walkthroughs around blockchain and cryptocurrency.

Ross Bulat

Written by

The Block Journal
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade