# Overview
The purpose of this document is to provide detailed instructions for building a decentralized, autonomous organization (DAO) using the principles and approach described in the paper [On-Chain Governance of Decentralized Autonomous Organizations (Craig Calcaterra, 2018)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3188374).
A [prototype of this system](https://gitea.dgov.io/DGF/dgf-prototype) has been implemented in Solidity and JavaScript. This specification will be derived from that prototype, and generalized in such a way that it can be implemented using an alternative technology stack, such as Casper.
## Decentralized Autonomous Organization
### Organization
- a group of persons organized for some end or work; association
([dictionary.com](https://www.dictionary.com/browse/organization))
In our model, a DAO is comprised of a group of experts who want to be able to present a united front. They will collaborate to define the rules by which the organization is to be governed, and by which customers may engage the expertise of the DAO.
### Autonomous
- self-governing; independent; subject to its own laws only.
- having autonomy; not subject to control from outside; independent
- (of a machine, device, etc.) able to operate with little or no human control or intervention
([dictionary.com](https://www.dictionary.com/browse/autonomous))
The rules of the DAO are to be implemented as code, and executed automatically, without the need for human intervention.
### Decentralized
- (of currency) not controlled or distributed by a government, bank, or other third party, as bitcoin and some other digital currencies
([dictionary.com](https://www.dictionary.com/browse/decentralized))
The code which implements the rules of the DAO is to be run by multipe parties who each verify one another's results.
# Terminology
| Term | Definition |
| --- | --- |
| DAO | Decentralized Autonomous Organization (see [Overview](./index.md)) |
| DGF | [DAO Governance Framework](https://daogovernanceframework.com/wiki/DAO_Governance_Framework) |
| Casper | A block chain supporting contracts and native fungible currency |
| CSPR | The native fungible currency of the Casper block chain |
| Ethereum | A block chain supporting contracts and native fungible currency |
| ETH | The native fungible currency of the Ethereum block chain |
| Matrix | A federated communications platform |
| Synapse | The reference Matrix server implementation, including support for federation |
| Element-web | The reference Matrix front-end implementation |
| Homeserver | A Matrix homeserver running Synapse or equivalent |
| Worker | A Matrix user with a Blockchain Wallet. May stake REP, and earn REP and CSPR/ETH. |
| Customer | A user with a Blockchain Wallet. Pays to engage a work contract. |
| Staking Client | An application that listens for validation pools, performs validation and stakes for/against the pool. |
| Reputation (REP) | A non-transferable ERC20 token representing the results of validation pools within a given expertise. |
| Forum Post | A signed contribution with weighted citations |
| Validation Pool (VP) | Takes CSPR/ETH and author stakes as input. Requires REP-weighted consensus. Mints and distributes REP; distributes CSPR/ETH. |
| Work Evidence (WEV) | A forum post representing work that fulfills some work request(s) |
| Work Smart Contract (WSC) | A contract that takes REP stakes from workers and CSPR/ETH from customers, and puts them toward a validation pool (VP) targeting work evidence (WEV). |
| Proposal | A Post representing some proposed action or change, to be reviewed and approved/rejected by the DAO. |
| Attestation | Assertion by a DAO member that they are aware of a given Proposal |
| Referendum | An instance of a Validation Pool targeting a given Proposal |
# Requirements
## Governance
We identify three aspects of governence: Executive, Legislative, and Judicial. Executive governance is focused on the present, day to day operations of a DAO. Legislative governance is focused on the future, and deals with the process of making changes to the operations of a DAO. Judicial governance is focused on the past, providing an opportunity for a DAO to review and reinterpret past actions.
### Core Contracts
The key insight of [On-Chain Governance of Decentralized Autonomous Organizations (Craig Calcaterra, 2018)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3188374) is to use Reputation as the primary incentive mechanism for DAO members, rather than relying on fungible currency alone as the representation of a DAO member's power.
Validation Pools mint and award Reputation (REP). REP can be used for staking for/against Validation Pools or staking availability to perform work, and entitles the holder to a share of DAO revenues in proportion to their REP balance.
#### Reputation
1. The Reputation contract must be able to associate a non-negative numeric value with a given wallet address or contract address.
1. The value associated with a given wallet address may be modified only by the results of a Validation Pool (explained below). The Validation Pool must be able to execute the following operations
1. Mint: Increase the value associated with a given wallet address
1. Burn: Decrease the value associated with a given wallet address
1. Update (a.k.a. Transfer): Decrease the value associated with one wallet address, and increase the value associated with another address by the same amount.
1. A Reputation holder must not be able to transfer Reputation to any other account.
1. A Reputation holder must be able to stake some or all of their Reputation for or against a Validation Pool (explained below).
1. A Reputation holder must be able to delegate permission to another account to stake a given amount of Reputation on their behalf.
#### Bench of Experts
The contract housing the Validation Pools can be thought of as a Bench of Experts.
These experts sit ready to receive submissions and render a decision on each.
The experts will stake their reputation on the soundness of their judgements.
1. Anyone may initiate a Validation Pool
1. A Validation Pool may be initated with or without a fee
1. Reputation (REP) is minted in proportion to the submitted fee. If no fee is included, no REP should be minted.
1. Half of the minted REP is staked in favor of the VP
1. Half of the minted REP is staked against the VP
1. A Validation Pool must include the following parameters
1. Quorum (Between 1/10 and 1)
1. For the Quorum to be met, the total amount of REP staked for and against the VP, divided by the total available REP in the DAO, must be greater than or equal to this ratio.
1. Quorum must be greater than or equal to a minimum value, such as 1/10, in order to prevent validation pools from being pushed through without sufficient participation.
1. Win Ratio (between 0 and 1)
1. For a VP to be accepted, the amount of REP staked in favor, divided by the total amount of REP staked for and against the VP, must be greater than or equal to this ratio.
1. Binding Percent (between 0 and 100%)
1. This represents the amount of staked REP that may be lost if staked on the losing side of a VP. 0% Binding means that no staked REP may be lost. 100% Binding means that all staked REP may be lost. A value between these extremes means that a fraction of staked REP may be lost.
1. Redistribute Losing Stakes (boolean)
1. If Redistribute Losing Stakes is true, then the Binding % of REP staked on the losing side of the VP is distributed among those who staked on the winning side, in proportion to their stakes. If Redistribute Losing Stakes is false, then the Binding % of REP staked on the losing side of the VP is burned rather than being redistributed.
1. Target Forum Post (explained in the Judicial governance section)
1. The Target Forum Post represents the subject of the Validation Pool.
1. A DAO member may stake Reputation for or against a Validation Pool after the pool is initiated and before the duration elapses
1. Once the duration has elapsed, the outcome of the VP may be evaluated.
1. If the Validation Pool is accepted,
1. If Redistribute Losing Stakes is true, Binding Percent of losing stakes shall be distributed among DAO members who staked in favor of the VP, in proportion to their stakes.
1. If Redistribute Losing Stakes is false, Binding Percent of losing stakes shall be burned rather than redistributed among the winners.
1. The half of the minted REP that was staked in favor of the VP is awarded to the Target Forum Post.
1. If the Validation Pool is rejected, and Redistribute Losing Stakes is true, losing stakes as well as the half of the minted REP that was staked against the VP shall be distributed among DAO members who staked against of the VP, in proportion to their stakes.
1. After the Validation Pool concludes, the fee provided by the Customer shall be distributed among all DAO members (Workers) in proportion to their REP balance.
### Executive
The day to day operations of a DAO are centered around Work Smart Contracts (WSC) and Validation Pools (VPs). Customers request work; the work is assigned to an available worker; the worker submits Work Evidence (WEV); and the Work Evidence is validated by the rest of the DAO in a Validation Pool.
#### Work Smart Contracts
1. A Worker may stake reputation toward a Work Contract (WSC), representing their availability to perform the work.
1. This availability stake should specify the duration of their availability window.
1. A Customer may submit a request for work to the WSC, including a fee and any necessary request details.
1. The work must be assigned to an available worker
1. The worker may be chosen by random weighted selection, weighted by the amount of REP each worker staked toward their availability.
1. The assigned Worker must submit a Work Evidence Post to the WSC, providing any necessary supporting information to verify that the work was performed correctly.
1. The Customer must submit approval/disapproval of the work to the WSC.
1. The WSC must initiate a Validation Pool targeting the Work Evidence Post.
1. This Validation Pool may target a single WEV Post, or multile WEV Posts (see Rollup section, below).
1. The fee from the Customer should be included when initiating this VP. The VP mints Reputation based on the provided fee.
1. The Staking Clients must verify the work evidence, and stake for/against the Validation Pool targeting the Work Evidence Post.
1. If the VP is approved, the minted Reputation is awarded to the Worker who submitted the Work Evidence.
1. The VP then distributes the fee among all DAO members, in proportion to their Reputation balances.
Note that the Worker does not directly receive the fee for the work they perform. Instead, they receive Reputation; then, based on their Reputation balance, they receive a fraction of all future fees sent to the DAO. The purpose of this is to incentivize long-term considerations and investment in the future of the DAO. The more REP a Worker earns, the more they get payed over time, as the DAO takes in revenue.
### Legislative
The DAO will need to be able to update the rules by which it operates, in order to respond to changing circumstances or goals. There will not always be unanimous consensus regarding what changes to make. Therefore, we need a legislative governance process that a DAO can use in order to progress from disagreement to agreement.
To achieve such a process, we introduce a Proposal mechanism. The proposal must first reach a certain level of Attestation; then it must progress through a series of Referenda. If all Referenda are accepted, then the Proposal is accepted; otherwise the Proposal is rejected.
#### Proposals
1. Anyone may submit a Proposal
1. Note that, if desired, this requirement could be strengthened such that only a DAO member may submit a Proposal
1. A Proposal may include a callback, to be executed when and if the Proposal is accepted. This callback may also include opaque data to be passed to the callback when executed.
1. A DAO member may attest a certain amount of REP to indicate that they are aware of the proposal. The amount must be less than or equal to the DAO member's REP balance.
1. Once the Proposal has reached 10% Attestation, meaning that 10% of the DAO's total supply of REP has been attested, the first Referendum shall be initiated. This referendum should be a Validation Pool that is 0% binding, with a quorum of 1/10 and a win ratio of 2/3.
1. If the Referendum does not meet quorum, then the Proposal is failed.
1. If the Referendum is rejected or does not meet a 50% participation rate, then the Referendum may be retried up to 3 times.
1. If the first Referendum is accepted and meets a 50% participation rate, then a second Referendum shall be initiated. This referendum should be a Validation Pool that is 1% binding, with a quorum of 1/10 and a win ratio of 2/3.
1. If the Referendum does not meet quorum, then the Proposal is failed.
1. If the Referendum is rejected or does not meet a 50% participation rate, then the Referendum may be retried up to 3 times.
1. If the second Referendum is accepted and meets a 50% participation rate, then a third Referendum shall be initiated. This referendum should be a Validation Pool that is 100% binding, with a quorum of 1/10 and a win ratio of 2/3.
1. If the Referendum does not meet quorum, then the Proposal is failed.
1. If the Referendum does not meet a 50% participation rate, then the Referendum may be retried up to 3 times.
1. If the Referendum is rejected, then the Proposal is failed.
1. If the third Referendum is accepted and meets a 50% participation rate, then the Proposal is accepted.
1. If provided, the callback should be executed. This can be used, for example, to update parameter values of a smart contract.
### Judicial
In the Executive governance section we outline how the DAO polices the REP minting process, and the Legislative governance section we outline how the DAO may modify the rules by which it operates. Now, we need to consider that as the DAO develops new rules, it may wish to reevaluate past REP rewards in light of new perspectives.
To achieve such reevaluation, we introduce the Forum reference mechanism. The Forum is a collection of Posts. A Post has a unique ID and one or more authors. A Post may also include weighted references to other Posts. Each Validation Pool targets a given Post. When a VP is accepted, the minted REP percolates through the Forum, to the author(s) of the targeted Post, and recursively to the Posts referenced by the targeted Post, the Posts referenced by those Posts, and so on, up to a limit determined by the Reference Chain Limit parameter.
Each reference may be positive or negative. A positive reference "donates" Reputation, while a negative reference "leaches" reputation.
A Post may also reference the Incinerator. Any reputation donated to the Incinerator is burned. A Post may not leach reputation from the Incinerator.
#### Forum
1. Anyone may add a Post to the Forum
1. A Post must have a unique identifier.
1. The Post ID should be a content hash.
1. The Post ID should correspond to an off-chain record housing the Post's content.
1. A Post must have one or more authors.
1. Each author is identified by their Wallet address.
1. Each author has a weight. Author weights must sum to 100%.
1. A Post may include zero or more references.
1. Each reference must include a weight between -1 and 1.
1. Sum of negative weights must be >= -1.
1. Sum of positive weights must be <= 1.
1. A Post may reference the Incinerator with 0 <= weight <= 1.
This Forum reference mechanism enables executing any conceivable change in the REP awarded to Posts and their authors.
1. When a Validation Pool targeting a given Post is accepted,
1. The REP that was minted and staked in favor of the VP is transferred to the target Post.
1. For each Post referenced by the target Post, a fraction of the incoming Reputation given by the weight of that reference, is transferred to the referenced Post; and so on, recursively, until the Reference Chain Limit is reached.
1. Positve references donate REP
1. Negative references leach REP
1. Negative references have the power to undo the effects of prior references, but a negative reference may not cause a Post to lose more REP than it had previously gained.
1. Remaining Reputation after donation and leaching, is transferred to the authors of the Post in proportion to their author weights.
1. A Post does not retain ownership of any REP
1. The REP value of a Post is defined as the amount of Reputation that its authors have gained via that Post.
## Rollup
As described above, in order for REP and fees to be distributed to DAO members, an on-chain Validation Pool must be executed. However, network gas fees must be payed every time a contract is called. Therefore a DAO may wish to batch multiple Posts and the Validation Pools targeting those Posts, into one consolidated Rollup Post and a single Validation Pool targeting that Rollup Post. To accomplish this, we introduce a Rollup contract.
The Rollup contract can be thought of as a specialized form of Work Contract (WSC), as it uses the same Availability stakes mechanism to select a Batch Worker.
1. When the Rollup contract is deployed, a Batch Interval must be specified.
1. A Work Contract may call the Rollup contract to add an item to the batch queue.
1. The fee that would have gone toward the VP, goes to the Rollup contract instead.
1. The Worker availability stakes that would have gone toward the VP, go to the Rollup contract instead.
1. A Worker may stake REP to register their availability to be the next Batch Worker.
1. Once the Batch Interval has elapsed, the current Batch Worker must add a Rollup Post to the Forum and call the Rollup contract to initiate a Validation Pool targeting the Rollup Post.
1. Only the current Batch Worker may submit the next Rollup batch.
1. If there is no current Batch Worker assigned, then anyone may submit the next Rollup batch.
1. When the batch is submitted,
1. Rollup contract initiates a Validation Pool targeting the Rollup Post.
1. The fees that were included with each batch go toward the Rollup VP.
1. The REP stakes that were included with each batch go toward the Rollup VP.
1. The next Batch Worker is selected by random weighted selection from among the Batch Worker availability stakes.
1. If there are no Batch Worker availability stakes, the transaction reverts, so the VP is not initiated.
1. If the current Batch Worker fails to submit the next Rollup batch before the Batch Interval plus a grace period elapses,
1. A Validation Pool should be initiated with no fee
1. The Batch Worker's availability stake should be staked in favor of the VP
1. A new Batch Worker must be selected
1. The DAO members should stake against the VP, in order to punish the Batch Worker for failing to complete their work
In this requirements section, we omit any details of the mechanisms for implementing the necessary off-chain validation that leads to the production and verification of the Rollup Post. We will provide those details in the [System Design](./system-design.md) section.
# System Design
In the [Requirements](./requirements.md) section, we identified the need for the following smart contracts: Reputation, Bench, Forum, Work, Proposal, and Rollup.
We also identified the need for a mechanism for coordinating Rollup Post validation. To address this need, we introduce [Matrix](https://matrix.org), a federated messaging protocol. Our application uses the Client-Server protocol to communicate with a Matrix Homeserver.
## Contracts
The following is a dependency graph, where the arrows represent one contract calling another.
```mermaid
flowchart BT
subgraph Core Contracts
Reputation
Bench
Forum
end
subgraph Business Logic
Work
Proposal
Rollup
end
Bench --> Reputation
Proposal --> Bench
Proposal --> Reputation
Work --> Reputation
Work --> Bench
Work --> Rollup
Work --> Proposal
Forum --> Reputation
Bench --> Forum
Rollup --> Bench
```
Reputation, Forum, and Bench can be considered core contracts. Together they provide the necessary primitives for a DAO to carry out its business.
Work, Proposal, and Rollup can be considered business logic. They allow the DAO to support arbitrarily complex use cases, according to its needs.
[Future work](./future-work.md) may include utilizing the process defined by the Proposal contract to govern features of the core contracts themselves.
### Reputation
We can achieve the requirements of the Reputation contract as follows:
1. Reputation may be implemented as an ERC20 token contract.
1. `transfer` and `transferFrom` methods must be disabled, so that REP may not be transferred.
1. Reputation internal methods (`mint`, `burn`, `update`) may be called only by the Bench and Forum contracts.
### Bench
To achieve the Bench requirements, the contract must do the following:
1. Define a minimum quorum
1. Define a minimum and maximum VP duration
1. Keep a record of Validation Pools
1. Implement a method for initiating a Validation Pool (VP)
1. This should be a payable contract call. The value transferred is the fee for this VP.
1. The VP shall mint an amount of REP equal to `valueTransferred * mintingRatio`
1. **`mintingRatio`** may be set statically, or may be taken as a parameter when initiating a VP. Taking `mintingRatio` as a parameter enables greater flexibility, but increases overhead cost per transaction. This makes `mintingRatio` a good candidate for being governed by a Proposal process, outlined in [Future Work](./future-work.md).
1. Half of the minted REP shall be staked in favor of the VP, and the other half shall be staked against the VP.
1. This ratio could be taken as a parameter or governed by a Proposal to increase the flexibility of the DAO; see [Future Work](./future-work.md).
1. Implement a method for receiving REP stakes for/against the VP
1. Stake should be rejected if the VP `duration` has already elapsed.
1. Staking REP means that a DAO member makes an allowance for the given amount of REP to be withdrawn from their balance. The amount of the shall be recorded along with the boolean `inFavor`, but the REP is not to be withdraws from the sender's balance until certain conditions are met during the evaluation of the VP outcome (explained below).
1. Implement a method for evaluating the outcome of a Validation Pool
1. Outcome may not be evaluated until VP `duration` has elapsed
1. An exception can be made if `totalStakedFor + totalStakedAgainst == totalSupply`. In thise case the DAO is all-in, and there's no reason to wait before evaluating the outcome.
1. The quorum is met if `(totalStakedFor + totalStakedAgainst) * quorum[denominator] >= totalSupply * quorum[numerator]`
1. The vote passes if `totalStakedFor * winRatio[denominator] >= (totalStakedFor + totalStakedAgainst) * winRatio[numerator]`
1. If the vote passes and the quorum is met,
1. If `redistributeLosingStakes` is true, then `(bindingPercent / 100) * totalStakedAgainst` shall be distributed among the accounts who staked against the VP, in proportion to their stakes.
1. The REP that was staked in favor of the VP during its initiation, shall be transferred to the Target Post, and propagated via the Forum Reference mechanism to the authors of the Post and its referenced Posts.
1. If provided, `callbackOnValidate` should be executed, and should be passed the results of the VP.
**`totalSupply`** refers to the total amount of REP held by all DAO members.
**`InitiateValidationPool`** Parameters
| Name | Type |
| --- | --- |
| `postId` | string identifying the Target Post |
| `duration` | positive integer number of seconds |
| `quorum` | integer numerator, integer denominator |
| `winRatio` | integer numerator, integer denominator |
| `bindingPercent` | integer |
| `redistributeLosingStakes` | boolean |
| `callbackOnValidate` | function(`ValidationPoolResult`, `callbackData`) | Optional callback to be executed when the VP is concluded |
| `callbackData` | bytes | Opaque data to be passed back to `callbackOnValidate` |
**`ValdiationPoolResult`** Fields
| Name | Type |
| --- | --- |
| `sender` | wallet address |
| `votePasses` | boolean |
| `quorumMet` | boolean |
#### Test Cases
A set of [test cases for the Bench contract](https://gitea.dgov.io/DGF/dgf-prototype/src/branch/main/ethereum/test/ValidationPools.js) can be found in the Solidity prototype implementation.
### Forum
To achieve the Forum requirements, the contract must do the following:
1. Keep a record of Posts, indexed by Post ID
1. Implement a method to add a Post
1. Implement a recursive method to distribute Reputation to a Post's references and authors.
1. This method must be called only by the Bench, when a Validation Pool is accepted.
**`AddPost`** Parameters
| Name | Type |
| --- | --- |
| `postId` | string |
| `authors` | Array<`AuthorWeight`> |
| `references` | Array<`ReferenceWeight`> |
**`AuthorWeight`** is an object or tuple with the following fields:
| Name | Type |
| --- | --- |
| `authorAddress` | wallet address |
| `weightPPM` | integer |
**`ReferenceWeight`** is an object or tuple with the following fields:
| Name | Type |
| --- | --- |
| `targetPostId` | string |
| `weightPPM` | integer |
**`PropagateReputation`** Parameters
| Name | Type |
| --- | --- |
| `postId` | string |
| `amount` | integer |
| `initialNegative` | boolean |
| `depth` | integer |
**`PropagateReputation`** Logic
1. `PropagateReputation` is a recursive function.
1. The recursion is initiated by a Validation Pool targeting a given Post.
1. Each time `PropagateReputation` is called, `depth` should be incremented.
1. Negative references "leach" reputation from the target, while positive references "donate" reputation. A Post may include both negative and positive references. Negative references should be processed first, so that a Post may then donate the leached reputation.
1. There are cases where reputation effects are unable to be propagated, due to the following constraints:
1. Post and Author reputations may not drop below zero.
1. A negative reference may at most undo the effects of prior posts, but not reverse them.
1. `depth` may not exceed `depthLimit` (a.k.a. Reference Chain Limit).
`PropagateReputation` should therefore return the amount that was unable to be propagated. We refer to this as a "refund". Subtracting this refund amount from the attempted amount gives the actual amount propagated.
#### Test Cases
A set of [test cases for the Forum contract](https://gitea.dgov.io/DGF/dgf-prototype/src/branch/main/ethereum/test/Forum.js) can be found in the Solidity prototype implementation.
### Proposals
To achieve the Proposals requirements, the contract must do the following:
1. Define an attestation threshold
1. Keep a record of Proposals
1. Implement a method to initiate a Proposal
1. The caller should be able to provide an optional callback to be executed when and if the Proposal is accepted. This can be used, for example, to update parameter values of a smart contract.
1. Implement a method for a DAO member to attest to a Proposal
1. Implement a method to evaluate the attestation for a given Proposal
1. If the attestation threshold is met, begin the referendum process
1. Implement the referendum process
1. Initiate the VP for the current stage referendum
1. Provide a callback to be executed when each referendum VP concludes, that advances the Proposal through the referenda stages according to the requirements.
1. If the Proposal passes all referenda stages, and a callback was provided, the callback should be executed.
### Availability
For convenience, we can define an Availability contract, as a base contract that other contracts may extend. Work contracts as well as the Rollup contract need to use this Availability mechanism.
To achieve the requirements, the Availability contract must do the following:
1. Keep a record of Worker availability stakes
1. Implement a method to accept Worker availability stakes
1. If a Worker submits multiple availability stakes, they may be combined into a single availability stake.
1. Implement a method to select a Worker by random weighted selection, weighted by the amount each Worker staked.
**`StakeAvailability`** Parameters
| Name | Type |
| --- | --- |
| `amount` | integer |
| `duration` | integer |
**`Availability Stake`** Properties
| Name | Type |
| --- | --- |
| `worker` | wallet address |
| `amount` | integer |
| `endTime` | integer |
| `assigned` | boolean |
### Work
To achieve the Work Smart Contract requirements, a work contract must do the following:
1. Inherit from the Availability contract
1. Alternatively, the DAO can use a single Availability contract that is able to interface with multiple Work Contracts. It would need to keep track of the target contract for each availability stake, and allow that contract to make a call to select one of the workers who staked availability for the given contract.
1. Define a price for the work
1. Optionally, implement a method to initate a Proposal to change the price
1. Implement a method for a Customer to request work
1. This should be a payable method
1. Implement a method for a Worker to submit Work Evidence (WEV)
1. Implement a method for a Customer to submit work approval/disapproval
1. Once approval/disapproval is submitted, either initiate a Validation Pool tarageting the WEV, or submit the fee and worker's REP stakes to the Rollup contract instead (explained below).
### Onboarding
The process of adding a new Member to the DAO can be implemented as a Work contract. The Customer is a prospective Member. A work request is a request to be onboarded, and the assigned Worker is responsible for reviewing the onboarding request.
The reviewer submits their review as work evidence. The Onboarding contract initiates a VP targeting this review, including a portion of the fee submitted with the onboarding request. If this VP is approved, then the Onboarding contract initiates a second VP, this time targeting the onboarding request, including the remainder of the fee.
### Rollup
Rather than submit every Post on-chain and conduct every Validation Pool on-chain, it is more efficient to keep a collection of Posts off-chain, and add a single Rollup Post on-chain representing multiple off-chain Posts.
With this Rollup Post, we have the opportunity to attribute credit to multiple authors, with a weight assigned to each author.
The Rollup Post should weight authorship in accordance with the off-chain Validation Pools that have taken place.
To achieve the Rollup requirements, the contract must do the following:
1. Inherit from the Availability contract
1. Keep a queue of items to be batched
1. Implement a method to add an item to the queue of items to be batched
1. This should be a payable method, because it needs to receive the fee that would have been sent to initiate a Validation Pool directly targeting the given Post.
1. The batch item should reference a Forum Post ID. However, the Post itself does NOT need to be stored on-chain. It is sufficient for the Post to be available off-chain, as long as the Batch Worker and Validating Clients are able to retrieve it.
1. Implement a method for the current Batch Worker to initiate a Validation Pool targeting a Rollup Post that represents items from the batch queue.
1. Items must be submitted in order without skipping any items
1. When initiating the VP targeting the Batch Post, the Rollup contract should include the aggregate of the fees that were included with each item in the batch.
1. Implement a method to select a new Batch Worker
1. If this method is called to replace a Batch Worker who has failed to submit the next batch, a Validation Pool should be initiated and the Batch Worker's stakes submitted in favor of the VP. The DAO members may then stake against this VP, punishing the worker who failed to submit the batch. This is a case where a Validation Pool would be initiated without a fee, and no Reputation would be minted for that VP.
**`AddItem`** Parameters
| Name | Type |
| --- | --- |
| `author` | wallet address |
| `postId` | string |
| `stakeAmount` | integer |
**`Batch Item`** Properties
| Name | Type |
| --- | --- |
| `sender` | contract address |
| `worker` | wallet address |
| `postId` | string |
| `stakeAmount` | integer |
| `fee` | integer |
**`SubmitBatch`** Parameters
| Name | Type |
| --- | --- |
| `batchPostId` | string |
| `batchItems` | Array<`string`> |
| `poolDuration` | integer |
**`SubmitBatch`** Logic
1. A batch may only be submitted by the currently assigned Batch Worker, unless there is no currently assigned Batch Worker.
1. `batchItems` is an array of Post IDs that are included in the batch.
1. Submitted batch length must not exceed the length of the current batch queue.
1. Each Post ID in the submitted batch must match, in order, the Post IDs in the batch queue, up to the length of the submitted batch.
1. A Validation Pool should be initiated targeting the `BatchPostId`.
1. The fee included when initiating this VP should be the sum of the fees for each item included in the submitted batch.
1. For each included item, `stakeAmount` should be staked in favor of the VP on behalf of the Worker that submitted the item.
1. The availability stake of the current Batch Worker should be staked in favor of the VP.
1. The submitted items should be removed from the batch queue.
1. A new Batch Worker should be assigned.
## Automated Staking
To achieve the Autonomy requirement for the DAO, Validation Pools targeting Work Evidence Posts or Rollup Posts should be automatically validated, without human intervention. This means the rules for validating a given VP and its target Post must be represented in code.
Our prototype demonstrates the simplest possible type of rule that can be applied: a Work Evidence Post is considered valid if it starts with a specific string, "This is a work evidence post". Another type of evidence we can consider is signatures from the customer, from the worker, or from reviewers.
### Validation Pool
The client that each worker operates should be prepared to render a decision on each Executive Validation Pool within its specified duration. For example, if a Work contract submits a VP targeting a particular Work Evidence Post, the Worker client should evaluate this post and determine if it qualifies as valid Work Evidence according to the rules of the DAO.
### Rollup
Each Worker client should compute the expected values for the Batch Post's authors and references, based on the outcomes of the Matrix Pools corresponding to each item in the batch. If the submitted Batch Post matches the expectation, the Worker client should stake in favor of the Batch Post VP. Otherwise, it should stake against the VP.
## Off-chain Operations
As outlined in the Rollup section above, we need to define processes for handling off-chain Posts and Validation Pools. Posts are represented by a unique identifier on-chain, but the Post content is stored off-chain. So, every on-chain Post must have a corresponding off-chain Post. These off-chain posts should be visible to the public. To achieve this, we introduce a Forum API, for supporting web clients in reading and writing posts. We use Matrix as the off-chain forum database. Each Forum API instance will read the history and receive new posts using the Matrix client-server protocol.
Matrix implements a layer of encryption and identity management. We define an identity registration process, whereby a Matrix user may send a signed message asserting their wallet address. Messages from this Matrix user can then be attributed to their wallet address, and their on-chain REP can be verified as needed.
As mentioned above, Matrix serves as the Forum database. For this we use `io.dgov.forum.post` events. We can also use Matrix to conduct off-chain Validation Pools. For this we use `io.dgov.pool.start`, `io.dgov.pool.stake`, and `io.dgov.pool.result` events.
### Forum API
#### Write
Parameters
| Name | Type |
| --- | --- |
| `sender` | Wallet address |
| `authors` | Array of tuples: (Wallet address, weight) |
| `content` | String |
| `references` | Array of tuples: (Post ID, weight) |
| `embeddedData` | Object |
| `signature` | Sender or author signature of `content` and `embeddedData` |
In order to protect the integrity of the off-chain Forum, the API should verify that the Post is signed by one of its authors, or by the sender. The reason for allowing the Post to be signed by the sender rather than by an author, is to support the use case of adding a Post on behalf of its author(s).
The API should compute a hash of all input parameters except for `references`, and use this hash as the key for storing the Post. The hash should also be returned to the caller.
The reason for excluding `references` from the hash, is to support the use case of importing Posts from an existing data source. If we included the references, then to import any Posts from an existing data source, we would have to import every referenced Post, starting with the earliest, in order to compute the entire tree of references made by a given Post. By omitting references from the hash, it becomes possible to precompute the hash (a.k.a. ID) of referenced Posts that have not yet been imported.
The reason for excluding `references` from the signature, is to reduce the number of queries that must be made to an existing data source when importing a Post. (Specifically, when importing from the [Semantic Scholar API](https://api.semanticscholar.org/api-docs).) If we had to include the references in the signature, there is an "N + 1 problem" to the query pattern. For each paper, we would need to perform an additional query for each of its references. A single query can't ask for the references of the references of a paper.
Note that because `references` is not included in the hash or signature, there is a replay attack vulnerability. Someone could read an existing Post, modify the `references`, and write the modified Post back to the API. The signatures will still be valid even though the references have changed, and the new references will overwrite the previous references. Note that this would only affect the off-chain record of the Post's references. If the Post is published to the on-chain Forum, it is not subject to such modification, as a Post with a given ID can only be added once. To mitigate this vulnerabliity in the off-chain Forum, we should reject a write attempt if a Post with the given ID already exists.
When a Post is written, the Forum API should send an `io.dgov.forum.post` event to the Matrix room. Peer nodes should listen for events of this type from other peers. When an `io.dgov.forum.post` event is received, the recipient should write the Post to storage just as they would if the `write` endpoint were called directly.
Each Forum API node should keep track of the most recent `io.dgov.forum.post` event received. On startup, each Forum API node should query the Matrix Homeserver for any newer `io.dgov.forum.post` events.
#### Read
The `read` endpoint should accept a Post ID argument, and retrieve the corresponding Post from storage. Before sending the Post to the caller, the Forum API should verify the hash and signature, to ensure the integrity of the record.
### Matrix Pools
We can use Matrix events to carry out a variation of a Validation Pool, which we call a Matrix Pool. The main difference is that we don't have a native fungible currency in Matrix. Therefore Matrix Pools do not require a fee, and do not mint Reputation.
In principle, we could define rules governing a Chat REP, that is distinct from our on-chain REP. However, the rules for governing such a Chat REP are not obvious. It would have the fundamental challenge that there is nothing truly at stake, since Chat REP would not be backed by fungible currency. Therefor we defer Chat REP for [future work](./future-work.md).
Since Matrix Pools have no direct power over on-chain Reputation, Matrix Pools are always non-binding, meaning that Members who stake on the losing side of a Matrix Pool do not lose the staked REP. This is in contrast to on-chain Validation Pools, which may be anywhere from 0 to 100% binding.
The main use case for Matrix Pools is in the context of the Rollup process. Rather than initiate an on-chain VP, a contract may add an item to the Rollup batch queue. The Rollup Batch Worker initiates a Matrix Pool for each of these items. Then, when the batch interval has elapsed, the Batch Worker submits a Batch Post whose authorship is determined by the outcomes of the corresponding Matrix Pools for the included batch items.
Like on-chain VPs, Matrix Pools have three operations: Initiate Pool, Stake, and Evaluate Outcome. All Worker clients which intend to participate in the on-chain VP targeting the next Batch Post should listen for and handle these messages.
#### Initiate
To initiate a Matrix Pool, a Member may send an `io.dgov.pool.start` event.
**`io.dgov.pool.start`** Properties
| Name | Type |
| --- | --- |
| `postId` | string |
| `sender` | contract address |
| `fee` | integer |
| `duration` | integer |
| `quorum` | [integer numerator, integer denominator] |
| `winRatio` | [integer numerator, integer denominator] |
#### Stake
To register a stake, a Member may send an `io.dgov.pool.stake` event.
**`io.dgov.pool.stake`** Properties
| Name | Type |
| --- | --- |
| `postId` | string |
| `amount` | integer |
| `inFavor` | boolean |
The stake should be accepted only if the following conditions are met:
1. It is sent before the Matrix Pool duration has elapsed.
1. The Member who sends the stake has an on-chain REP balance greater than or equal to the staked amount.
#### Evaluate Outcome
When the Matrix Pool duration has elapsed, the current Batch Worker should evaluate the outcome and send an `io.dgov.pool.result` event.
**`io.dgov.pool.result`** Properties
| Name | Type |
| --- | --- |
| `postId` | string |
| `result` | `Result` object |
**`Result`** Properties
| Name | Type |
| --- | --- |
| `stakedFor` | integer |
| `stakedAgainst` | integer |
| `totalSupply` | integer |
| `votePasses` | integer |
| `quorumMet` | integer |
This message provides an opportunity for other Workers to compute their own expected result for the Matrix Pool and verify the result provided by the Batch Worker. If there is a discrepancy, it can be logged and reported for investigation.
### Register Identity
A client may send an `io.dgov.identity.register` event via Matrix.
1. This event should include a message signed by the sender's wallet.
1. To prevent replay attacks, the signed message should include the Matrix user ID of the sender.
1. All Forum nodes should receive this message and do the following:
1. Verify the signature, extracting the sender's wallet address
1. Verify that the signed message contains the sender's Matrix user ID
1. Store a record associating the given Matrix user ID with the given wallet address
Once this has been performed, messages from the given Matrix user can be attributed to the given wallet address.
## User Interface
### Web App
### Widget
## Other
- Imprt from Semantic Scholar
- Import from Matrix
- Bot Commands
# User Stories
## Experts start a new DAO
### Deploy DAO Contracts
```mermaid
sequenceDiagram
participant Admin
box DAO Core
participant Reputation
participant Forum
participant Bench
participant DAO
end
box Additional DAO Contracts
participant Rollup
participant Proposals
participant Work
participant Onboarding
end
Admin ->> Reputation : Deploy
Admin ->> Forum : Deploy
Admin ->> Bench : Deploy
Admin ->> DAO : Deploy
DAO -->> Reputation : Registers DAO Contract
DAO -->> Forum : Registers DAO Contract
DAO -->> Bench : Registers DAO Contract
Admin ->> Rollup : Deploy
Rollup -->> DAO : References DAO Contract
Admin ->> Proposals : Deploy
Proposals -->> DAO : References DAO Contract
Admin ->> Work : Deploy
Work -->> DAO : References DAO Contract
Admin ->> Onboarding : Deploy
Onboarding -->> DAO : References DAO Contract
```
### Initialize DAO with a single member
```mermaid
sequenceDiagram
participant Expert
box DAO
participant Forum
participant Bench
end
Expert ->> Forum : Make an initial post
Expert ->> Bench : Initiate a Validation Pool, with a fee
Bench -->> Forum : VP targets initial post
Bench ->> Bench : VP passes automatically
Bench ->> Forum : Awards minted Reputation
Forum ->> Expert : Propagates Reputation
Bench ->> Expert : Distributes fee back to Expert
```
### Initialize DAO with multiple members
```mermaid
sequenceDiagram
participant Expert1
participant Expert2
participant Expert3
box DAO
participant Forum
participant Bench
end
Expert1 ->> Forum : Make an initial post, with Expert1, Expert2, and Expert3 as authors
Expert1 ->> Bench : Initiate a Validation Pool, with a fee
Bench -->> Forum : VP targets initial post
Bench ->> Bench : VP passes automatically
Bench ->> Forum : Awards minted Reputation
Forum ->> Expert1 : Propagates Reputation
Forum ->> Expert2 : Propagates Reputation
Forum ->> Expert3 : Propagates Reputation
Bench ->> Expert1 : Distributes fee among Experts
Bench ->> Expert2 : Distributes fee among Experts
Bench ->> Expert3 : Distributes fee among Experts
```
## New member joins a DAO
## DAO member defines a new Work Contract
## Customer engages a Work Contract
## Contract triggers a dispute resolution process
## DAO changes the price of a Work Contract
## DAO upgrades the soft protocol
# Specialized DAOs
## Arbitration
Here we outline a sequence representing the on-chain portion of the dispute initiation and resolution process. If a Disputed Contract includes a "Trigger clause", a Complainant may initiate a dispute. The disputed funds are sent to the Arbitration DAO, and are held in escrow until a decision is rendered.
```mermaid
sequenceDiagram
participant complainant as Complainant
participant contract as Disputed Contract
box Arbitration DAO
participant arbitration as Arbitration Contract
participant forum as Forum
participant bench as Bench
end
participant arbitrator as Arbitrator
participant arbitrators as Arbitration DAO Members
arbitrator ->> arbitration : Stake availability
complainant ->> contract : Initiate dispute
contract ->>+ arbitration : Transfer disputed funds
arbitration ->>+ arbitrator : Assign arbitrator
loop Resolution
arbitrator ->>+ forum : Post resolution
arbitrator ->> arbitration : Submit resolution
deactivate arbitrator
arbitration ->>+ bench : Initiate Validation Pool<br>Includes portion of disputed funds as fee
bench -->> forum : VP targets resolution post
arbitrators ->> bench : Stake for/against VP
alt VP passes, resolution favors complainant
alt Disputed Contract Appeals
contract ->> arbitration : Submit an appeal (See Appeal Process, below)
else No Appeal
arbitration ->> complainant : Transfer remaining disputed funds
end
else VP passes, resolution favors disputed contract
alt Complainant Appeals
complainant ->> arbitration : Submit an appeal (see Appeal Process, below)
else No Appeal
arbitration ->> contract : Transfer remaining disputed funds
end
else VP fails
arbitration ->> arbitrator : Assign new arbitrator
end
deactivate bench
end %% loop
opt Appeal Process
arbitration ->>+ arbitrator : Assign reviewer
loop Resolution
arbitrator ->>+ forum : Post resolution
arbitrator ->> arbitration : Submit resolution
deactivate arbitrator
arbitration ->>+ bench : Initiate Validation Pool<br>Includes portion of disputed funds as fee
bench -->> forum : VP targets resolution post
arbitrators ->> bench : Stake for/against VP
alt VP passes, resolution favors complainant
arbitration ->> complainant : Transfer remaining disputed funds
else VP passes, resolution favors disputed contract
arbitration ->> contract : Transfer remaining disputed funds
else VP fails
arbitration ->> arbitrator : Assign new reviewer
end %% alt
end %% loop
end %% opt
deactivate arbitration
deactivate forum
```
The above sequence assumes that each instance of an Arbitration contract corresponds to a particular area of expertise. A contract which wants to support dispute initiation must select an Arbitration contract in advance, and the dispute will be assigned to an Arbitrator who has staked availability on that Arbitration contract.
A single Arbitration DAO may support multiple areas of expertise by deploying an Arbitration contract instance for each area of expertise. However, all of these instances would be governed by a single type of Reputation.
Alternatively, a new Arbitration DAO may be deployed for a given area of expertise. This Arb DAO would have its own type of Reputation, independent of other Arb DAOs.
# Implementation
## Ethereum Prototype
```mermaid
flowchart TD
Homeserver[Matrix\nHomeserver]
Contracts <-- Node.js blockchain\nclient library (ethers) --> API
Contracts <-- Web-based blockchain client library\n(MetaMask)--> WebApp
Contracts <-- Web-based blockchain client library\n(MetaMask)--> Widget
WebApp <-- HTTPS --> API
Widget <-- HTTPS --> API
Widget <-- Element-web Widget API\n(npm matrix-widget-api) --> Homeserver
API <-- Matrix Client-Server Protocol\n(npm matrix-bot-sdk) --> Homeserver
```
## Contracts
### DAO
We introduce a DAO contract which estabishs the public interface of the DAO core, and provides a context within which the core contracts may securely call each other.
Each of the core contracts must first be deployed. Then the DAO contract is deployed, and for each core contract, makes the first and only call to `registerDAO` to set the address of the DAO contract. All calls are then mediated by the DAO contract's public interface. This enables us to enforce the security of the core contracts.
### Bench
## Casper Production
# Future Work
## DAO Core
### Proposals
The process defined by the Proposal contract could be used to govern features of the core contracts themselves (Bench, Forum, Reputation). When a DAO is instantiated, a specific deployment of a Proposal contract can be designated as the official core DAO Proposal contract. DAO core contracts can utilize the designated Proposal contract to create and observe proposals.
### Validation Pool
#### Ratio of Minted REP Staked For/Against
The ratio of minted REP staked for and against a VP could be taken as a parameter or governed by a Proposal to increase the flexibility of the DAO.
### Minimizing on-chain computation and storage
The reason for including the Authors and References on-chain, is so that future posts can reference prior ones, and the reputation effects can be propagated.
It may be possible to avoid the cost of storing information about Posts on-chain. Instead of traversing the Forum WDAG and computing reputation rewards, the Validation Pool would need to accept a flat list of resulting REP transfers to execute if the VP is accepted.
One way to implement this is that any time a VP is initiated on-chain, it would need to include this set of resulting transfers. However, this still leaves the question of when and where the calculation of these results is performed. In general, contracts that may want to initiate Validation Pools will not have access to the required information.
The other approach would be to have an additional phase at the beginning of each VP, prior to staking, where a worker would first compute the list of transfers and make a call to the Bench contract to set the list of transfers for the given VP. Then staking would proceed, and if approved, the transfers would be executed.