Kauri Features

Browse Topics

Find trusted written and up to date knowledge based articles

Request

Request articles for the community

Contribute

Help the community by providing expert advice and help knowledge

Support (Late 2018)

Find trusted written and up to date knowledge based articles
logometamask
RECENT ARTICLES
From the MetaMask developer FAQ:
Using synchronous calls is both a technical limitation and a user experience issue. They block the user's interface. So using them is a bad practice, anyway. Think of this API restriction as a gift to your users.
Setting up a Web3 function to work asynchronously was pretty easy to figure out for a single call; but what about making multiple calls through Web3, that all need to be asynchronous, but also have dependencies on one another? An example would be calculating the ERC-20 token balance of an Ethereum address. To do this, you need to know both the balance of tokens at the address, but also the decimals value for that token to convert to the right units. JavaScript Promises are the natural solution here. They allow you to track the status of an asynchronous function, and perform actions after your multiple dependencies all resolve.
You can make an asynchronous requests by adding an error first callback to the Web3.js functions:
If we depend on multiple calls from the Ethereum blockchain to create a result, using JavaScript Promises is a good solution. They allow you to react to a success or a failure from an asynchronous function. Creating a promise from the error first callback function is pretty straightforward:
But we can actually make this process even simpler for multiple Web3 functions by creating a wrapper which both makes the function asynchronous, and turn it into a promise; basically automating what we would repeat above for each different Web3 function we call. Here is the wrapper from 0xcaff posted in StackExchange:
Now that we have a Promise, we can take advantage of the async/await pattern which simplifies not only the look, but also the behavior of Promises. Putting this all together, let's show how simple this makes getting the token balance for an ETH account. We convert our orginal "Hello World" getBalance into an ansychronous function, like so:
Not much shorter for a single function, but will certainly make things better the more separate functions we call. My next post will show the results of these smaller educational posts, and how we can put it together to create the project I have been hinting above: Getting the ERC-20 balance of an Ethereum Address. I hope this teaches you something! Again, this may be trivial to many, but was not so straightforward when I first started to tackling these problems. 
Please note: This is a very early stage feature, and the exact implementation may be subject to change! Do not use this method for production applications that you’re not able to update should the API change in the future!
There are a wide array of ways that Ethereum plans to scale, and it’s a favorite topic of blockchain fans, because the scalability of the blockchain is a hard technical limit on how useful it can become.
One of the easiest ways you can start scaling your application on Ethereum today, without waiting for any other technology to be available, is to construct mechanisms that allow users to sign state changes that aren’t always submitted to the blockchain, but can be if needed, like a state channel. To make a working state channel today, there’s no easier option than to take advantage of MetaMask’s new signedDataType model
Originally proposed in EIP 712 by Leonid Logvinov of 0x, and then implemented for MetaMask by Sergey Ukustov of Machimony. This new method makes it easier than ever to create applications involving user signatures that:
    sent structured data.
    Are human readable.
    Cannot impersonate Ethereum transactions.
    Are cheap to compute on-chain.
In this article, you’ll learn to show the MetaMask user something like this:
The API is simple, and will be even simpler once it has been deployed in new versions of EthJS and Web3.js. In the meanwhile, using it exposes you to the lowest-level API that MetaMask gives you: The Ethereum Provider.
You can find this code live online on github here.
As you can see, in this we:
    Imported the signature recovery library eth-sig-util
    Assembled parameters for the method.
    Retrieved the current user’s address from the web3 API.
    Asked the user to sign those parameters.
    Using the parameters and the signature, we were able to verify this signature came from their address (and only their address!).
Not only can you verify this data with JavaScript, you can also verify it in Solidity. Here is an example of verifying one of these signatures in Solidity. This can be useful for writing code for closing a state channel.
I hope this has been useful to you, let us know if you have any questions, and if you create any sample examples you’d like to share!

3 Articles

VIEW ALL
logouport
RECENT ARTICLES
Today we are opening initial testing for uPort AppManager. We will continue improving performance, documentation, and features over the coming weeks. Register your app today, and let us know what you think.
uPort AppManager is how developers create and manage identities for their applications. Application identities on Ethereum allow for more rich, secure, and meaningful relationships between your app and your users.
While uPort identities commonly represent people, we designed the technology to be extensible to also support identification of organizations, businesses, applications, and devices. Learn more about uPort Identities.
If you have ever developed applications on a centralized platform like Facebook, Apple AppStore, or Google PlayStore, you are familiar with registering your application. Platform operators make app registration a requirement so they can protect their users from malicious applications.
The uPort Application ID is a similar concept, except you are registering a decentralized application on a decentralized network. Since there is no platform operator (middleman) on Ethereum like there is on Facebook, it is your job to build a trusted relationship with your users. uPort AppManager helps you take the first step to building trust with your users.
Identify your app to your users
The most important thing you can do with an application identity is identify your app to your users during interactions on the uPort mobile app.
The first time a user interacts with your app on the uPort platform, the identity of your app will be added as a Connection within their mobile app. This creates a place for the user to find information that your app has shared with them, and view a history of interactions between you and them.
Issue Verifiable Credentials
Registering your application identity with AppManager allows you to issue Verifiable Credentials to your users. Credentials are how you attest to facts about a user, such as a verified email address, a GitHub username, or other aspects of their interaction with your app such as average account balance, number of transactions, etc.
User credentials are located in the About Me section of the uPort mobile app. Users can share their credentials with other identities, apps, and businesses. The uPort credential system allows apps and businesses to help bootstrap a person’s identity and reputation in a decentralized way, while allowing the user to maintain control.
Sending Push Notifications to the uPort Mobile App
I will go into this with more detail in another article in a couple of days, but you will also be able to send transactions and verifiable credentials directly to your users’ uPort mobile app using your Application Identity.
1. Go to App Manager
Go to https://appmanager.uport.me.
2. Login with your uport App
Press the Login button and scan the QR code.
3. Create app
Scan the QR code with the uPort app and authorize the transaction. This Transaction creates a completely new uPort Identity for your app.
4. Enter your application Details
Add your name, description, url, and upload a logo and banner image.
5. Publish app details
This brings up yet another QR code that you should scan on your uPort app. This creates the transaction registering your application details in the uPort registry on the blockchain.
6. Make a note of your application Credentials
You need the application address and the signing key in the app.
For a simple browser dapp, you can simply include the applications address as the clientId when creating your application using uport-connect.
This will identify your app and create unsigned requests to the user’s mobile app.
The real power of Apps registered with the AppManager is that you can create requests to the user for private information and create signed Verified Credentials to send back to your users.
Signing implies having a signing key which we create for you as part of creating your app. If that signing key is available to your user in their browser it would be very easy for them to create fake requests on your behalf.
That said, many developers are experimenting with use cases and creating proof of concepts of blockchain apps right now. In these cases early prototypes can still be created 100% in the browser.
This allows you to experiment with the full set of uPort features such as requesting private credentials, attesting credentials, etc.
For server side apps you should use the uport library directly. This is also used behind the scenes in uport-connect. The uport library creates and builds JWT objects that are used to communicate securely between your app and your user’s uPort mobile app.
The SimpleSigner creates a very simple implementation of a signing function. It would be fairly easy to create a similar function delegating signing to a HSM or other more secure implementation.
See the tutorial for the uPort library for how to use this in more details.

1 Articles

VIEW ALL
logoaragon
RECENT ARTICLES
Code in Github: aragon-apps/apps/voting
The Voting app is an entity that will execute a set of actions on other entities if token holders of a particular token decide to do so.
The Voting app is instantiated with a certain set of parameters that won’t be changeable for the lifetime of the app:
    Token: address of the MiniMe token whose holders have voting power proportional to their holdings.
    Support required: what % of the votes need to be positive for the vote to be executed. Making it 50% would be a 'simple democracy'.
    Minimum acceptance quorum: minimum % of all token supply that needs to approve in order for the voting to be executed.
    Voting time: number of seconds a vote will be opened, if not closed prematurely for outstanding support.
The only parameter that can be changed is 'Minimum acceptance quorum' for protecting against the case in which there is not enough voter turnout.
If you are a front end user you can skip this section, but if you are a developer and want to manipulate the Voting contract directly these are some notes you should consider.
The variables "Support required" and "Minimum acceptance quorum" are percentages that are expressed between zero and a maximum of 10^18 (that represents 100%). As a consequence, it's important to consider that 1% is actually represented by 10^16.
Moreover you should pass to the smart contract the actual number, not the scientific notation so: - 10^16   is 10000000000000000   (or 1 with 16 zeros) - 10^18 is 1000000000000000000 (or 1 with 18 zeros)
Here are a few percentages you can use
Creation
A new vote is initialized with:
    Execution script: EVM call script to be executed on vote approval, contains a series of addresses and calldata payloads that will be executed.
    Metadata: An arbitrary string that can be used to describe the voting.
The voting app conforms to the aragonOS Forwarder interface. A generic forward action will create a vote with the provided execution script and empty metadata.
When a vote is created a reference to the previous block number is saved as the snapshot block for the vote. The reason the previous block number is used is to avoid double voting in the same block the vote is created. Whenever a vote is casted, the MiniMeToken associated with the app is checked for the token balance of the voter at the snapshot block.
In order for casting a vote all these conditions must be met:
    Sender had a positive token balance in the token at the vote snapshot block.
    Vote hasn't expired.
    Vote hasn't been already executed.
If the casted vote is in support of the vote, the number of tokens held by the sender at the snapshot block will be added to the vote yea counter. In case a vote is against, it will add it to the nay counter.
After any casted votes, the contract checks whether a vote already has the complete support to be executed (even if everyone else voted against, the vote would still be approved), in that case the vote is executed and closed.
After a vote has expired time-wise (and no more votes are allowed), the result of the vote can be executed by anyone if it was approved. For a vote to be considered approved both conditions must be true:
    The percentage of yea out of the total number of votes is greater than or equal the 'Support required' global parameter.
    yea support is greater than or equal the 'Minimum acceptance quorum' global parameter.
At any time, the minimum acceptance quorum for the new votes can be modified.
Any open votes will maintain the value minimum acceptance quorum was when they were created.
Forwarding using the common interface executes a votingApp.newVote(...) action. ACL is checked for whether the sender has permissions to create a vote.
Code in Github: aragon-apps/apps/finance
The purpose of the Finance app is to be the central point for keeping track of income and expenses in an organization, as well as performing payments.
The Finance app is multi-token (plus ether). In order to remove the need of a trusted prices feed (oracle) for token exchange rate, every token is accounted on its own for budgeting and period financial statements.
Accounting period
Accounting periods are the equivalent of financial quarters in traditional organizations. Their length can be set depending on how the organization wants to use them.
For every accounting period, a balance (called token statement) for every transacted token is kept, this balance will be negative if more was spent than deposited and positive if otherwise.
Transactions
A transaction records an event in which assets were deposited or spent through the Finance app. Spend transactions are called 'outgoing transactions' and deposits 'incoming transactions'. Every transaction occurs in an accounting period and counts towards its token statement.
Transactions cannot be created directly, they are recorded as the result of an operation (either a payment being executed or a deposit made).
Payments
Payments are the construct used for spending using the Finance app. A payment can be created to happen only once or it can be a recurring payment that will be performed according to a certain time schedule.
If executing a payment succeeds, it creates an outgoing transaction with a reference to the payment.
Budgets
Budgets give the ability to limit how much units of a token can be spent per Accounting period. Budgets are set in a token per token basis. By default no token has a budget, which means unlimited spending is allowed.
Once a budget has been set for a token, the Finance app will only allow the budgeted amount of tokens to be spent for that period.
Initializing a Finance app requires the following parameters:
    Vault: a reference to a Vault instance that the Finance app will use for depositing and spending tokens. In order for it to work correctly, the Finance app must have permissions to transfer Vault's tokens.
    Ether token: address of the EtherToken instance used as ether.
    Accounting period duration: the initial duration for accounting periods. Can later be changed for future periods.
Deposits
Two deposit mechanisms are supported:
ERC20
After doing an ERC20 approval with the Finance app as spender, calling deposit(...) will create an incoming transaction saving the reference string.
ERC677
Performing a ERC677 transferAndCall(...) to the Finance app will also trigger a deposit (intercepted with the tokenFallBack). The data passed as payload to transferAndCall is used directly as the reference for the deposit.
Given that aragonOS' EtherToken implementation conforms to ERC677, depositing Ether to the Finance app can be done by wrapping the ether using etherToken.wrap() and then doing a transferAndCall(...) or using the shortcut wrapAndCall(...) which performs both actions.
Please note that this section is subject to change as the ERC677 discussion evolves.
Depending on the parameters a payment is created with, it can be an instant one time payment, a recurrent payment for payroll or a scheduled payment.
Creating payment
A payment is created with the following parameters:
    Token: Address of token for payment.
    Receiver: Address that will receive payment.
    Amount: units of token that are payed every time the payment is due.
    Initial payment time: timestamp for when the first payment is done.
    Interval: number of seconds that need to pass between payment transactions.
    Maximum repeats: maximum instances a payment can be executed.
In case a payment can already be executed on creation, it will be executed.
If a payment is created that won't be repeated ever again, and already was executed, only an outgoing transaction is recorded to save storage.
A payment can have a past initial payment time, which could cause many instances of the recurring payment to be executed at payment creation time.
Executing payment
Payment execution will transfer the recipient of a payment the amount due depending on the current time. A single execution can result in multiple transactions if the payment hasn't been executed in time. To prevent it going out of gas when many transfers are due, a maximum amount of transfers are performed per execution (multiple executions could be needed in some instances).
Payments can always be executed by its recipient, but there is also an additional role to the Finance app that allows another entity to execute the payment (recipient gets the funds in both instances).
For payments whose token is the known EtherToken, instead of doing a token transfer, it will directly transfer ether to the recipient.
A payment execution can fail in case the organization is out of budget for the payment token for that particular accounting period, or the organization doesn't have enough token balance.
Disabling payments
At any time, a payment can be disabled by an authorized entity. If a payment hasn't been fully executed until that time and it is disabled, the recipient won't be able to execute it until it is enabled again.
Setting duration
Sets the period duration for next periods. The current period duration cannot be modified.
Setting budget
Updates the budget of a token for accounting periods. Newly set budget is automatically enforced for the current period.
Removing budget
Removes budget for a token, allowing unlimited spending of that token in any period. Removing budget affects the current period.
Transitioning periods
All operations that can result in the creation of a transaction (creating a payment, executing a payment, performing a deposit) first check whether the accounting period needs to be transitioned (previous period has end time has passed) or it can be triggered manually by calling tryTransitionAccountingPeriod(...).
If many periods passed (last operation occurred two periods ago, but never transitioned), an empty period is created for every one of them.
To prevent the case in which the Finance app cannot perform any operation because it needs to transition too many accounting periods, causing any operation to go out of gas, transitioning periods has a parameter for how many periods it will transition. Automatic transitions will only perform 10 transitions maximum, and if more were needed the operation will fail. In case this lock occurs and periods cannot be automatically transitioned, multiple period transitions operations can be triggered manually to remove the lockup.
    Payments are allowed to be created but can make it go out of budget. It can cause a race to execute payments right at the beginning of an Accounting period.
    Payment executions do not expire. There is an attack vector in which by not executing a payment in some time, a budget can be impacted when executed. In case this is happening, payment can be executed by another allowed entity or it could be disabled.

7 Articles

VIEW ALL
logodharma
RECENT ARTICLES
Dharma is a protocol that enables decentralized origination, underwriting, issuance, and administration of tokenized debt assets in a highly generic and unopinionated construction. The protocol aims to build a common informational interface by which exchanges, brokerages, and traders can reasonably price a tokenized debt's default risk without having to rely on a singular centralized data broker. The Dharma debt issuance scheme leverages two classes of utility players that compete in distinct marketplaces for compensatory fees -- underwriters and relayers. The former are trusted originators and assessors of debtor default risk, and the latter facilitate the funding and issuance of debts in a trustless manner. Both can be empirically evaluated on historical asset performance, and, as such, markets have lucid signals with which to evaluate the default risk of tokenized debts attested to by any given underwriter or relayer. The Dharma debt issuance process only requires one on-chain transaction to execute, and is heavily inspired by the mechanics of the 0x Protocol.
Claim: An under-recognized advantage of blockchains is that they necessarily engender the creation of universal, permissionless standards for tokenized asset classes.
Token sale crowd-funds have, as of the time of this paper's writing, raised over $2B in 2017 alone. If this proves anything, it is that there is clearly an under-satisfied market demand for crowd-sale offerings that compensate retail investors with assets that have equity-like1 risk profiles. Equity crowd-funding mechanisms, however, pre-date the ICO phenomenon significantly -- so how does one explain the sudden burst of interest? If equity crowd-sales have been technically feasibly and in production for years, what aspect of the token sale ecosystem did Ethereum uniquely enable from a technological perspective? I posit that the answer is jarringly simple: the ERC20 token standard created the common rails on top of which a diverse ecosystem of secondary markets for tokens could be built in a permission-less and interoperable manner. Judged on investor liquidity alone, token crowd-sales are a step-function improvement over the status quo of equity fundraising.
In the existing financial system, however, the sum total capital raised in equity fundraises is paltry in comparison to its big brother in the world of debt fundraising. Debt markets, however, remain opaque and proprietary; executing a debt fundraise, be it in a public offering or to private investors, is as bespoke and inefficient as executing an equity fundraise is. Consider the following: why not apply the token-sale model to debt fundraising?
As a toy example, a corporation could, hypothetically, issue a bond as an "ICO for debt," so to speak, and represent bond ownership with ERC20 tokens to be sold in a token crowd-fund. Ostensibly, a world where debt assets were represented by a permission-less, universal token standard would, similarly, be a step-function improvement over the status quo in terms of liquidity and transparency. In order for liquid secondary markets to crop up in a similarly permission-less manner, however, investors would need a standardized mechanism of pricing tokenized debt assets. Whereas equity-like tokens are tied in value to branded protocols, projects, or entities, debt-like tokens are tied in value to empirical financial obligations from counter-parties that are often anonymized. The ERC20 standard, therefore, falls short of capturing the obligatory semantics of a debt asset insofar as it does not provide a means of:
    Retrieving machine-readable debt-specific metadata (e.g. principal, interest rates) associated with the assets
    Retrieving a history of payments between debtors and creditors in a debt asset's terms
    Pricing default risk into the debt asset's value
Dharma protocol intends to bridge this gap and provide a permission-less, generic mechanism by which debt assets of flexible type can be issued, sold, administered, and priced without having to rely on centralized data brokers of any kind.
Dharma protocol defines a procedure for issuing, funding, administering, and trading debt assets using a set of smart contracts, keeper marketplaces, and standardized interfaces elaborated on below. Dharma is heavily inspired in design by the 0x decentralized exchange protocol2, using 0x Broadcast Order Messages as the blueprint on which we base Dharma Debt Orders, their analogous equivalent in Dharma protocol. This mechanism will be explicitly formalized further in the paper. The protocol is designed to support EVM blockchains, but could ostensibly be extended to support any blockchain with requisite generic smart contract functionality. First, we solidify some terminology.
Agents
We define agents as the end-consumers of the protocol -- i.e. entities looking to borrow or lend crypto-assets. Those entities, be they people, corporations, contracts, or automata, unsurprisingly fall into two categories:
    Debtor - a party in a debt transaction who is borrowing an asset and owes a creditor some agreed upon value.
    Creditor - a party in a debt transaction who is lending an asset is owed some agreed upon value by a debtor.
Keeper Marketplaces
We adopt the catchall term keepers3 to encompass the utility players who provide value-added services to the network and compete in their respective marketplaces for compensatory fees.
    Underwriters4
In traditional debt markets, underwriters are entities that collect fees for administering the public issuance of debt and pricing borrower default risk into the asset. In Dharma protocol, this definition is expanded and formalized. An underwriter is a trusted entity that collects market-determined fees for performing the following functions:
    Originating a debt order from a borrower
    Determining and negotiating the terms of the debt (i.e. term length, interest, amortization) with the potential debtor
    Cryptographically committing to the likelihood they ascribe to that debt relationship ending in default (process described in detail under Specification)
    Administering the debt order's funding by forwarding it to any number of relayers.
    Servicing the debt -- i.e. doing everything in the underwriter's reasonable power to ensure timely repayment according to the agreed upon terms
    In the case of defaults or delinquencies, collecting on collateral (if debt is secured) or the individual's assets via legal mechanisms and passing collected proceeds to investors
This is not particularly out of band with what most online lenders do in their day-to-day underwriting and servicing operations. We foresee Dharma protocol facilitating an alternative, cheaper route for aspiring online lending platforms to bootstrap their operations and earn similar margins as they would in the status quo by becoming an underwriter -- all-the-while never holding balance sheet risk and avoiding the upfront time and capital costs associated with raising the requisite debt vehicles from traditional investors.
Example: Alice has a novel thesis on how to originate, underwrite, and service loans to aspiring ZCash miners who need significant upfront capital to buy GPUs on bulk. In lieu of knocking on the doors of traditional fixed-income investors, Alice decides to become an underwriter in Dharma protocol. She obtains the necessary lending licenses, sets up a website advertising lending services for miners, and drums up hype in the ZCash community for her credit product. When borrowers come to her site, their creditworthiness is automatically scored by Alice's proprietary technology and they are presented with the terms of the loan, as determined by Alice. Upon acceptance of the terms, Alice cryptographically attests to the borrower's likelihood of default, forwards the signed debt order to a relayer, and, upon the loan's funding, collects her desired fee. The entire flow of funds is transparently auditable on-chain, and Alice's competence in servicing and collecting on the debt can be empirically determined ex post facto.
    Relayers
Relayers in Dharma protocol perform an analogous function to relayers in the 0x Protocol -- namely, relayers aggregate signed debt order messages and, for an agreed upon fee, host the messages in a centralized order book and provide retail investors with the ability to invest in the requested debt orders by filling the signed debt orders. Note that, similarly to the 0x relaying mechanism, Dharma Protocol relayers need not hold any agent's tokens -- they simply provide a mechanism for creditors to browse through aggregated signed debt order messages, which creditors can use to trustlessly issue themselves debt tokens in exchange for the requested principal via client-side contract interactions (this mechanism is specified later in this paper). The primary differences between relayers in Dharma protocol and 0x are:
    Dharma protocol relayers are not hosting a secondary market order book, but rather, an order book containing requests for debts that have yet to be issued
    Dharma protocol relayers provide creditors with signed debt-specific metadata associated with the debt order messages and their accompanying underwriter so that they can make informed investment decisions about the risk profile of a given debt order.
    Dharma protocol relayers do not freely allow any anonymous party to publish signed debt orders on to their order book, and use their discretion to only accept signed debt orders from known, trusted underwriters.
Example: Bob wants to build a retail loan investor portal through which users can invest in a variety of debt assets -- a Kayak for peer-to-peer loans, if you will. Bob becomes a Dharma protocol relayer by setting up an online order book, building a retail investment platform, and allowing investors to browse through debt requests and examine associated data pertaining to the debtors' credit worthiness and the identity of the backing underwriters. Since Bob has seen that the empirical historical performance of Alice's attested assets has been in line with her predictions and knows that Alice's company is a publicly trusted and regulated entity, Bob allows Alice to broadcast signed debt orders onto his order book. When a debt order is filled on his platform, Bob is paid out a fee stipulated in the signed debt order.
Contracts
Dharma protocol leverages several contracts deployed on the Ethereum network. We highlight a few that are particularly relevant to understanding the prtocol's mechanics.
    Debt Kernel
The debt kernel is a simple smart contract that governs all business logic associated with minting non-fungible debt tokens, maintaining mappings between debt tokens and their associated term contracts, routing repayments from debtors to creditors, and routing fees to underwriters and relayers. These mechanisms are easier to define within the context of the debt lifecycle, and are extensively elaborated on in the below specification.
    Terms Contract(s)
Terms contracts are Ethereum smart contracts that are the means by which debtors and creditors agree upon a common, deterministically defined set of repayment terms. By extension, terms contracts expose a standard interface of methods for both registering debtor repayments, and programmatically querying the repayment status of the debt asset during and after the loan's term. A single terms contract can be reused for any number of debt agreements that adhere to its repayment terms -- for instance, a terms contract defining a simple compounded interest repayment scheme can be committed to by any number of debtors and creditors. The exact interface for this is defined within the specification below.
Note: An alternative scheme for committing to loan terms would be to commit to a standardized schema of plaintext loan terms (a la Ricardian contracts5) on chain and assess loan repayment off-chain in client applications. We deliberately opt not to pursue this scheme for several reasons. Primarily, explicitly defining a universal schema for debt terms inherently limits the range of debt asset types that can be issued in the protocol, while a generic interface for terms contracts opens the door for an infinite array of debt term arrangements. Moreover, committing to a terms contract on-chain removes any ambiguity from the evaluation of a loan's repayment status -- the contract is a single, programmatic, and immutable source of truth that is queryable by both contracts and clients. Finally, having an on-chain provider of repayment status greatly simplifies the mechanisms by which on-chain collateralized debt agreements can be structured and collected on in cases of default.
    Repayment Router
The repayment router contract is constructed to trustlessly route repayments from debtors to debt agreement beneficiaries (i.e. owners of the debt tokens). Additionally, the repayment router acts as a trusted oracle to the Terms Contract associated with any given debt agreement, reporting to it the exact details of each repayment as it occurs. This enables the terms contract to serve as a trustless interface for determining the default status of a debt.
Overview
The entire debt issuance process occurs synchronously in one on-chain transaction, when a signed debt order message is submitted to the Debt Kernel contract. If the message is valid as per the below specification, the following happen in one transaction:
    The debtor's adherence to the chosen terms contract and the underwriter's prediction of default likelihood are committed to on-chain.
    A non-fungible, non-divisible debt token is minted to the creditor and mapped to the above commitment.
    The principal amount is transferred from the creditor to the debtor (minus fees) and any keepers' fees are similarly transferred from the creditor.
This process is detailed below. First, we formalize the the format of data packets in the protocol.
Message Types
Communications between the different agents and keepers in the protocol are comprised of data packets that we refer to as Debt Orders.
Debt Orders
Debt orders are data packets listed by relayers that are the fundamental primitive of Dharma protocol -- submitting a valid debt order to the Debt Kernel triggers the issuance of a debt token and its swap with the requested principal amount. Dharma protocol is agnostic to the means by which creditors, debtors, underwriters, and relayers communicate and transfer debt order packets between one another -- A debt order can have up to 3 ECDSA signatures attached to it -- a debtor's signature, a creditor's signature, and an underwriter's signature.
The payload they sign depends on their role in the transaction -- debtors and creditors are required to sign the hash of the debt order (i.e. the debt order hash), while underwriters are required to sign only a subset of the fields in the debt order, which we refer to as the underwriter commitment.
Moreover, not all 3 signatures must be attached to the debt order in order to submit it to the Debt Kernel -- if an agent or keeper is not involved in the transaction (i.e. their address in the debt order is null) or they are involved but are also the party submitting the Debt Order to the Debt Kernel contract, then their signature is not mandated.
The debt order is comprised of the following fields:
Debt Issuance Commitments
A debt issuance commitment is a subset of the debt order data packet that we consider separately in order to define a canonical, unique identifier for any given debt agreement. The debt issuance commitment indicates the debtor's (and underwriter's) desire to mint a non-fungible debt token, where that debt token is to be immutably associated with a pairing (TC, P)TC being the address of a deployed terms contract adhering to the Terms Contract Interface (see below) and P representing the set of parameters ingested by the contract at TC. Moreover, the underwriter commits to a value R representing the underwriter's assessment of the average likelihood that the debtor will repay any given unit-of-value he is expected to, as defined by (TC, P). The hash of of this data packet is known as the issuance hash, which is used throughout the protocol as the canonical unique identifier of a debt agreement.
A sample schema for a debt issuance commitment follows:
Debtor/Creditor Commitment Hash
The debtor/creditor commitment hash is the payload signed by a debtor or creditor in order to indicate her consent to the parameters of the debt order. It is comprised of the Keccak 256 hash of the the following subset of the debt order parameters:
Underwriter Commitment Hash
The underwriter commitment hash is the payload signed by a underwriter in order to indicate her consent to the parameters of the debt order. The underwriter is given a different subset of parameters to sign so that debtors will not need to request new signatures from the underwriter for each relayer with whom they broadcast their debt order -- we will elaborate on this further below. The underwriter commitment is comprised of the Keccak 256 hash of the the following subset of the debt order parameters:
All together, a debt order is considered ready for submission if attached to it are:
    The debtor's ECDSA signature of the debtor/creditor commitment hash. (required unless the debtor is the address submitting the order to the Dharma smart contracts)
    The underwriter's ECDSA signature of the underwriter commitment hash (if no underwriter is present, or the underwriter is submitting the order to the Dharma smart contracts, this is not required)
    The creditor's ECDSA signature of the debtor/creditor commitment hash. (required unless the creditor is the address submitting the order to the Dharma smart contracts)
Any party that possesses a valid debt order with the requisite attached signatures can fill the order by submitting it to the Dharma smart contracts. Submitting the debt order to the Dharma smart contracts kick starts a mechanism, described below, in which a debt agreement token is minted and synchronously swapped with the principal amount. We will refer to arrangements in which a debtor fills a complete debt order as Debtor-Filler Order Submissions and arrangements in which a creditor fills a complete order as Creditor-Filler Order Submissions.
Creditor-Filler Order Submissions
The following steps correspond to the circled numbers in the above diagram:
    Debtor requests loan from an underwriter.
    Debt Order Handshake (described in detail further) occurs between the debtor, underwriter, and relayer(s), resulting in the relayer listing a valid, complete debt order.
    Creditor evaluates the terms of the Debt Order on a relayer's public order book.
    If the creditor wants to fill the order, he first grants the token transfer proxy an approval for transferring an amount of tokens greater than or equal to principal + creditorFee (i.e. using the ERC20 approve method). Note that this step need not be repeated for every order the creditor fills -- a creditor can grant an approval to the token transfer proxy once for a very large number of tokens knowing that the contract will only withdraw from his account if he consents to it via his submission or signature of a debt order.
    The creditor then submits it directly to the Debt Kernel contract. Note that his signature is not required in this scenario, given that his submission of the order to the kernel implicates his consent to its parameters. Debt Kernel then issues to the creditor a non-fungible, non-divisible token representing the debtor's commitment to the terms contract and associated parameters.
    The Debt Kernel transfers an amount of principal - debtorFee from the creditor to the debtor.
    The Debt Kernel transfers the underwriter her allotment of the fee, as defined by the Debt Order.
    The Debt Kernel transfers the relayer his allotment of the fee, as defined by the Debt Order.
The Debtor-Maker scheme is advantageous for scenarios in which there are many potential creditors, and the debtor does not care to control the precise moment at which the debt is eventually issued. For most use cases, the Debtor-Maker scheme would likely be most efficient.
Debtor-Filler Orders
The following steps correspond to the circled numbers in the above diagram:
    Debtor requests loan from an underwriter.
    Debt Order Handshake (described in detail further) occurs between the debtor, underwriter, and relayer(s), resulting in the relayer listing a valid, complete debt order.
    Creditor evaluates the terms of the Debt Order on a relayer's order book.
    If the creditor wishes to participate in the transaction, he first grants the token transfer proxy an approval for transferring an amount of tokens greater than or equal to principal + creditorFee (i.e. using the ERC20 approve method). He then attaches his ECDSA signature of the debtor/creditor commitment hash to the debt order.
    The creditor submits the signed Debt Order to the relayer
    The relayer forwards the signed Debt Order to the debtor.
    At his convenience, the debtor submits the signed debt order to the Debt Kernel contract, which triggers the minting of a unique, non-fungible debt token to the creditor acting as a signatory of the debt order.
    The Debt Kernel transfers an amount of principal - debtorFee from the creditor to the debtor.
    The Debt Kernel transfers the underwriter her allotment of the fee, as defined by the Debt Order.
    The Debt Kernel transfers the relayer his allotment of the fee, as defined by the Debt Order.
The Debtor-Filler scheme is advantageous for scenarios in which the debtor wants to synchronously borrow tokens as part of another, broader transaction. For instance, if a smart contract requires a user pay a certain amount of storage-specific tokens (e.g. FileCoin, Storj, etc.) in order to make use of it, the user could include a valid, signed Debt Order obtained through the above scheme as an argument to the smart contract function call. The smart contract could then submit the order on the debtor's behalf to the Debt Kernel, synchronously lending the debtor the necessary storage tokens and then debiting them to the smart contract in one transaction. This greatly reduces the friction around executing transactions in virtually any context on borrowed credit.
Debt Order Handshake
The Debt Order Handshake alluded to above is formalized as follows:
    Debtor requests an underwritten debt from a given underwriter, enumerating his desired loan terms (i.e. principle, term length).
    Underwriter assesses the debtor's default risk using her proprietary risk models, constructs an underwriter commitment (which, in turn, entails constructing a debt issuance commitment), attaches her ECDSA signature to the hash of the underwriter commitment, and sends the debt issuance commitment, underwriter commitment, and ECDSA signature to the debtor.
    If the parameters are in line with the debtor's desired terms, the Debtor now has all the requisite parameters to construct a complete debt order. If he wishes to have his order relayed to potential creditors, however, the debtor will request a relayer's fee schedule and address.
    The relayer responds to the debtor's request with his fee schedule and address.
    If the relayer's fees are in line with the debtor's wishes, the debtor will construct a complete debt order using the parameters supplied by both the underwriter and relayer, and send the order to the relayer.
    The relayer lists the completed Debt Order on their order book. Their signature is not necessary, given that their consent to the parameters of the order is tacitly affirmed by nature of the fact that they are voluntarily listing the order.
In order for the repayment status of any debt asset to be empirically evaluated on-chain, we define a repayment process in which repayments are facilitated by the Repayment Router contract and immutably recorded.
When a debtor wishes to make a repayment, they do the following:
    The Debtor grants the Token Transfer Proxy a transfer allowance (i.e. via the ERC20 approve method) greater than or equal to the desired repayment amount.
    The Debtor sends a transaction to the Repayment Router calling the repay function with parameters stipulating the desired repayment amount. The Repayment Router then retrieves the address of the current beneficiary of the debt agreement (i.e. the owner of the debt token) and transfers the desired repayment amount from the Debtor's account to the beneficiary's account, and registers the repayment by calling the registerRepayment method of debt's associated Terms Contract.
Note: we could construct a trivially simpler scheme in which Debtors send Creditors repayments directly without leveraging the Debt Kernel contract. It is necessary, however, for the Debt Kernel to facilitate the repayment process in order to ensure that, when a repayment is registered with a given Terms Contract, it empirically corresponds to a repayment transaction.
Terms Contract Interface
We require that any Debt issued via Dharma protocol commit to a smart contract, referred to as a Terms Contract. The purpose of the Terms Contract is to provide an immutable and programmatically queryable source-of-truth revealing the repayment status of the debt. This allows us to empirically and unambiguously both define the terms repayment scheme in the Debt Issuance process and evaluate the debt's repayment status during the debt's lifecycle both on and off-chain. The interface of required functionality is as follows:
Note that in the getExpectedRepaymentValue and getValueRepaid functions, repayments are defined abstractly in terms of 'units-of-value'. The units by which repayments are measured are intentionally left undefined -- this gives debt issuers the flexibility to, say, denominate the expected repayment values in fiat currencies whilst executing the actual transactions in tokens.
Dharma protocol is agnostic to the means by which underwriters deter defaults and go about collecting on debts. Ostensibly, some underwriters could issue legally binding lending agreements with debtors off chain and collect on debts by leveraging the courts. Alternatively, others could use on-chain collateralization schemes that leverage the functions exposed by a given debt's committed terms contract to release collateral to creditors in a trustless manner whenever the units-of-value repaid fall short of the expected units-of-value repaid.
Innumerable other schemes could be constructed to disincentivize defaults -- Dharma protocol doesn't advocate or design for any particular solution, but rather aims to provide a standard mechanism by which underwriters can be empirically evaluated for the performance of the debt assets they've attested to in the past. The market ought to gravitate towards rewarding underwriters whose past performance has been strong, and vice versa in punishing underwriters whose past performance has been weak. The metric by which an underwriter's past performance can be evaluated is what we'll refer to as the  metric, a function that borrows from the statistical analysis of binary classification in order to classify how accurate an underwriter's default predictions are:
It is crucial to emphasize that this is NOT a trustless, all-encompassing metric by which we evaluate an underwriter's performance -- fraudulent underwriters can game this metric in a variety of manners (seeAttacks). Rather, this is an empirical signal by which good-faith, trusted underwriters can be transparently evaluated. The metric is a valuable performance signal for the market only insofar as the underwriter is a trusted actor.
Debt is a massively varied asset class, and, in theory, virtually any type of debt agreement could be issued and underwritten via Dharma protocol. An online lender of any class of fiat loans could port their back office onto Dharma protocol by acting as both the debtor and underwriter in every transaction, converting principle payments into fiat on receipt, and conducting all borrower payments & repayments using fiat, thus obfuscating the on-chain nature of the loan funding process away entirely from the end user. We think that, eventually, this will provide an attractive alternative route for online lenders seeking debt capital.
In the short term, however, the more compelling use cases for on-chain debt issuance will be those that are uniquely enabled or augmented by an on-chain implementation. We highlight a few of those below.
Initial Debt Offerings / Tokenized SAFTs
Putting together an ICO is a surprisingly expensive endeavor, and projects in the space are beginning to raise larger and larger pre-ICO rounds in order to finance their eventual crowd-sale. This has led to the creation of the SAFT6: a legal instrument which effectively functions like a convertible debt agreement -- an investor contributes $X and, in the event of a future utility token-sale, expects to receive $X worth of tokens at a discounted price.
We propose that the pre-ICO financing of a cryptographic protocol can be issued, crowd-funded, and tokenized via Dharma protocol, under terms and conditions that are more flexible than status quo pre-sales.
In the most simple of examples, the debt terms contract can stipulate a vanilla discounted pre-sale agreement akin to a SAFT -- the principle lent would be the $X raised, and the repayment expected would be $X worth of the eventually deployed utility tokens at a discounted price. Thus, investors would be given a convertible debt token indicating their discounted ownership in the eventual utility tokens. However, the benefit in this arrangement over simply selling tokens in a proxy token that will eventually become the utility token are marginal.
The arrangements become more useful and interesting insofar as the terms contract can encode any variety of investor compensation schemes. Consider, for instance, a pre-sale which the debtor, at the time of the eventual ICO, owes 90% of the raised $X, paid out in Ether, at a Y% interest rate, with the remaining 10% paid out in discounted utility tokens. This is akin to venture debt fundraising in the traditional financial system, and would give investors a floor on downside-risk (i.e. 90% of the $X are betting on the success of the ICO) with a more muted up-side potential (i.e. 10% of the $X are betting on the eventual use of the utility token). This can further be augmented by creating a contract that acts as one of the multi-sig holders of the contract collecting proceeds in the eventual ICO, locking the proceeds as collateral until the debt terms contract indicates that the pre-sale investors have been properly compensated. Infinitely more pre-sale arrangements can be structured using debt terms contracts in Dharma protocol (e.g. variable discount rates based on how long it takes the debtor to reach their eventual ICO, refunding investors if an ICO is never achieved, etc.).
Decentralized Margin Lending
Decentralized exchanges relying on off-chain order books (e.g. 0x Protocol) are an important and necessary piece of infrastructure in the token ecosystem. If they are to match centralized exchanges in utility and user experience, however, they will need to support margin trading in some capacity.
We can construct a decentralized margin lending system by issuing margin loans via Dharma protocol and having the terms contract associated with a given debt act as a gating function for allowing agents to close margin positions locked into a smart contract. In such a scheme, an underwriter would require a debtor to lock collateral into a margin account contract according to a desired margin ratio as a prerequisite for attesting to the borrower's debt issuance commitment. The debtor would then execute a trade on margin by synchronously filling a Debt Order and a 0x Broadcast Order in the same transaction, with the receiving account being the locked margin account. During the position's term, the underwriter would act as a trusted price oracle to the terms contract. Closing the account would be within the purview of the debtor until the terms contract indicates that either the margin account is in a state of default (as per the agreed upon margin ratio) or the position has expired, at which point the margin account contract will allow the creditor to close the account and earn her desired interest.
Thus, we can leverage the protocol to build a margin lending system that fits natively into the order books of relayer-like entities in existing decentralized exchanges.
Fraudulent Underwriters
Underwriters operating in a fraudulent manner can deceive investors into believing that they are originating prime debt from borrowers, when in reality they are in fact acting as borrowers themselves. Conceivably, a fraudulent underwriter could build up an extremely positive on-chain attestation performance by lending to themselves using many assumed public keys, and then execute a large exit scam by deceiving creditors into investing in Debt Orders they've attested to in which they are the actual borrower and defaulting entirely on those debts. It is for this reason that we emphasize that Dharma is not a fully trustless protocol -- borrowing and lending under this scheme is only safe insofar as underwriters are known, trusted entities, and not pseudonymized public keys. It is an underwriter's responsibility to go to whichever lengths are possible to build creditors' trust in their legitimacy -- be that by publicly corroborating the identities of the entities' whose creditworthiness they're attesting to (e.g. if the debtor is a business or corporation), or by cultivating a publicly trusted and known relationship with regulators (e.g. as would be the case with most existing online lenders leveraging the protocol). The sort of trust an underwriter must build with the investment community is not unlike that of a protocol's development team in the run up to a token-sale -- both are facilitating a public investment offering, and, as such, both have an onus of asserting their legitimacy and integrity.
Sybil Attacks
In the context of a lending protocol, a sybil attack involves generating a large number of fraudulent identities, taking on multiple unsecured debts at a time, and defaulting on all at once with little consequence. Largely, defending against sybil attacks falls within the purview of an underwriter's responsibilities -- if an underwriter's identification and KYC procedures are not robust enough to detect sybil behavior, the empirical performance of debts they've attested to will reflect it. However, sybil attackers could ostensibly solicit debt orders from several underwriters at a time, meaning that data sharing amongst underwriters operating in similar debt verticals would likely become a pertinent need.
Debtor Griefing
In scenarios in which a creditor is acting as the market maker in a Debt Order transaction, the creditor could ostensibly engage in what we call "Debtor Griefing" -- the act of front-running the debtor's attempts to fill the given Debt Order by transferring the principle tokens away from the address in which they were originally held for an impending atomic swap. In order to execute the attack, the creditor would facilitate the completion of a Debt Order as the market maker in the handshake process, await the submission of the debtor's filling transaction by listening to the pending transaction pool of a local Ethereum node, and submit a transaction in the same block moving his tokens away from the address at which the principle tokens were located, causing the debtor's transaction to fail and throw. The attack would result in a debtor's fill order throwing an exception, and waste a small amount of gas on the debtor's behalf. In one-off situations, the wasted gas is a nuisance at worst. However, in a systematically executed context, a creditor could ostensibly use this mechanism to perform a denial-of-service attack on a relayer's entire order book by acting as a market maker under a variety of continually generated addresses to the entire span of Debt Orders in the order book, consistently griefing the debtors and recycling the funds for usage in further griefing attacks. The gas costs of executing such an attack at large scale are non-negligible, but, assuming an attacker is motivated by some sort of extortionary bounty levied from a relayer, the attack could prove to be profitable if an attacker possesses the requisite liquidity. The best line of defense against such attacks is the relayer herself -- relayers that are plagued by such attacks have a variety of options to temper denial-of-service attacks from malicious creditors, ranging from simple IP blocking to more aggressive policies that force creditors to go through KYC walls.
Side Deals
We refer to "side deal attacks" as attempts by agents in any given debt transaction to avoid paying fees to the keepers involved in the transaction's structuring. Consider the following scheme -- a third-party maintains an online registry in which potential debtors voluntarily associate their public keys with their email addresses. Given that creditors can inspect Debt Orders in their client browser on a relayer's order book, a creditor could leverage the third-party's registry to communicate with debtors whose Debt Orders are listed on the relayer's order book. The creditors and debtors could then coordinate on a separate channel to construct a point-to-point Debt Order in which neither the underwriter nor relayer are compensated for their services, saving the agents fees that would otherwise go to the agents.
Underwriters are likely less sensitive to this vulnerability insofar as creditors rely on their services throughout the debt's term. With relayers, however, creditors have nothing to lose in conducting side deals, meaning it's feasible for an adversary to systematically sabotage a relayer's operations by constructing a publicly usable matching engine that ingests Debt Orders from the relayer's order book and matches participating debtors and creditors such that they are in a position to construct a side deal.
We contend that, in practicality, participating in most systemic side deal matching constructions is a fairly high friction process for agents, in that successful side deal matching would require agents to engage in yet another Debt Order Handshake, which, under highly asynchronous conditions, could be too time consuming to merit the fee saved. But even if we construct side deal matching arrangements which are frictionless enough to merit their usage, relayers are not without recourse. A particularly targeted relayer could obfuscate debtors' addresses via a Commit-Execute construction that retains a trustless relationship between the relayer and creditor7:
    In lieu of listing Debt Orders in the intended manner, relayers list Debt Orders modified such that all fields containing the debtor's address are zero'd out -- nullifying the validity of Debt Order messages and their associated signatures, but providing creditors with the data points necessary to reason about investing in any given debt offering.
    Commit: Creditors commit to filling an order by submitting the invalid and incomplete Debt Order to a purpose-built smart contract that acts as an intermediary cog in the transaction. Additionally, creditors grant the smart contract token transfer allowances8 equivalent to the token allowances necessary to fill the Debt Order's attached 0x Broadcast Order.
    Execute: The relayer executes the issuance and swap by submitting the complete, valid Debt Order to the aforementioned contract. The contract then verifies that all fields in the submitted Debt Order match their counterparts in the creditor's committed, incomplete Debt Order (with the exception of fields containing the debtor's address), and then, in sequence, transfers itself the requisite principle tokens from the creditor, submits the complete Debt Order to the debt kernel contract in its capacity as an intermediary creditor, and finally transfers the debt token it newly possesses to the creditor. If the submitted debt order is invalid or mismatched with the Debt Order committed to by the creditor, the contract throws and the creditor maintains ownership of her tokens.
Thus, relayers can leverage the above Commit-Execute construction in order give creditors a means of filling obfuscated Debt Orders in a trustless manner, if circumstances necessitate its usage.
1 I emphasize equity-like insofar as protocol tokens are, in theory, not equity, but, in terms of their risk profile and the class of speculative interest they attract, behave exactly like equity.
2 Warren, Will, and Amir Bandeali. “0x: An Open Protocol for Decentralized Exchange on the Ethereum Blockchain.” Https://0xproject.Com, 0xproject.com/pdfs/0x_white_paper.pdf.
3 Zurrer, Ryan. “Keepers - Workers That Maintain Blockchain Networks.” Medium, Medium, 5 Aug. 2017, medium.com/@rzurrer/keepers-workers-that-maintain-blockchain-networks-a40182615b66.
4 In previous versions of this white paper, these entities were referred to as Risk Assessment Attesters, or RAAs. We've moved away from this terminology, given that 'underwriters' are more intuitively digestible as a broad class.
5 Grigg, Ian. “The Ricardian Contract.” Iang.org, 2000, iang.org/papers/ricardian_contract.html
6 Batiz-Benet, Juan, et al. “The SAFT Project: Toward a Compliant Token Sale Framework.” saftproject.com/static/SAFT-Project-Whitepaper.pdf.
7 Note that this construction only works for Debtor-Maker Debt Orders.
8 i.e. via the ERC20 approve method. 
Since we released the new & improved Dharma white paper last week, we’ve been blown away by the interest we’ve received from crypto denizens and general enthusiasts alike. Building an informed community of technologists, entrepreneurs, and thought leaders is crucial to our vision. To this end, the purpose of this post is to demystify the inner workings of the protocol in a succinct, plain-language explanation that is accessible to audiences technical and non-technical alike. For a more thorough deep dive on the protocol’s mechanics, study the Dharma white paper here.
This post will serve as a primer on how Dharma protocol works and what roles different constituents in the protocol play. We assume readers are comfortable with the following concepts (useful resources are linked for each one):
    The Ethereum blockchain and smart contracts
    Public-key cryptography
    Basic terminology of borrowing and lending
    Reading pseudo-code
This primer glosses over many processes, design rationales, and limitations that are explored at length in the Dharma white paper. Moreover, the motivation for building Dharma protocol and why we think it’s exciting are elaborated on elsewhere. As always, if anything is unclear, feel free to hop in the Dharma community chat and ask a question.
First, let’s start with a basic example.
Meet Alice and Bob — Alice wants to borrow 1 Ether, and Bob is a friend of Alice’s with more than 1 ether to spare. Alice and Bob come to an agreement that Bob will lend Alice 1 ether today, and, in exchange, Alice will repay Bob 1.1 ether in a week. In this transaction, Alice will be a debtor and Bob will be a creditor. Note that neither Bob nor Alice have to be humans per se —debtors and creditors can be computer programs, smart contracts, decentralized organizations, etc. — from the protocol’s perspective, Alice and Bob are simply Ethereum addresses.
One way Alice and Bob could formalize their agreement is by drafting and signing a legal contract that defines the terms of the transaction — that way, if Alice, Bob, or any third party ever come to a disagreement over how much ether Alice is expected to repay Bob, they can refer back to the signed legal contract in order to resolve the dispute. Such a legal contract would look something like this:
Legal contracts, however, are clunky — if Bob wants to sell his rights to receive 1.1 ether from Alice to Charlie, he would have to either amend the original contract with Alice, or sign a new agreement with Charlie. Alice and Bob decide instead to enter into a debt agreement using Dharma protocol.
First, Alice and Bob have to somehow consensually record their agreement to a certain set of repayment terms. They do this with the help of a special type of smart contract we call a terms contract. A terms contract is very similar to a legal contract in that it serves as a form of social proof that a debtor and creditor have entered into a repayment agreement with one another. What makes a terms contract different from a legal contract is that:
    It is immutably stored on a blockchain.
    A creditor can easily transfer his rights to receive repayments to another party.
    It is easy for a machine to understand what repayment terms are defined by the terms contract.
In order for the last point to be feasible, terms contracts must adhere to the terms contract interface — a smart contract “template” that enumerates which methods must be implemented by a terms contract. An abridged version of the terms contract interface is as follows:
Let’s construct a terms contract for Alice and Bob’s agreement using pseudo code. Remember it must codify that, in exchange for 1 ether today, Alice owes Bob 1.1 ether in 1 week. For reasons we elaborate on later, we can actually simplify the terms to represent only Alice’s repayment obligation to Bob as follows:
We now have a smart contract that programmatically defines the terms of repayment Alice is expected to adhere to, and that can be queried at any given time in order to determine whether Alice has defaulted on her repayments (i.e. getValueRepaid() < getExpectedRepaymentValue() ). Alice now deploys this terms contract to the Ethereum blockchain, and the terms contract now has an Ethereum address we’ll call. 
Note: Debtors need not deploy a new smart contract for each debt agreement, as this would be expensive. The mechanism by which terms contracts can be re-used and generally repurposed is described in the white paper.
Alice now proceeds to construct a debt order using the deployed terms contract’s address. Debt orders are the fundamental primitive of Dharma protocol — they are signed data messages that communicate a debtor’s desire to receive a loan under certain repayment conditions. We will not cover the specific schemas and processes associated with generating and signing debt orders in this post — for our example’s purposes, imagine Alice constructs a string of text that says:
Alice can now take this string, cryptographically sign it using the private key associated with her public key Y , and send the signed message to Bob via any channel she desires — an email, a Facebook message, carrier pigeon, etc. Note that nothing in the message specifies Bob as the creditor in the transaction. This is deliberate — anyone with access to the signed debt order and a willingness to pay the desired principle can “fill” the debt order and become the creditor in the transaction. This will become important later.
Bob now takes the signed debt order and submits it to the debt kernel smart contract. The debt kernel is a smart contract that acts as a central registry and hub for all administrative logic in the protocol. When Bob submits Alice’s signed debt order to the debt kernel, the following happens:
    The repayment terms defined by the terms contract X are immutably recorded in the debt kernel’s registry as having been committed to by the holder of public key Y (i.e. Alice).
    Alice is transferred the desired principle amount from Bob’s account, and Bob is issued a unique debt token that is associated with the committed debt agreement and terms contract X.
Alice has now been credited with 1 ether, while Bob has been debited 1 ether and credited with 1 debt token that is unique to Alice’s repayment agreement. Bob’s debt token is a means of establishing who Alice is expected to repay in the debt agreement — whichever address controls the debt token at any given time is the address that will receive Alice’s repayments.
A week passes and Alice wants to repay her debt to Bob. The following happens:
    Alice sends her repayment to the debt kernel smart contract
    The debt kernel registers Alice’s repayment with the terms contract associated with the debt she is repaying
    The debt kernel forwards Alice’s repayment to whichever address currently controls the associated debt token, which, in this case, is Bob’s address
Et Voilà — Alice and Bob were able to issue and administer a tokenized debt agreement without having to rely on any brokers or intermediaries.
This is great, but leaves a lot to be desired — if Alice and Bob are friends or family then Alice might have a social incentive to repay her debt, but the vast majority of the world’s debt agreements are made between strangers. The above scheme lacks a means of incentivizing Alice to repay Bob’s loan, or, for that matter, a mechanism for helping Alice find potential creditors like Bob.
We introduce two classes of utility players to fill these gaps: underwriters and relayers.
Underwriters are trusted entities that, in any given debt issuance, do the following in exchange for fees paid by both the debtor and creditor:
    Evaluate the likelihood D that any debtor will repay a creditor according to terms defined in the terms contract.
    Immutably attest to the predicted likelihood D on the debt kernel’s on-chain registry.
    Do everything in their power to make sure that, with a likelihood of D, the debt is repaid in full.
In the context of Alice and Bob’s debt agreement, we can introduce an underwriter Charlie into the equation, who, for this example’s purposes, we will imagine as a publicly known online lender (e.g. LendingClub, SoFi, etc.). Alice would begin the process by going to Charlie’s website and requesting that he attest to a debt order she has constructed. If Charlie agrees, we can modify the previously constructed debt order to include Charlie’s attestation — something to the effect of:
The new debt order would be signed by both Alice and Charlie, and, when Bob submits the order to the debt kernel, Charlie’s prediction would be immutably recorded. Alice and Bob would be debited 0.001 ether each in addition to the normal debt issuance transaction’s proceedings, and Charlie would be credited 0.002 ether.
Crucial to the underwriter scheme is the notion that creditors and debtors alike can empirically evaluate an underwriter’s on-chain historical performance by comparing the predictions he has attested to with the repayment status of those debts. Herein lies the incentive for underwriters like Charlie to do whatever is in their power to make sure debtors repay — if Charlie’s predictions line up with reality well, the market ought to gravitate towards leveraging his services more often and at a higher fee.
How an underwriter chooses to deter defaults is intentionally out of the scope of what Dharma protocol defines, but there are innumerable routes an underwriter can take to incentivize repayment both on and off chain. At a minimum, underwriters can leverage the traditional, offline collections mechanisms most lenders rely on today — courts, contracts, collections agencies, etc.
More interesting, though, are mechanisms which leverage smart contracts to deter defaults — for instance, on-chain collateralization schemes where, as a prerequisite for receiving an underwriter’s attestation, a debtor is required to lock a certain number of tokens into a smart contract that releases the tokens to a creditor if the terms contract indicates that the debt has begun to default.
These mechanisms will be elaborated on in future posts — what is important to understand is that, at a protocol level, Dharma is agnostic to the deterrence methodology.
Note: There are several aspects of the underwriting mechanism that are either simplified or omitted in this explanation. Most importantly, a crucial caveat not discussed above is the risk of fraudulent underwriters and the necessity that underwriters be trusted entities (see here).
Alice can now broadcast her signed, underwritten debt order via any channel that lets her reach potential creditors. In practicality, the majority of borrowers would likely prefer not to solicit funds from their friends and family on social media. If we want to create debt markets that hold a candle to their traditional counterparts, we need to construct some sort of mechanism for connecting debtors to potential creditors. We introduce relayers — a concept borrowed from the 0x protocol — to fill this gap.
Relayers are centralized entities that “relay” debt orders from debtors to potential creditors, and collect a fee in the event that an order is filled. Their job is simple — to provide creditors with a centralized interface for browsing through different debt orders, and to give debtors a means of broadcasting their orders to a broad, general audience.
In Alice and Bob’s example, we can introduce a relayer Dave into the transaction. Let’s imagine Dave is a Chinese entrepreneur who builds a debt crowdfunding platform tailored to Chinese retail investors — Dave accepts debt orders from a host of underwriters around the world, and earns a fee anytime those debt orders are filled by creditors on his platform. Alice would send her debt order to Dave, who would list her order on his platform after amending it to include his fee allocation and signature — i.e.:
In a manner similar to that of the underwriter scheme, Dave will be paid the defined fee once Alice’s order is filled by Bob on Dave’s platform.
Note that relayers can come in many different flavors — here we imagine Dave as hosting a centralized debt crowdfunding platform, but we could conceive of relayers who act as thin APIs catering to developers and arbitragers writing auto-investment bots, or, on the opposite side of the spectrum, operating entirely offline and manually relaying large packages of debt to institutional investors. Future posts will elaborate on some of the more novel strategies relayers can take in the Dharma debt issuance scheme.
We can summarize the above as follows:
    Dharma protocol is an end-to-end mechanism for issuing, underwriting, and administering debt instruments of virtually any type as tradeable, programmable tokens.
    The repayment terms of any debt agreement in Dharma protocol are codified by a type of smart contract we refer to as a terms contract.
    Potential debtors request loans using a signed message packet we refer to as a debt order.
    Debt orders can be sent to prospective creditors via any channel — email, Twitter, Slack, Relayers, etc.
    Creditors “fill” a debt order by submitting a debtor’s signed debt order to a smart contract we refer to as the debt kernel, an action that synchronously transfers the principle amount from the creditor to the debtor and issues the creditor a tradeable debt token that is unique to the debt agreement.
    Underwriters are trusted, centralized entities that, for a fee, vouch for the creditworthiness of a borrower and do everything in their power to make sure that the given debt is properly repaid.
    Relayers are entities that, for a fee, facilitate the funding of debt orders by broadcasting signed debt orders to potential creditors on debtors’ behalves.
Again, it’s important to note that this post glosses over many important details, processes, and limitations of the protocol — if your interest is sufficiently piqued, we suggest doing a deep dive into the technical white paper. Additionally, you can subscribe to the Dharma Mailing List for weekly content, progress updates, and early access to releases we’ll be rolling out over the coming months.
We’re excited about the community we’re building around Dharma protocol, and look forward to hearing your questions, thoughts, and constructive feedback on the Dharma community chat channel.
Welcome aboard!
— N

2 Articles

VIEW ALL
logoens
RECENT ARTICLES
Just want to get a name and make it resolve to something? Here’s how.
First, download ensutils-testnet.js to your local machine, and import it into an Ethereum console on a node synced to ropsten or rinkeby:
Before registering, check that nobody owns the name you want to register:
If this line returns a date earlier than the current date, the name is available and you’re good to go. You can register the domain for yourself by running:
Next, tell the ENS registry to use the public resolver for your name:
Once that transaction is mined, tell the resolver to resolve that name to your account:
...or any other address:
If you want, create a subdomain and do the whole thing all over again:
Finally, you can resolve your newly created name:
which is shorthand for:
Experimental support is available for hosting DNS domains on the Ethereum blockchain via ENS. This works by configuring the domain’s nameserver records to point to gateway DNS servers; these DNS servers resolve lookups by consulting an ENS registry which points to resolvers containing the zone data for the relevant domain.
The steps to host your own domain on the blockchain are:
    deploy your own ENS registry
    Deploy an instance of DNSResolver
    Update your ENS registry to set your newly deployed DNSResolver as the resolver for your domain name (eg, by calling setSubnodeOwner and setResolver; see Interacting with the ENS registry for details). Don’t forget to set the TTL on this record to a reasonable value, or your DNS data may not get cached.
    Write a zonefile. The zonefile must include an NS record for your domain that specifies the resolver as address.ns1.ens.domains, where address is the address of the ENS registry you deployed in step 1, without the leading ‘0x’. An example zonefile is available for reference.
    Clone and build ensdns. Start a local node, and run ‘ensdns upload –keystore=path/to/keystore zonefile’ to upload the zone to the blockchain.
    Update your NS records with your registrar to point to the name above (address.ns1.ens.domains).
Please note that this feature is still experimental, and shouldn’t be used for anything production critical; the DNS gateway is lightly tested, and only a single instance is running at present, providing no backup or failover in case of server issues. The API and configuration may change in backwards-incompatible ways, breaking your nameserver!

6 Articles

VIEW ALL
logomakerdao
RECENT ARTICLES
"With great power comes great responsibility" - Uncle Ben (Spiderman)
This quote best summarizes the power of leverage, the ability to invest with more money than you actually have. That means if you make money from investing, you make even more money, but if you lose money, you lose even more money. The simplest way to leverage yourself is by borrowing money or taking out a loan, and then reinvesting it in hopes of making more money than you would have without borrowing.
In this paper I’ll be talking about how you can open a Collateralized Debt Position (CDP) with MakerDAO in order to use leverage and go over the risks/rewards associated in doing so. There may be a lot of terms and concepts that may be new to you in relation to the MakerDAO platform, but I will try my best to explain any necessary background information you need to know. My assumption is the reader may have heard about MakerDAO and DAI, but doesn’t have a firm grasp of what it is and how it works. If you are already familiar with the project skip down to the section entitled “CDPs and creating your own DAI”.
The goal of this article is to give a high-level overview of MakerDAO, DAI, and the risks/rewards of opening a CDP for leverage. Afterwards, the reader can decide if they’d like to try it out for themselves.
Let's start at the beginning.
The first place to start is the DAI token; it is a stable coin pegged to the value of the US Dollar. What that means is, it is a cryptocurrency whose value should be equal to 1 USD. That means 1USD = 1DAI. (Note: The fact that 1DAI = 1USD is actually arbitrary, 1DAI can equal 1YEN or 1EURO, but MakerDAO decided on 1USD).
Another stable coin you may have heard of is Tether (USDT) which is used on many cryptocurrency exchanges. The difference between Tether and DAI are the mechanisms they use to keep the value stable. Tether keeps the value stable by backing 1Tether (USDT) to 1USD. That means for every Tether that was printed there should be an equal number of USD in a vault somewhere to back it up. The disadvantages with this approach is the possibility of fraud or manipulation because it is centralized by whoever owns the vault. If one day it is found out that there wasn’t actually enough fiat to back up the value of Tether then the price would collapse. You have to trust that the organization behind Tether has the full amount saved somewhere.
In my opinion, the difference between a centralized, stable currency and a decentralized one is who has the ability to print more money. DAI can be considered a decentralized stable coin because anyone has the ability to create their own DAI. Imagine that... with the power to print your money, you become your own bank. That being said, DAI is able to stay at a stable price and give people the power to create their own DAI through some complex mechanisms that may turn some people off. Truthfully, the process is a bit cumbersome right now, but in the future I’m sure there will be user experience improvements.
Most people will not have to understand the process of creating DAI. You could simply go to your favorite cryptocurrency exchange and buy DAI off of there, and 99% of people will probably go ahead and do that. With some exceptions, the price should be very close to 1USD so whether or not you create your own, or buy off of an exchange it won’t matter much to most people.
As long as the currency’s value is stable, it is living up to its purpose and people can use it without understanding its mechanisms. However, if you’re reading this you probably aren’t a part of the 99%, you’re the 1% who believes in a decentralized future and want to know how to create your own DAI, so you can be your own bank, lender, escrow service, etc. First though, we’ll have to explain why a stable coin is important.
Stablecoins or currencies that keep their value predictable are important for several reasons. I’ll give an example. Imagine you are a young, working, middle-class millennial who is really into cryptocurrency. After you convince your boss that the future is crypto by talking non-stop about it, they have agreed to pay half of your salary in crypto, specifically a meme-coin. Let’s say for simplicity you earned 3000 USD a month. Now you’ll get 1500 USD and 1500 worth of meme-coin. At first you think this is great because the price of meme-coin is going up so you are actually earning more than 3000 USD. However, one day there is a large pump and dump after you receive your pay and your $1500 worth of meme-coin goes down 30%. Suddenly you’ve lost $450 and can’t pay this month’s Lambo bills. Stablecoins are important because they help to mitigate the risk related to investing in cryptocurrencies. Sure you can get paid in meme-coin, but the value can appreciate or depreciate so rapidly it can be hard to come up with fair, stable prices for services and goods. This is why stable coins are important for commerce and everyday activities.
In terms of investments, a common cryptocurrency trading strategy is to exchange coins that you predict will depreciate in value with a stable coin effectively locking in the price. If the price goes down you can buy back in and earn more, while if the price goes up, you technically haven’t lost money, but if you want to buy back in you’d get less of the coin than you originally had. Stablecoins also provide a great base for Fiat trading pairs on exchanges since they usually match on a 1 to 1 basis.
Now we’ll talk about how DAI actually keeps its price stable and how to create your own DAI.
There are different strategies for keeping a coin’s price stable. The common tactic is to back the coin’s value with something else of equivalent value. For Tether it’s fiat. For fiat it may be a precious metal like gold. When something’s value is backed by another object it can be considered as collateral.
This might get a little meta, but money can be considered as a kind of debt. When you think about it, a $1 dollar bill is kind of like an IOU (I owe you). When the USA was still using the gold standard 1 dollar bill was worth $1 worth of gold, and it was an unspoken agreement that you could trade in your bills for its equivalent value in gold. After the government stopped using the gold standard in the 70’s you can’t actually do that anymore, but the concept of debt still exists. Dollar bills are still IOUs, not for gold, but for goods, services, or anything that can be exchanged in USD.
Traditionally the process of printing money or creating debt is a centralized process, but MakerDAO gives you that power with CDPs and DAI. Let’s break down the process of printing money or debt.
    You need some kind of collateral
    You need to be able to store that collateral safely somewhere
    You need a mechanism to be able to print/create new debt
    You need a mechanism to free up debt
    You need a mechanism to deal with bad debt.
In a centralized system all 5 of these things are handled by a single authority. The reason why MakerDAO is powerful is because all 5 of these things can be managed by anybody.
USD
    A type of Collateral - Gold (Before 70s). USD is not actually backed by anything anymore.
    Place to store Collateral safely - Fort Knox for gold, but since USD is not backed by a physical type of collateral anymore it is metaphorically stored as trust in the government.
    Mechanism to print/create debt - Treasury can print more money
    Mechanism to free debt - Government could, theoretically, remove debt it owns from circulation.
    Mechanism to deal with bad debt - Repossession/Liquidation of other collateral by a central authority.
Tether (USDT)
    A type of Collateral - USD
    Place to store Collateral safely - Bank/Vault
    Mechanism to print/create debt - Tether organization can print more money
    Mechanism to free debt - Tether organization buys back Tether
    Mechanism to deal with bad debt - Tether doesn’t really deal with loans or bad debt.
DAI
    A type of Collateral - Ether (ETH) Note: Currently MakerDAO the organization behind DAI only allows Ether to be used as collateral, but in the future they plan on implementing multiple collateral types so you could choose from a range of options.)
    Place to store Collateral safely - CDP - Smart Contract
    Mechanism to print/create debt - Smart Contract functions
    Mechanism to free debt - Smart Contract functions
    Mechanism to deal with bad debt - Liquidation of CDP by peers/keepers
1. A type of Collateral
The first thing is the type of collateral. DAI is backed by Ether. That means if you own Ether you can create your own DAI. In the future MakerDAO plans to implement multi-collateral DAI, meaning you’ll be able to choose different collateral types; it won’t have to be just Ether.
Earlier, I mentioned why a stablecoin may be better in some situations than a cryptocurrency like Ether due to price volatility. So, how does DAI’s price stay stable even though it is backed by something that may be unstable? That will be explained later when we explain how MakerDAO deals with bad debt.
2. Place to store Collateral Safely
The next thing is a place to store that collateral. Tether and USD both use banks or vaults to store their collateral. DAI uses smart contracts. I will not go into what smart contracts are, as that is a completely different and larger topic, but if you don’t know what it is you can think about it as a kind of digital vault that can manage itself. Because Ether is a digital cryptocurrency it makes sense it would be kept inside of a digital vault. Smart contracts are programs that when coded correctly may even be harder to get into than a bank vault with guards and guns.
3. Mechanism to print/create debt
The third thing you need is a mechanism to create new debt. Both USD and Tether print money centrally by a single authority. DAI on the other hand gives this power to anybody who has Ether. Remember how I said that the smart contract that holds all the Ether is kind of like a digital vault that manages itself? The digital vault not only holds the money, but manages it too. If you wanted to create DAI what you would do is go up to the smart contract/vault, let’s name it Vaulty for now, and say Vaulty I would like to give you some Ether as collateral so I can print my own debt/DAI. This process is also known as opening a Collateralized Debt Position (CDP). The Ether is the collateral and once it is locked away by Vaulty you can print your own Debt. Hence the name Collateralized Debt Position or CDP. So once you give Vaulty your Ether to lock up, Vaulty will let you create your own DAI backed by the Ether you gave earlier.
The basic process is as follows, open up a CDP, lock away your Ether as collateral, and then create your own DAI. If you want to create more DAI, then you have to lock up more Ether.
4. Mechanism to free debt
If you can create debt, then you need a way to clear debt as well. With USD it seems we are always deeper and deeper in debt every year, so I’m not sure there is a mechanism for this, but theoretically the government could reduce inflation by removing debt or fiat it owns from circulation.
For Tether the organization can buy back Tether off the exchange then burn the token. If they buy Tether on an exchange when it is below 1 USD they can even make profit. That sounds too good to be true, but anybody can do the same thing with DAI as well.
With DAI anyone who created debt can free it up. All you have to do is return the DAI you created to Vaulty. At that point you can even ask Vaulty to return you the Ether you locked up. The way MakerDAO created DAI was to incentivize users to keep the price stable at 1USD by creating profit-making opportunities when the price is not 1USD that will drive the price toward that number. If DAI’s price on an exchange is below 1USD that means you can make profit buying DAI, which will drive the price back up toward 1USD. Then you can pay back your CDP debt at a discount earning you profit. If DAI’s price on an exchange is above 1USD, you can create more DAI from your CDP (which will always be 1DAI = 1USD) then sell it on the exchange for a profit, driving the price back down toward 1USD.
An important thing to note is there is a small fee associated with MakerDAO to close or pay down a CDP. This is called the Governance Fee and it is currently set to a 0.5% APR which is incredibly low when compared to traditional APR rates of conventional debt like credit cards which can have APR rates greater than 20%.
5. Mechanism to deal with bad debt
Traditionally, bad debt is the inability to pay back what you owe. In those scenarios the lender would repossess and liquidate assets owned by the lendee. This can be scary for several reasons. The lender can lay claim to other assets as collateral and then liquidate them at the expense of the lendee. The other downside is it can affect the ability to borrow more debt in the future.
Centralized systems try to keep their assets safe by assessing the risk associated with doing business with an individual or organization. You may have heard of credit scores. If you are unable to pay a debt back this has long term effects on your ability to borrow more debt in the future.
One of the advantages of MakerDAO is inability to deal with a debt will not affect future attempts to use the platform. MakerDAO doesn’t use things like Credit Score and doesn’t care if you failed to keep a healthy CDP several times (please maintain a healthy CDP for your own sake). As long as you have ETH you can create DAI.
That being said, DAI has a liquidation process that borrowers have to be aware of. The primary risk of owning a CDP is if the value of the collateral goes down. This is true of currencies, like DAI, where the collateral has a value that can appreciate or depreciate over time. The reason why the value of collateral going down is bad is because it lowers the value of the currency. For example, let’s say 1 ETH costs 100USD and 100DAI was created backed by that 1ETH. If the price of ETH goes down by 10% to 90USD and 100 DAI was already created that means each DAI will be worth 0.90USD and not 1USD anymore. Since the value of ETH is volatile a MakerDAO CDP will not let you create DAI at a full one to one ratio of the value of your ETH in case something like this happens.
Something else to understand about the MakerDAO CDP is that it is a kind of loan you don't have a schedule to pay back on. The only time you have to pay debt back is to prevent the value of the collateral going below the amount of DAI created from the CDP. In a traditional system the inability to pay back the bad debt is to liquidate the collateral or repossess assets owned by the lendee. This process is done by a central authority like the IRS or a bank, but with DAI the liquidation process can be done by anyone.
MakerDAO incentivizes people to keep the price of DAI stable by creating profit opportunities to keep the price stable at $1USD. When bad debt is introduced into the system it will make the system less stable and may make it harder to redeem 1DAI for 1USD in collateral. To deal with the potential of bad debt MakerDAO has created a profit opportunity for peers to liquidate CDPs that don't meet the safe liquidation percentage (150%). Liquidation is done through peer enforcement and bots created to make profit by closing out bad debt.
The advantage of this mechanism is the clear rules for liquidation. The disadvantage is it is almost 100% certain you will be liquidated and it will happen at the exact moment you are below the safe liquidation rate. You will not receive letters in the mail, second chances, or 30 day opportunities to get the debt in good standing. Due to the profit opportunities, peers and bots will liquidate every time they get the chance to.
To summarize you can't be liquidated for no reason, but if you do it will be certain and instant. This is one of the most important concepts and is where a lot of the “risk” part of leverage is involved. Logically, you might assume if the price of Ether is 100$ USD and you give Vaulty 1 ETH to lock away, you can ask Vaulty to print 100 DAI. This is not true. The reason for this is the possibility that Ether’s value could go down.  For example, if Ether’s price goes down 10%, now there is only 90$ worth of ether locked up for the 100DAI that was created. So instead of being able to draw out 100% of the Ether’s value that you locked up, the MakerDAO organization created a liquidation ratio that limits the amount of DAI you can create before the possibility of being liquidated by someone else. What does that look like?
Imagine 1 ETH is worth 100 USD. To calculate the max amount of DAI you can mint, you can do some basic algebra.
Take the current value of your ETH (100) and divide it by the liquidation ratio of 150% (1.5).
100/1.5 = X. Where X is maximum amount of DAI you can mint.
X = 66.67.
Therefore if you locked up 1 ETH at 100 USD you can draw a maximum of 66.67 DAI before being liquidated.  Liquidation occurs when the ratio goes below 1.5. So let's take a look at the liquidation ratio if the price of ETH goes down by 10% to 90 USD.
Take the current value of the locked ETH (90) and divide it by the amount of DAI you minted (66.67):
90/66.67 = X. Where X is the new liquidation ratio
X= 1.35
1.35 is below the 1.5 liquidation ratio which means the CDP would be liquidated. If, however, the price of ETH goes up 10% to 110 let's take a look at what happens:
110/66.67 = X. Where X is the new liquidation ratio
X= 1.64
1.64 is above the 1.5 liquidation ratio which means the CDP will not be liquidated and in fact, more DAI can be created.
The easiest way to keep track of a healthy CDP is to keep track of the value of ETH. When you create a CDP on MakerDAO and create DAI it will tell you at what price ETH will need to drop to before you get liquidated. If you are ever at risk of being liquidated you can return DAI back to the CDP or lock away more ETH. This is a simple overview of the liquidation process for more detailed information please refer to this post or the official white paper. If you do decide to open a CDP you can also play with the values in the CDP simulator.
To review MakerDAO and DAI gives you the ability to:
    Control your collateral (you own your ETH) and in the future you can choose what type of collateral you’d like to use
    Store your collateral somewhere safe (smart contract)
    Create your own debt by minting DAI
    Free up debt and redeem your locked collateral
    Deal with bad debt through peer enforcement
The simplified version of actually accomplishing this:
    Tell Vaulty you want to open a CDP
    Give Vaulty your collateral (ETH) to lock away
    Tell Vaulty you want to create DAI backed by the collateral you locked up in step 2
    If you want to withdraw your ETH, give Vaulty back DAI
    Make sure you don’t get liquidated by monitoring your liquidation ratio or the price of ETH.If you want to see what this actually looks like in the MakerDAO platform you can access the DAI Dashboard or view the video below.
Earlier I stated that leverage is being able to invest with more money than you actually own. So now the question is how do you do this with MakerDAO and DAI?
Remember, you can only create enough DAI from your CDP so that your position is not liquidated. If you reinvested the DAI to buy more cryptos that would mean you would be investing with less money than if you had just used ETH as your trading pair, but what if you instead used the DAI you created to buy even more ETH?
This is the mind-blowing part. You can lock away your ETH so you can create DAI, then use that DAI to buy more ETH, then lock that ETH away so you can create more DAI, which you use to buy more ETH so you can lock it up to create more DAI, and so on and so forth. Isn’t that incredible? Take a look at the example below to understand what this process looks like and how it can make you more money than just holding. Please note this example is very simplified, in practice it would be hard to do all this manually and without delay to capitalize on price changes.
From the example you can see that you can earn more potential profit from leverage. If we wanted to make even more profit, we could’ve taken the 0.5 ETH we bought with 50 DAI, locked it up into the CDP, created even more DAI, and repeated the steps multiple times. An important thing to note about this strategy is it will not create infinite money or leverage. The reason for this is because the amount of DAI you can create on each cycle is less every time. If you like math, you’ll realize this is actually a finite geometric series. Ian Macalinao wrote a great article where he does the math to check the maximum amount of leverage you can actually create with MakerDAO.
It can be found at https://ian.pw/posts/2018-01-25-maximum-leverage-on-maker.html
The TL;DR is, if you keep reinvesting the DAI you created the maximum leverage you can create without going below the liquidation ratio is 3x. That means if you had 1ETH, you can end up with 3ETH's worth locked up between your CDP and in DAI you created. That being said 3x is not realistic because if the price of ETH goes down even a little you’ll instantly be at risk of being liquidated. A more conservative estimate would be 1.5x-2x.
Here is where risk and reward come into play. Leverage is a double edged sword because it is a multiplier and it works in both directions. When you use leverage to invest you can make more money faster and also lose money faster. The biggest risk of opening a CDP with MakerDAO is being liquidated, and that happens when the value of your collateral goes down (price of ETH). However, the greatest rewards come when the value of your collateral goes up because then you profit more than you would have if you just held.
It’s a balancing act, if you think the price of ETH is going down, then you would not open a CDP and draw DAI to use for leverage at the risk of being liquidated, but if you think the price of ETH is going up, then you could open up a CDP and recursively invest until you have more than what you started and profit more than if you just held. Always remember the golden rule of investing in cryptocurrencies,
“Never invest more than you’re willing to lose.” - Somebody on Reddit, 4chan, or wherever else cryptos are discussed.
The rewards and risks of leverage are clear:
Rewards
    Possibility of greater profit than if you just held.
Risks
    Possibility of losing more money than if you just held.
In the context of using MakerDAO and DAI here are the pros and cons compared to other leverage platforms.
Pros
    Clear and understandable liquidation process
    DAI’s value is predictable
    Ability to profit off of DAI if its value is not 1USD (Arbitrage opportunities)
    Lower longer-term risks than other platforms (does not affect future ability to use platform)
    Decentralized
    Very low interest fee
Cons
    Currently can only use ETH for collateral
    Current process is complex
    Lower maximum leverage than other platforms
    Liquidation is certain and instant
    More volatile collateral type
The last thing I want to write about is that MakerDAO and the process of creating DAI can be used for more uses than just leverage. MakerDAO gives you the ability to be your own bank. That means anywhere you need a low interest loan or a stable coin you can use DAI, leverage is just one use case. Please check out this medium article created by MakerDAO to get more ideas of how you can use MakerDAO.
If you decide to use MakerDAO for leverage I wish you the best of luck, but please remember.
"With great power comes great responsibility" - Uncle Ben (Spiderman)
- Erick Kusnadi
Yes. Interest, which Maker calls a Governance Fee, is compounded continuously at a rate of 0.5%, and is measured against the total DAI currently drawn on your CDP. The outstanding balance owed on a CDP is shown in the Governance Debt column on the Dai Dashboard.
When you pay down your debt (by returning DAI to your CDP) you will be charged accrued interest proportional to the amount of DAI being returned, which is payable in MKR. In this context, the MKR token is required to use a feature of the system, and thus behaves as a utility token.
It's important to ensure you have enough MKR in your wallet to cover the interest charges or the transaction will fail.
Given that:
    A CDP exists with a Stability Debt of 1000 DAI
    The CDP has been open for 30 days
    The current value of a MKR token is 100 DAI
    The Governance Fee is 0.5%
    A user pays back a debt of 50 DAI
The total MKR required to complete the transaction is 0.020547945
You can use the following simplified formula to determine how much interest has accrued on a CDP:
(((Total Stability Debt in DAI * (1 + Current Governance Fee in decimal format)) ^ (Age of Stability Debt in days/365)) - Total Stability Debt in DAI ) = Total Governance Debt owed in DAI
When we plug in the values we've already used above:
(1000 * (1 + 0.005) ^ (30÷365)) - 1000 = 0.410018954 DAI
Now that we have the total interest in DAI we can convert that to MKR. Assuming an exchange rate where 1 MKR is worth 100 DAI:
0.410958904 ÷ 100 = 0.004109589 MKR
Therefore, as the user is repaying 50 DAI, they will be expected to pay the interest accrued on that amount:
(50 * (1 + 0.005) ^ (30÷365)) - 50 = 0.020500948 DAI
The DAI value converted to the current price of MKR according to the Oracle feeds will be:
0.020500948 ÷ 100 = 0.000205009 MKR
The user will need 0.000205009 MKR in their wallet to cover the accrued interest on 50 DAI after 30 days.
After the transaction has been completed, the total amount of interest remaining in the CDP will be:
0.004109589 - 0.000205009 = 0.00390458 MKR
Note that users are not required to perform these calculations. The total outstanding interest fee is always shown in the Governance Debt column on the Dai Dashboard, and the proportional amount owing is displayed when users return DAI to their positions.
No. In a future iteration of the system called Multi Collateral Dai, accrued interest will automatically be withdrawn from funded CDPs. This fee will then be used to purchase MKR on the open market, which will then be burnt.

4 Articles

VIEW ALL
logoremix
RECENT ARTICLES
Remixd is an npm module. Its purpose is to give the remix web application access to a folder from your local computer.
The code of Remixd can be checked out here .
Remixd can be globally installed using the following command: npm install -g remixd
Then remixd -s <absolute-path-to-the-shared-folder> will start Remixd and share the given folder.
The folder is shared using a websocket connection between Remix IDE and Remixd.
Be sure the user executing Remix has read/write permission on the folder.
From Remix IDE, you will need to activate the connection.
Click on the localhost connection icon:
A modal dialog will ask confirmation
Accepting this dialog will start a session. Once the connection is made, the status will update and the connection icon should shows up in green.
Hovering the icon will give more connection status information.
At this point if the connection is successful, the shared folder will be available in the file explorer.
The ultimate goal of this tutorial is to debug transactions that have been created by a dapp front end.
It is easy in Remix to debug a transaction created from its own GUI. However, setting up an environment that allows you to debug transactions created outside of Remix, require a bit more of complexity.
We will need four tools for that :
    Geth - this is the center piece and provides the blockchain environment. We will basically run geth in a dev mode.
    Mist - this is the Ethereum dapp browser. We will use it to browse our front end.
    Remix - this is the Ethereum IDE. We will use it to develop our Solidity contract.
    Any code editor you want - in order to write your front end :)
Install Mist
Mist is the Ethereum browser and the entry point of a Dapp.
Please download the latest version (at least 0.8.9).
Basically we will always run our front end in Mist (note that it is also possible to use Metamask).
Install Geth
Geth is the official Ethereum client.
Run Geth
We will run a test node. This node will have a new empty state and will not be synced to the main or ropsten network.
<test-chain-directory> is the folder where keys and chain data will be stored.
- -ipcPath defines the end point that other apps (like Mist) use to talk to geth.
- -datadir specifies the data directory.
- -dev sets the node into private chain mode and adds some debugging flags.
Then we need to create accounts and mine a bit to generate some Ether:
Next time we run Geth, we will only need to mine transactions (no need to recreate account).
Run Mist
If we run Mist without any argument, its internal Geth node will run. As we have our own we need to specify the ipc path of the node installed above.
(yes the option is –rpc)
Once Mist is started, verify that it is connected to the test node (that’s very important!!).
On the bottom left, check that the network is Private-net and that the block number is the same as reported by the test node we are currently running. Run the following command in the Geth Console to check: web3.eth.blockNumber.
Clicking on Wallet will allow you to send transactions and check account balances (if you are currently mining you should see the balance increasing).
In Mist click on Develop / Open Remix IDE
Remix will open in a new window. If this is the first time it is run, the Ballot contract will be loaded.
Now, we need to check if Remix is connected to Mist:
Right panel / third tab from the left, Injected Provider should be checked.
Right panel / second tab from the left, Transaction Origin should contain accounts we have previously created in Geth.
Donation contract - Dapp Back end
Here is a sample solidity contract.
Copy and paste the following inside remix:
Dapp Front end
and here is the front end:
I would suggest serving this file using http-serve, but you can use any web server you like.
Example: Dapp Front End https://github.com/ltfschoen/dapp_front_end
Important notice !
The variable contractspec contains the abi of the donation contract. This means that if you change something in the contract interface (function names, parameters, …) you need to copy the new abi from remix to the front end.
Right panel / Red button Create
This creates a new transaction that deploys the Donation contract (Mist will ask for the usual passphrase check).
Wait for the transaction to be mined (don’t forget to activate mining miner.start()). Once this is done, you can use it by executing the moveFund and donate function. But this is not what we want to achieve. We want to run and debug those functions from the front end.
Remix also display the address of the contract. Save it, we’ll need this address later.
From Mist, browse the above front end. In the first field, paste the address of the newly created contract. Now, let’s call the first function (label give).
You will need an account and a value.
The account could be any account that is declared in the Wallet section of Mist. This is the sender of the transaction that we are going to create. The value should be no more than the actual balance of the account - the unit is in wei, so just put 100 (100 wei), that should be fine.
Click on Give and wait for the transaction to be mined.
The HTML block with id log is filled by all the transactions created from the front end. It was easier for the purpose of this tutorial to just log transactions in a div but you can have your own logging mechanism.
There is only one field that we need, this is the transactionHash.
Copy it and switch to Remix. On the right side, the fifth panel shows a small “bug” icon, that is the debugger.
Paste the hash into the transaction field and click on the play button.
You are now entering a debug session for the call to donate.
Debugging in Remix is easier than with common tools like gdb because you can freely move in time. Use the slider to change the current step and click on the panels below to expand them and explore the curret state, local variables, etc. There are also breakpoints to move between sections of the code quickly, but more on all that later.
At the time of this writing, there is an issue that could break the contract creation. The a workaround for that at https://github.com/ethereum/go-ethereum/issues/3653 . Please follow the workaround or wait for this issue to be closed.
Also, although retrieving a contract’s storage when Remix is using the JavaScript VM is working well, there is still work to be done when Remix is using eth or geth as backend.

4 Articles

VIEW ALL
logotoshi
RECENT ARTICLES
Toshi Dev is a version of the Toshi client that provides a testing environment for use by developers of Toshi bots & apps. It runs on Ropsten testnet and will gain support for further test environments in the future.
    Using your Android device, navigate to the latest Toshi Dev Android release on GitHub
    Tap the APK file in the Downloads section
    Follow the install prompts
To install an app from outside of the Play Store, you will need to allow apps from unknown sources as follows:
    Open the device settings. Look for a gear icon in the notification shade near the top left corner and tap on it.
    Scroll down to the Security section and tap to open it.
    Scroll down to the entry labeled Unknown sources and read the subtext
    Read the pop-up box and tap Ok to enable the setting.
You can read more about this process and the implications here: https://www.androidcentral.com/unknown-sources
Toshi contains a Webview into which a web3.js instance is injected and hooked into your Toshi account. When developing a DApp, you can treat it just like any other web3.js instance - there is no Toshi-specific functionality.
If you're not sure where to start with DApp development, we recommend Truffle
DApps can be launched from the Browse screen by typing the URL into the search bar.
You can also create buttons or menu items that open an embedded webview. Webview buttons have an action property instead of a value.
The action property should begin with Webview:: followed by the URL to open.

4 Articles

VIEW ALL
logozeppelin
RECENT ARTICLES
The effect of having a market cap north of $10 Billion USD is that a growing number of blockchain enthusiasts trust putting their Ether only in smart contracts that have been vouched and fine-combed by security professionals.
Among the emerging best practices, the most recommended are to write extensive unit tests, have the code audited by specialists and set up a bug bounty program. I won’t elaborate on the first two recommendations as they deserve entire blog posts on their own, but in this blog post you will learn about how to setup bug bounty programs for your smart contracts.
The advantage of setting up bug bounty program is that security researchers from all over the world are incentivized to have a go at hacking your smart contract for a period of time. If the smart contract is broken into, the researcher collects Ether and you learn where the vulnerability lies in your code.
Another upside is that the process is able to be fully automated on the Ethereum blockchain and with the Bounty smart contract from the OpenZeppelin library, any blockchain developer is able to set up a bug bounty program within a reasonable amount of time. Let’s see how this is achieved.
First off, let’s bootstrap the project using Truffle.
Next step is to add the OpenZeppelin library.
This adds the zeppelin-solidity folder to node_modules and in it you will find all smart contract templates from the OpenZeppelin library.
For this project we only need Bouncty.sol, SafeMath.sol, Ownable.sol, PullPayment.sol and Destructable.sol. If you just want to jump to the code, this is the repo where it resides: https://github.com/gustavoguimaraes/bug-bounty .
Moving on.
To set up a bug bounty program we need a smart contract that others will try to break. Let’s code up a smart contract that locks a user’s ether for any amount of time in the future.
And include the following contract:
The LockYourEther contract keeps track of the User in a mapping hash function which has access to a value and releaseDate . A User is able to lockFundsUntil a date in the future when it is able to withdraw the Ether from the contract (and hope that Ether will triple in value by then).
Now onto setting up the bug bounty program. This is the high level procedure:
    Create a bounty contract that inherits from OpenZeppelin’s Bounty.sol and have a deployContract() function which has to return a new contract address every time. In our case, we will return the LockYourEther contract address.
    Have LockYourEther inherit from Target contract found in OpenZeppelin’s Bounty.sol . Add another function to LockYourEther called checkInvariant() which checks state variables within the contract. These must be true at all times. That is to say that you need to check if the contract state remains as intended. Example of implementations of checkInvariant() could be: checking if the total supply of all tokens equals the number of tokens that handed out on a token crowdsale, whether the timestamp of a variable in the contract is > now and so on and so forth.
    Deploy the contracts to the blockchain.
    Set the Bounty reward.
Let’s create the Bounty contract:
Firstly, we override the Bounty contract function deployContract function with our own so as to instantiate LockYourEther version for the bounty program for us.
Next, we include checkInvariant() in LockYourEther and ensure that it derives from the Target contract found at Bounty.sol.
Here we are checking if the total Ether value from balances must match the state variable totalLockedWei . We know that if these are not equal the contract is not storing the ether or withdrawing as it should.
Now for the deployment:
In migrations/2_deploy_contracts.js flesh it out with the JavaScript that lets Truffle deploy the contracts:
Run the Truffle command to the desired Ethereum blockchain of your choice: kovan or ropsten which are test nets (For n00bs out there, these are examples of test nets that we can deploy and test our contracts on decentralized environments), or main net for the actual bug bounty program.
Lastly, set the reward for the bounty program.
Using truffle console:
Voilá, the bug bounty program is setup.
I purposely left a bug in the LockYourEther. Are you able to find it and get the bounty reward?
Give it a try, I will give you a few minutes …
If you have found it, great! You got an eye for security breaches in smart contracts (this is a link for you). If you jumped to this section, no worries. The more exposure you get to this, the better it becomes.
So let's find the bug in LockYourEther contract and collect the bounty. For this, we are going to interact with the contract.
From truffle console:
Set ourselves as researchers of this bug bounty program and setup the contract instance we will be hacking:
Then, interact with the target contract.
Check if all is okay with the contract:
So far, so good. Let’s send it some more Ether with the same researcher address:
Now calling checkingInvariant once more:
Ha! We found the bug. The contract permits users to override their data. If you pay attention to the lockFundsUntil() function , line 19, you see that we are only checking if _releadeDate > now. A user could just keep calling this function over and over and modifying its balances value. To fix this bug we would need to create another check such as require(balance[msg.sender.value == 0) so that an address is of balance 0 before locking any funds.
We deserve some Ether. Let’s claim the reward.
There we go.
If there happened to have no researcher to breach the contract, the creator of the contract could retrieve the bounty reward as such:
We saw here how to setup a bug bounty contract using the OpenZeppelin smart contract library. Traditionally bounty sites are non standardized, and its process is manual and can cause disputes such as who claimed first and whether the claim is legitimate. With smart contracts and the help of the OpenZeppellin library, smart contract owners can post their smart contract (target contract) as well as another contract which checks whether the contract can be hackable or not (invariant contract) with some rewards of Ether if it is hackable. Any security researchers can submit their exploit contract to prove that it can hack the contract. Once the hack is proved, the security researcher can get reward automatically. Or if no bug is found the creator can destroy the bounty contract and recover the invested reward.
The code for the smart contracts can be found at: https://github.com/gustavoguimaraes/bug-bounty
Hope this has helped you understand more about smart contract security.
Thanks for Francisco GiordanoManuel Aráoz and Demian Brener for reviewing this blog post before publication.
As mentioned in our Development Roadmap Part Two, the Kernel is the foundational layer of zeppelin_os, and we will soon be launching a prototype of it, starting with the functionality currently found in the OpenZeppelin framework.
We’re happy to announce another step towards launching the zeppelin_os Kernel. We’re now investigating different upgradeability mechanisms. As you may have read, there are several approaches to implementing contract upgradeability, like proxy libraries or eternal storage, among others. We’ve been working on a solution that combines some of these patterns.
The approach consists in having a Proxy that delegates calls to specific implementations which can be upgraded, assuming that the storage structure won’t ever change. This scenario is referred to as “Eternal Storage”. Let’s see how the Proxy contract looks like:
As you can see, given the proxy uses delegatecall to resolve the requested behaviors, the upgradeable contract’s state will be stored in the proxy contract itself.
Let’s analyze how this would work by building an upgradeable ERC20 token contract. To do this, we will need to manage two really different kinds of data, one related to the upgradeability mechanism and another strictly related to the token contract domain. Naming plays a really important role here if we want to express correctly what’s going on. This is the proposed model:
Proxy, UpgradeabilityProxy, and UpgradeabilityStorage are generic contracts that can be used to implement upgradeability through proxies. In this example we use them to implement an upgradeable ERC20 token:
The UpradeabilityStorage contract holds data needed for upgradeability, while the TokenStorage contract holds token-related information. It defines the token-specific storage:
On the other hand, TokenProxy extends from UpgradeabilityProxy (which in turn extends from UpgreabilityStorage), and then from the TokenStorage contract:
TokenProxy is the contract that will delegate calls to specific implementations of the ERC20 token behavior. These behaviors are the code that can be upgraded by the token developer, for example Token_V0 and Token_v1
As you can see, token behavior implementations extends from UpgradeableTokenStorage, which derives from UpgradeableTokenStorage and TokenStorage. This is what every implementation of the upgradeable behavior needs:
Notice that inheritance order in TokenProxy needs to be the same as the one in UpgradeableTokenStorage, to respect storage structure (given we are using delegatecall). Moreover, we are not defining any new state variables in the token behavior implementation contracts. This is a requirement of the proposed approach to ensure the proxy storage is not messed up.
Thanks to the Winding Tree and Aragon teams for their collaboration on this research and development.
Join Our Community:
+ Chat with the team and community on our Slack channel + Follow Zeppelin on Twitter + Read the whitepaper

3 Articles

VIEW ALL