diff --git a/.github/workflows/deploy-mkdocs.yml b/.github/workflows/deploy-mkdocs.yml new file mode 100644 index 0000000..c368dc6 --- /dev/null +++ b/.github/workflows/deploy-mkdocs.yml @@ -0,0 +1,40 @@ +name: Deploy MkDocs to GitHub Pages + +on: + push: + branches: + - v0.3.6-docs + +jobs: + deploy: + permissions: + contents: write # This allows writing to the repository contents + pages: write # This allows deploying to GitHub Pages + id-token: write # This is required for requesting the JWT + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set up Conda + uses: conda-incubator/setup-miniconda@v2 + with: + auto-update-conda: true + python-version: 3.9 + + - name: Install dependencies + shell: bash -l {0} + run: | + cd docs/ + conda install -c conda-forge --file requirements.txt + + - name: Build site + shell: bash -l {0} + run: | + cd docs/ + mkdocs build + + - name: Deploy to GitHub Pages + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs/site \ No newline at end of file diff --git a/.gitignore b/.gitignore index 852fb69..52add64 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ cache/ out/ # docs -docs/ + # gas snapshot files .gas-snapshot diff --git a/README.md b/README.md index a066f4a..7ef7387 100644 --- a/README.md +++ b/README.md @@ -1,95 +1,88 @@ # Circles Protocol -## Introducing Circles Protocol v2 +Circles is a decentralized protocol for creating and distributing fair and social money through personal currencies. Built on the Gnosis Chain, it utilizes smart contracts to manage the creation, distribution, and transfer of personal currencies using the ERC1155 multi-token standard. -We're excited to be working on Circles Protocol v2, where we focus on making things better for everyone who uses and builds on Circles. Learning from our journey since Circles began, we've tackled the challenges we faced in the early days. +## Key Concepts -In Circles v2, we make it easier and more inviting for users and developers to engage with Circles. Our goal is to foster an ecosystem of products and experiences building on Circles. We've also been busy updating our technology, using the latest in cryptography to enhance performance, scalability, and to bring a new level of privacy to the Circles experience. +- **Personal Currencies**: Each individual can mint their own currency at a rate of one Circle per hour. +- **Trust Networks**: Currencies become valuable and transferable through trust relationships between participants. +- **Demurrage**: A 7% annual cost applied to held currencies, encouraging circulation and maintaining equity. -## Why build Circles ? +## Features -Our standard money system is based on debt, primarily from banks. Repaying this debt requires more than the initial amount due to interest, ensuring a consistent return of funds to these financial institutions. This system indirectly encourages anticipating future economic growth, which can increase our demand on the planet's resources. +- Retroactive minting for up to 14 days +- Path-based transactions through trust connections +- Flexible economic interactions between individuals, organizations, and groups +- Equilibrium mechanism balancing issuance and demurrage -In Circles UBI, we introduce "Time Circles" (TiC), a money system backed by the equal passage of time for all people. Every hour, each individual can seamlessly add one TiC to their account, unconditionally. To ensure TiC remains a meaningful measure of value, we implement a decay mechanism: tokens diminish in value over time. This equilibrium between token creation and decay ensures a stable balance for everyone, today and for future generations. +## Documentation -Understanding "Time Circles" also means recognizing what they are not. While this brief overview may not capture the full depth of the discussion, let's set a clear foundation from the outset. +For more details on Circles and details of the implementation please refer to [https://aboutcircles.github.io/circles-contracts-v2/](https://aboutcircles.github.io/circles-contracts-v2/) -Time Circles is not a panacea for all economic challenges, but it is essential to understand its intended purpose. TiC isn't a promise of a universal standard of living across diverse regions. Instead, it's a commitment that no person should be completely without financial means. Think of TC as a baseline currency available to all. +## Getting Started -Time Circles encourages circular spending. Its true worth will be determined by the quality and range of goods and services available for TiC. While other currencies may prioritize store-of-value, TiC complements this financial landscape, emphasizing circulation and utility. +🐲 **Beta Status**: This repository is in beta and actively developed in the open. While initial reviews are on-going, we welcome community engagement for wider testing and integration. As AGPL-licensed software, it's provided as-is. We encourage thorough review and testing before any production use. -Lastly, two crucial parameters underpin the TiC system. The first parameter straightforwardly defines the unit: one token for every human, every hour. The second parameter establishes the decay rate of TiC. With a vision for sustainability across generations, our approach is retrospective: taking an optimistic human lifespan of 80 years as a benchmark, a token minted today should, after those 80 years, carry negligible value. -## Specifications +### Prerequisites -🐉 **warning**: here be dragons. This repository is under construction and neither functionally complete or externally reviewed. It is shared publicly to enable early discussion, but should not be considered ready for use. +- [Foundry](https://book.getfoundry.sh/getting-started/installation) -For questions, contact maintainer: Ben +### Installation -## Setting up development environment - -This Solidity project uses Foundry as a toolkit. If you don't have Foundry installed yet, see instructions [below](#foundry-as-toolkit) - -### Using Foundry to build the contracts -1. First, you'll need to clone the repository to your local machine: +1. Clone the repository: ```bash - git clone https://github.com/CirclesUBI/circles-contracts-v2 + git clone https://github.com/aboutcircles/circles-contracts-v2 cd circles-contracts-v2 ``` - -### Compiling the contracts -1. To compile the contracts, use the following command: +2. Install dependencies: ```bash - forge build + forge install ``` - Upon successful compilation, you'll find the generated artifacts (like ABI and bytecode) in the specified output directory, by default `out/`. +### Building -2. To format the code, you can run: +1. Compile the contracts: ```bash - forge fmt - ``` - or only check the correct formatting without changing the code: - ```bash - forge fmt --check + forge build ``` -### Testing the contracts -1. To test the contracts, use the following command: +### Testing + +1. Run the test suite: ```bash forge test ``` - or to report on gas usage: +2. For a gas report: ```bash forge test --gas-report ``` -2. To create a snapshot file to disk of each test's gas usage, use: +### Deployment + +To deploy to the Chiado testnet: + +1. Copy `.env.example` to `.env` and set your private key and API keys. +2. Run the deployment script: ```bash - forge snapshot + ./script/deployments/chiadoDeploy.sh ``` -### Deploying the contracts -#### Chiado -To deploy the contracts to the Chiado testnet, run `./chiadoDeploy.sh` and supply a private key and API keys in `.env` file in the root directory (copy `.env.example` and set private information): -```shell -./script/deployments/chiadoDeploy.sh -``` +## Contributing -## Foundry as toolkit +Contributions are welcome! Please feel free to submit a Pull Request. -Foundry consists of: +## License -- **Forge**: Ethereum testing framework (like Truffle, Hardhat and DappTools). -- **Cast**: Swiss army knife for interacting with EVM smart contracts, sending transactions and getting chain data. -- **Anvil**: Local Ethereum node, akin to Ganache, Hardhat Network. -- **Chisel**: Fast, utilitarian, and verbose solidity REPL. +This project is licensed under the [AGPL-3.0 License](LICENSE). -You can find the installation guide for Foundry in their [book.getfoundry.sh - Getting started](https://book.getfoundry.sh/getting-started/installation) +## Disclaimer -Here we re-iterate the most important steps to get you started. +This project is under active development. The code has not completed externally reviews and should not be used in production environments without proper review and testing. -1. You can install precompiled binaries with their toolchain installer: - ```bash - curl -L https://foundry.paradigm.xyz | bash - ``` - and follow the instructions in the terminal. - To instead build from source, see their getting started guide. +## Contact + +For questions or support regarding this project, please contact: + +- About Circles +- Ben + +We appreciate your interest and feedback! \ No newline at end of file diff --git a/docs/LICENSE b/docs/LICENSE new file mode 100644 index 0000000..3654b55 --- /dev/null +++ b/docs/LICENSE @@ -0,0 +1,429 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. + +https://creativecommons.org/licenses/by-sa/4.0/ \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..128417f --- /dev/null +++ b/docs/README.md @@ -0,0 +1,79 @@ +# Protocol Documentation + +This directory contains the documentation for the protocol using MkDocs. + +## Prerequisites + +- Miniconda or Anaconda installed on your system. If you don't have it installed, you can download and install it from the [official website](https://docs.conda.io/en/latest/miniconda.html). + +## Setup + +1. Open a terminal or command prompt and navigate to the `docs/` directory. + +2. Create a new conda environment named "protocol-docs" with Python 3.9: + ```bash + conda create --name protocol-docs python=3.9 + conda activate protocol-docs + ``` + +3. Install MkDocs and its dependencies from the `conda-forge` channel: + ```bash + conda install -c conda-forge --file requirements.txt + ``` + +4. Verify the installation by running: + ```bash + mkdocs --version + ``` + +## Usage + +1. Ensure you have activated the "protocol-docs" environment: + ```bash + conda activate protocol-docs + ``` + +2. Preview the documentation locally: + ```bash + mkdocs serve + ``` + Open a web browser and navigate to `http://localhost:8000` to view the documentation. + +3. Build the documentation: + ```bash + mkdocs build + ``` + The static HTML files will be generated in the `site/` directory. + +4. Deploy the documentation: + - Copy the contents of the `site/` directory to your preferred hosting platform or server. + - Configure your hosting platform to serve the files from the `site/` directory. + +## Adding Documentation + +- Create new Markdown files in the `docs/` directory for each documentation page. +- Update the `mkdocs.yml` file to include the new pages in the navigation structure. + +## Updating Dependencies + +If you need to update the dependencies or install additional packages, follow these steps: + +1. Update the `requirements.txt` file with the desired dependencies. + +2. Activate the "protocol-docs" environment: + ```bash + conda activate protocol-docs + ``` + +3. Update the dependencies using conda and the `conda-forge` channel: + ```bash + conda install -c conda-forge --file requirements.txt + ``` + +## Deactivating the Environment + +When you're done working on the documentation, you can deactivate the "protocol-docs" environment: + +```bash +conda deactivate +``` \ No newline at end of file diff --git a/docs/docs/20240321-Circles-contracts.svg b/docs/docs/20240321-Circles-contracts.svg new file mode 100644 index 0000000..7eaafe9 --- /dev/null +++ b/docs/docs/20240321-Circles-contracts.svg @@ -0,0 +1,13 @@ + + + + + + + + Gnosis ChainSAFECircles contracts v2, 2024not built by uscore contractsa networkednode instanceEoAHumans and organizationshub v1tokenContracts v2orGroupas organisationhub v2is CirclesContracts v1Groupsenvisioned extensionsmigrationv1-to-v2single TransferThroughfor v1 PathfinderOperatorscan operate on the Graphintent solvercompetitionpre-/post-hookson intentscommunity dAppseg. CowSwap v2v2 mint auto-blocksNameRegistryCustomTreasuriesStandard TreasuryCirclesis ERC1155VaultGroupsDemurrage ERC20Inflationary ERC20Wrappers(Base) MintPolicyAccount AbstractionExtensionsFlow Matrixand ERC1155ERC20Lift \ No newline at end of file diff --git a/docs/docs/about.md b/docs/docs/about.md new file mode 100644 index 0000000..8f5e7a4 --- /dev/null +++ b/docs/docs/about.md @@ -0,0 +1,20 @@ +# About the Circles Protocol + +Circles is a vision for a fair and social form of money. It is also the culmination of the efforts of multiple teams over several years, working to bring this vision to life through organizing and building concrete instantiations. + +Various teams have collaborated with varying degrees of coordination and autonomy, all in the spirit of open-source development, to continually advance Circles forward. This protocol improvement to Circles is presented in that same spirit by the "About Circles" team, acting as a "Circles Ambassador." + +We do not claim any authority over what Circles should be or become. Instead, we humbly propose this as a way to make Circles better, and invite people to vote with their feet by adopting it if they find value in it. Our aim is simply to contribute to the Circles ecosystem and vision in a positive way. + +Ultimately, the path forward for Circles will be shaped by the collective actions and decisions of the community. We are merely one voice and one effort among many in this collaborative, open-source endeavor to create a fair and socially-embedded form of digital money. We are excited to be part of this journey and to see how Circles evolves. + +## Disclaimer +Circles is not owned or controlled by any single entity, including the "About Circles" team. Instead, it is a collective vision and effort, intended to be cared for and shaped by the wider community. The "About Circles" team acts as an ambassador and contributor to this vision, but does not claim any special authority or ownership over Circles. + +## Licensing +In alignment with our open-source ethos, Circles Protocol is developed and released under the following licenses: + +- All code is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0), a strong copyleft license. This ensures that any derivative works or modifications of the code are also released under the same license, maintaining the open and shared nature of the codebase. +- All documentation is released under the Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. This is a copyleft license that allows others to share and adapt the material, as long as they credit the original creation and license their new creations under identical terms. + +We believe in the power of open collaboration and sharing, and these licenses reflect our commitment to keeping Circles open and accessible to all. \ No newline at end of file diff --git a/docs/docs/advanced-topics/group-mint-policies.md b/docs/docs/advanced-topics/group-mint-policies.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/docs/advanced-topics/index.md b/docs/docs/advanced-topics/index.md new file mode 100644 index 0000000..ee8959c --- /dev/null +++ b/docs/docs/advanced-topics/index.md @@ -0,0 +1,6 @@ +# Advanced Topics + +These documents are written as deeper introduction to some of the technical workings of the Circles protocol. + +- [Inflation and demurrage calculations](inflation-demurrage.md) +- [Path-based transactions and flow matrices](path-based-transactions.md) \ No newline at end of file diff --git a/docs/docs/advanced-topics/inflation-demurrage.md b/docs/docs/advanced-topics/inflation-demurrage.md new file mode 100644 index 0000000..ed4af32 --- /dev/null +++ b/docs/docs/advanced-topics/inflation-demurrage.md @@ -0,0 +1,132 @@ +# Demurrage Mechanism in Circles: Developer's Guide + +## Overview + +Circles implements demurrage as a systematic reduction of token balances over time, applied to all token balances in the system, affecting both personal and group currencies. The system extends the ERC1155 multi-token standard to incorporate this demurrage mechanism. + +Additionally, Circles allows wrapping ERC1155 tokens (in a demurrage representation) into an ERC20 contract. For each Circles identifier (personal or group), two ERC20 contracts can be created: one for demurrage representation and one for inflationary representation. + +### Key Features of Demurrage in Circles + +1. **Annual Rate**: 7% reduction in token balances per year +2. **Daily Application**: Calculated and applied on a per-day basis +3. **Universal**: Affects all Circles tokens equally + +## ERC1155 Interface and Demurrage + +Circles extends the standard ERC1155 interface to handle demurrage. Key functions include: + +### Balance Queries + +```js +function balanceOf(address account, uint256 id) public view returns (uint256) +``` +Returns the current demurraged balance of `account` for token `id`. This function internally calls `balanceOfOnDay` with the current day. + +```js +function balanceOfOnDay(address account, uint256 id, uint64 day) + public view returns (uint256 balance, uint256 discountCost) +``` +Returns the demurraged balance for `account` and `id` as of the specified `day`, along with the `discountCost` (amount of tokens "burned" due to demurrage). + +### Transfers + +```js +function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public +``` +Transfers `value` amount of token `id` from `from` to `to`, applying demurrage before transfer to both sender and receiver if applicable. + +### Token ID Convention + +Token IDs in Circles are derived from addresses: +```js +function toTokenId(address _avatar) public pure returns (uint256) { + return uint256(uint160(_avatar)); +} +``` + +## Demurrage Calculation + +### Balance Reduction + +The system reduces token balances daily by a factor calculated as: +```sh +Daily Factor = (1 - 0.07)^(1/365.25) ≈ 0.99980813 +``` +This results in a compound 7% reduction over a full year. + +### Practical Effects + +- A balance of 100 Circles reduces to approximately 99.98081 Circles after one day +- Over 365 days, 100 Circles reduces to about 93 Circles + +## Implementation Considerations + +1. **On-Demand Calculation**: Balance reductions are computed when balances are accessed (through view functions) or computed and updated when modified (through transfers). +2. **Token Burning**: The reduction in balance burns the amount that gets demurraged, effectively removing these tokens from circulation. +3. **Gas Efficiency**: On-demand calculation avoids the need for daily update transactions. +4. **Precision**: 128-bit fixed-point arithmetic ensures high accuracy in calculations, allowing for daily updates. + +## Development Guidelines + +1. Always use `balanceOf()` or `balanceOfOnDay()` to get current, demurraged balances. +2. On the hub contract, all amounts are to be understood as demurraged amounts on the current day. +3. Be aware that token balances decrease over time, even without explicit transfers or actions. +3. If your application expects static (ie. inflationary) balances or to interface with external systems: + - Use the provided `InflationaryOperator` contract to interact with ERC1155 Circles. + - Alternatively, wrap the (group) Circles you want to interact with in an inflationary ERC20 contract, where you can treat them as regular ERC20 tokens. + +## Time and Day Calculation in Circles + +Understanding how Circles handles time is crucial for working with demurraged balances. The system uses a concept of "days" since a fixed starting point to calculate demurrage. + +### The `day` Function + +```js +function day(uint256 timestamp) internal view returns (uint64) { + return uint64((timestamp - inflationDayZero) / 1 days); +} +``` + +This function converts a Unix timestamp to a day number used in demurrage calculations. Key points: + +1. **Inflation Day Zero**: This is the starting point for all time calculations in Circles. It's set to October 15, 2020, at 00:00:00 UTC (Unix timestamp: 1602720000). + +2. **Day Calculation**: Days are calculated as the number of whole days passed since Inflation Day Zero. + +3. **Usage**: This day number is used in all demurrage calculations to determine how much a balance has decreased over time. + +### Demurrage vs Inflationary Balances + +- **Demurrage Balances**: These are time-dependent. The actual balance at any given moment is a function of the stored balance, the last update day, and the current day. +- **Inflationary Balances**: These are static in time. They represent an equivalent way of representing the 7% p.a. "inflation", but through an ever-increasing money supply. In the inflationary representation, Circles mints slightly more tokens per hour each day than the previous day, to offset the existing Circles already in circulation. + +Note that the ground-truth for Circles is the demurrage representation, where exactly one Circle is minted per person per hour, offset by the daily burning of Circles at a rate equivalent to 7% p.a. + +### Practical Implications + +1. When querying balances, the current day is always used to calculate the up-to-date demurraged balance. + +2. For future projections, you can specify a different day using `balanceOfOnDay()`. + +3. When converting between demurrage and inflationary representations, the day parameter determines the point in time for the conversion. + +## Helper Functions for Inflationary Conversion + +Circles provides two helper functions to convert between demurraged and inflationary representations: + +```js +function convertInflationaryToDemurrageValue(uint256 _amount, uint64 _day) + public view returns (uint256) +``` +Converts an inflationary amount to its demurraged equivalent as of the specified day. + +```js +function convertDemurrageToInflationaryValue(uint256 _amount, uint64 _dayUpdated) + public view returns (uint256) +``` +Converts a demurraged amount as on the day provided to its inflationary equivalent. + +## Conclusion + +Understanding the demurrage mechanism is crucial for developers working with Circles. Always consider the time-dependent nature of token balances and use the provided functions to ensure accurate balance calculations and transfers. \ No newline at end of file diff --git a/docs/docs/advanced-topics/path-based-transactions.md b/docs/docs/advanced-topics/path-based-transactions.md new file mode 100644 index 0000000..cb30790 --- /dev/null +++ b/docs/docs/advanced-topics/path-based-transactions.md @@ -0,0 +1,290 @@ +# Path-based Transactions and Flow Matrices + +In the Circles ecosystem, path-based transactions enable the transfer of Circles tokens between people who don't directly trust each other. This system uses flow matrices to represent and validate these multi-hop transactions. + +## Concept Overview + +Path-based transactions allow Circles to be transferred along a path of trust relationships. Instead of requiring direct trust between the sender and receiver, the system finds a path through the trust network where each step involves a trusted relationship. + +## Flow Matrices + +Flow matrices are structured representations for these path-based transactions. They describe the movement of Circles tokens through the network for a given transaction (or a batch of transactions). + +### Structure of a Flow Matrix + +A flow matrix consists of the following components: + +1. **Flow Vertices**: An ordered list of avatar addresses that the transaction path touches. This includes any avatar that sends, receives or whose Circles are used in any of the flow edges. These can be humans, organizations or groups, but must be registered. +2. **Flow Edges**: A path consists of a set of flow edges. This is expressed as an array of `FlowEdges`, each representing a transfer of a specific (personal or group) Circles type and amount between two vertices. These flow edges are applied in the order given and the order of the coordinates must match that of the flow edges. A `FlowEdge` therefore is a structure that specifies: + - `amount`: The amount of tokens being transferred (uint192) in this edge. + - `streamSinkId`: To perform the `ERC1155:onERC1155Received()` call, the path needs to identify which edges are terminal flow edges. Therefore this references for all terminal edges a stream identifier (and is 0 for non-terminal edges; >0 for terminal edges). +3. **Coordinates**: Packed data representing triplets of indices within the flow vertices array: for each flow edge the coordinates must provide a triplet `(uint16, uint16, uint16)`, referencing the addresses of `(Circles-to-send, sender, receiver)` read from the flow vertices array. The coordinates are input as `bytes` packed explicitly per 16 bits to avoid zero-padding for 256bit word length. +4. **Streams**: A stream represents the actual intent of a sender to send an amount of Circles to a receiver - without specifying which Circles to send or over which path, simply that the receiver only ever receives Circles they trust. A stream specifies a `sourceCoordinate` as the index of the source (or sender) in the flow vertices array, an array of the `flowEdgeIds` to cross-reference with the flow edges the correct terminal edges of this stream; and `bytes data` that will be sent to the receiver of the stream in the acceptance call. A flow matrix can have: + - zero streams provided: All edges combined must form a closed path where no sender and no receiver nett-receives or nett-sends an amount of Circles. This can be used to reorganise the balances of Circles across the graph. + - one stream provided: The flow matrix represents the path of a single intended transfer between a sender and receiver. + - two or more streams: The flow matrix represents a batch of intents of multiple senders to send Circles to receivers, and they get settled on-chain as single path (while still performing the acceptance checks for each stream's receiver). + +### An example of a flow matrix + +Let's illustrate a flow matrix and streams with an example. Let's assume we have the following avatars (only humans). +``` +Avatars (Flow Vertices): +A: Alice +B: Bob +C: Charlie +D: David +E: Eva +``` + +Let's assume Alice wants to send 3 CRC to David, and 5 CRC to Eva. Bob wants to send 4 CRC to David as well. Let's assume they have the following trust graph among them (where the arrow means "trusts"): + +Circles Trust Graph + +We can assume that everyone already holds some balances of the tokens of the people they trust. A possible path could look like the following: + +```sh ++----------+-----+-----+-----+-----+-----+ +| | A | B | C | D | E | ++----------+-----+-----+-----+-----+-----+ +| A-B | -8A | 8A | | | | ++----------+-----+-----+-----+-----+-----+ +| B-D (T2) | | -4C | | 4C | | ++----------+-----+-----+-----+-----+-----+ +| B-C | | -5B | 5B | | | ++----------+-----+-----+-----+-----+-----+ +| B-D (T1) | | -3C | | 3C | | ++----------+-----+-----+-----+-----+-----+ +| C-E (T3) | | | -5D | | 5D | ++==========+=====+=====+=====+=====+=====+ +| Net Flow | -8 | -4 | 0 | 7 | 5 | ++==========+=====+=====+=====+=====+=====+ +| Stream 1 | -3 | | | 3 | | ++----------+-----+-----+-----+-----+-----+ +| Stream 2 | | -4 | | 4 | | ++----------+-----+-----+-----+-----+-----+ +| Stream 3 | -5 | | | | 5 | ++----------+-----+-----+-----+-----+-----+ +``` + +In this diagram, positive values represent incoming tokens and negative values represent outgoing tokens; the letters `(A, B, C, D)` represent the type of Circles tokens being transfered; and streams don't specify token types, only amounts. + +#### Flow edges Explanation + +Note: flow edge arrays and flow vertices arrays are indexed from 0. Streams are explicitly indexed from 1, because we reserve 0 for not-referencing a stream. (And Markdown will not enumerate from 0, so subtract 1 here): + +1. A-B: Alice sends 8 of her own Circles (A) to Bob. + - `(amount = 8, streamSinkId = 0)` + - coordinates `(A, A, B)` +2. B-D: Bob sends 4 of Charlie's Circles (C) to David. + - `(amount = 4, streamSinkId = 2)` + - coordinates `(C, B, D)` +3. B-C: Bob sends 5 of his own Circles (B) to Charlie. + - `(amount = 5, streamSinkId = 0)` + - coordinates `(B, B, C)` +4. B-D: Bob sends 3 of Charlie's Circles (C) to David. + - `(amount = 3, streamSinkId = 1)` + - coordinates `(C, D, D)` +5. C-E: Charlie sends 5 of David's Circles (D) to Eva. + - `(amount = 5, streamSinkId = 3)` + - coordinates `(D, C, E)` + +#### Stream Explanation + +- Stream 1: Alice intends to send 3 Circles from her to David. + - `sourceCoordinate = 0` (Alice) + - `flowEdgeIds = [3]` (fourth edge B-D is the single terminal edge for stream 1) + - `data` (some message Alice sends along to David) +- Stream 2: Bob intends to send 4 Circles to David. + - `sourceCoordinate = 1` (Bob) + - `flowEdgeIds = [1]` (second edge B-D is single terminal edge for stream 2) + - `data` +- Stream 3: Alice intends to send 5 Circles to Eva. + - `sourceCoorindate = 0` + - `flowEdgeIds = [4]` (fifth edge C-E terimates stream 3) + - `data` + +## Net Flow and Consistency Check + +The net flow is not sent as input to the contracts, rather it is included in the diagram to illustrate the consistency check that the contract performs. +For an explicit path of flow edges to be a valid solution to the set of intents expressed in the streams, it must hold that +for every vertex the sum over all flow edges (modulo Circles Id) must equal the sum over all streams (ie. summing the columns). + +Streams themselves don't specify an amount though - both to compactify the representation but also to not over-determine the representation. Instead it is checked that for each stream: + +- all the terminal edges that reference this stream have the same receiver. +- that each stream lists their terminal flow edge ids in ascending order. +- and that the count of terminal edges that reference a stream, matches the length of the `flowEdgeIds` array of that stream. + +By cross-referencing, and checking consistency we ensure that we can use the sum of the terminal edges for a stream as the amount intended to send by that stream. + +In our example, all streams only had one terminal flow edge, but in general a flow matrix can have multiple terminal flow edges for a single stream. + +## Technical Implementation + +The `Hub` contract implements path-based transactions through the `operateFlowMatrix` function. Let's break down its key components: + +### Function Signature + +```solidity +function operateFlowMatrix( + address[] calldata _flowVertices, + FlowEdge[] calldata _flow, + Stream[] calldata _streams, + bytes calldata _packedCoordinates +) external nonReentrant(0) +``` + +### Key Steps in Processing +The function performs several crucial steps: + +1. **Unpacking Coordinates**: The packed coordinates are unpacked into an array of uint16 values. +2. **Authorization Check**: Ensures all senders (as listed in the streams) have authorized the operator calling this function (with `ERC1155::setApprovalForAll()`). +3. **Flow Matrix Verification**: Checks the correctness of the flow matrix, including trust relationships and avatar registrations. +4. **Path Transfers**: Executes the individual transfers defined by the flow edges. +5. **Acceptance Checks**: Calls acceptance checks for the streams and calculates the netted flows. +6. **Flow Matching**: Ensures the netted flows from streams match the verified flow matrix. + +The important internal functions that accomplish these above steps are the following: + +- **_verifyFlowMatrix** + - Ensures all vertices are registered avatars. + - Verifies that receivers trust the Circles being sent. + - Calculates the netted flow for each vertex. +- **_effectPathTransfers** + - Processes each flow edge, either as a transfer or a group mint. + - Keeps track of stream definitions and ensures their correctness. +- **_callAcceptanceChecks** + - Calls acceptance checks for each stream. + - Emits `StreamCompleted` events for successful "effective transfers" for each stream. + +## Minting Group Circles along a Path + +The Circles ecosystem allows for the minting of group Circles as part of path-based transactions. This feature enables dynamic creation of group tokens within complex transfer paths, enhancing the liquidity and utility of the system. + +### How Group Minting Works in Path Transactions + +1. **Flow Edge to Group Avatar**: When a flow edge in the path has a receiver that is a registered group avatar, the system treats this as a group minting operation instead of a regular transfer. + +2. **Collateral for Minting**: The tokens being sent to the group in this flow edge are used as collateral for minting new group Circles. + +3. **Automatic Minting**: The `_groupMint` function is called internally, creating new group Circles based on the collateral provided. + +4. **Mint Policies**: Each group has an associated mint policy contract that determines the rules for minting new group Circles. This policy is consulted during the minting process. + +### Implementation Details + +The `_effectPathTransfers` function in the Hub contract handles the minting of group Circles within a path: + +```solidity +if (!isGroup(to)) { + // Regular transfer for non-group receivers + _update( + _flowVertices[_coordinates[index + 1]], // sender + to, + ids, + amounts + ); +} else { + // Group minting for group receivers + _groupMint( + _flowVertices[_coordinates[index + 1]], // sender + to, // receiver + to, // group + ids, // collateral + amounts, // amounts + "", // No additional data for path-based group mints + false // Indicate this is part of a path, not an explicit call + ); +} +``` + +### Key Aspects of Group Minting in Paths + +1. **Implicit Minting**: Group minting occurs automatically when a group is the receiver in a flow edge, without requiring explicit minting instructions. + +2. **Collateral Transfer**: The tokens sent to the group are transferred to the group's treasury contract as collateral. + +3. **Mint Policy Checks**: The group's mint policy is consulted to ensure the minting operation is valid according to the group's rules. + +4. **No Additional Data**: When minting occurs as part of a path, no additional data is passed to the mint policy (unlike in explicit group mint calls when the caller can pass data to the group mint policy). + +5. **Trust Relationships**: The system checks that the group trusts the collateral being provided (i.e., the actual tokens being sent, not the sender of the flow edge). + +### Implications and Benefits + +- **Dynamic Token Creation**: Allows for the creation of new group tokens as part of complex transfer paths. +- **Increased Liquidity**: Facilitates the conversion from personal (or group Circles) into (other) group Circles within a single flow edge. Group Circles are likely to be trusted by more and hence accepted by more, reducing the number of hops in the graph a path needs to traverse to reach far away recipients. +- **Flexible Economic Structures**: Enables more complex economic interactions and structures within the Circles ecosystem. +- **Seamless Integration**: Group minting is seamlessly integrated into the path-based transaction system, requiring no special handling from the transaction initiator. + +This feature significantly enhances the capabilities of path-based transactions in Circles, allowing for dynamic and flexible token interactions that can adapt to the needs of the network and its participants. +[Previous content remains unchanged] + +## Trust and Consented Flow + +### Trust Implies a Flow Edge + +The default behavior for Circles is such that if one avatar trusts another avatar, they attest that: + +1. **Token Acceptance**: They are willing to accept the trusted avatar's personal Circles tokens as payment. + +2. **Implicit Flow Permission**: They allow their balance of the trusted avatar's tokens to be used in path-based transactions, potentially without their direct involvement in each transaction. + +3. **Network Facilitation**: They contribute to the overall liquidity and connectivity of the Circles network by creating a potential path for transactions. + +4. **Value Recognition**: They recognize some form of value or merit in the trusted avatar's economic activity or contribution to the community. + +5. **Transitive Trust**: While not directly trusting the entire network of the trusted avatar, they implicitly allow for multi-hop transactions that may involve avatars further down the trust chain. + +6. **Time-Bound Relationship**: Trust relationships have an expiry time, allowing for dynamic changes in the trust network over time. + +This default behavior enables the Circles system to create paths for transactions between avatars who may not directly trust each other, facilitating a more interconnected and fluid economy. + +### Consented Flow + +Consented flow is an advanced feature in the Circles ecosystem that provides additional control over path-based transfers. It's an opt-in mechanism that allows people (and groups or organizations) to have more granular control over how their Circles tokens are used in path-based transactions. + +#### Key Aspects of Consented Flow + +1. **Opt-In Feature**: Avatars must explicitly enable consented flow by setting an advanced usage flag. +2. **Bidirectional Trust Requirement**: When consented flow is enabled, a valid flow edge requires: + - The receiver trusts the Circles avatar of the tokens being sent (standard requirement). + - The sender trusts the receiver. + - The receiver must also have consented flow enabled. +3. **Recursive Protection**: The requirement for the receiver to also have consented flow enabled ensures that the protection extends through multiple hops in a transaction path, for those flow edges that enter a region of consented flow. +4. **Enhanced Control**: Provides more precise control over how an avatar's tokens can be used in the network, potentially reducing unexpected or undesired token movements. +5. **Impact on Liquidity**: While offering more security, consented flow may make some transactions more challenging to complete, as it requires more tightly-knit web of trust relationships. + +#### Behaviour Details + +The `isPermittedFlow` function in the Hub contract implements the logic for checking whether a flow edge is permitted (with or without consented flow enabled for the sender): + +1. **Basic Trust Check**: + - Always checks if the receiver trusts the Circles being sent. + - If this basic trust doesn't exist, the flow is never permitted. +2. **Consented Flow Check**: + - If the sender has consented flow enabled (checked via `advancedUsageFlags`), additional checks are performed: + 1. The sender must trust the receiver. + 2. The receiver must also have consented flow enabled. +3. **Return Value**: + - Returns `true` if the flow is permitted based on the above checks. + - Returns `false` otherwise. + +#### Implications of Consented Flow + +1. **Enhanced Security**: Provides an additional layer of control for avatars concerned about unauthorized use of their tokens. +2. **Potential Complexity**: May increase the complexity of finding valid paths for transactions, especially if a sender with consented flow is trying to send tokens to a receiver outside the consented flow perimeter (ie. a receiver without consented flow enabled). The sender may be required to sandwich their path-transfer between disabling and re-enabling consented flow for themselves, so that their path can start from outside the local consented flow perimeter. +3. **Network Dynamics**: Could influence the overall structure and behavior of the Circles trust network, potentially leading to more tightly-knit, high-trust sub-networks. +4. **Flexibility**: Allows for different trust models within the same network, catering to varying preferences for control and openness. + +Consented flow represents an advanced usage of the Circles system, allowing for a more nuanced approach to trust and token flow within the network. It balances the need for additional control with the system's goal of creating a fluid, interconnected economy. + +## Conclusion + +The Circles ecosystem implements path-based transactions using flow matrices to enable multi-hop transfers of personal and group tokens. This system allows for: + +1. Complex transfers between indirectly connected avatars +2. Automatic group token minting within transaction paths +3. Flexible trust models, including opt-in consented flow for enhanced control + +These mechanisms collectively form a decentralized currency network capable of supporting diverse economic interactions and trust relationships. The technical infrastructure provides a foundation for a social currency system that can adapt to various community needs and transaction complexities. \ No newline at end of file diff --git a/docs/docs/architecture.md b/docs/docs/architecture.md new file mode 100644 index 0000000..11b0f27 --- /dev/null +++ b/docs/docs/architecture.md @@ -0,0 +1,224 @@ +# Circles Architectural Overview + +## Introduction + +Circles is a decentralized economic system built on the Gnosis Chain, designed to create and distribute fair and social money through personal currencies. This overview provides a high-level understanding of the system's architecture and how its various components interact. + +## System Architecture Diagram + +![Alt text](./20240321-Circles-contracts.svg) + + + Open Circles Architecture diagram in new tab + + +## Core Components + +### Hub v2 (Circles) + +The central contract in the Circles ecosystem is the Hub v2, which serves as the main entry point for interactions with the system. It manages: + +- Registration of humans, organizations, and groups +- Minting of personal currencies +- Trust relationships between entities +- Group creation and management +- Minting collateral into group currencies +- Wrapping ERC1155 Circles Ids tokens into ERC20 wrappers +- Demurrage of all Circles tokens equally + +The Hub v2 contract implements the ERC1155 standard, allowing it to handle multiple token types efficiently. + +Code: /src/hub/Hub.sol + +### NameRegistry + +The NameRegistry contract manages names, symbols and metadata for avatars (humans, groups, and organizations): + +- Allows humans to register a unique short name (12 characters, base58 encoding) +- Stores custom names for groups and organizations +- Manages custom symbols for group currencies +- Stores and updates metadata digests (eg IPFS CIDs) for avatar profiles +- Names are read by ERC20 contracts for name and symbol + +The NameRegistry plays a role in identity management and human-readable addressing within the Circles system, enhancing user experience and facilitating easier identification of avatars and their associated currencies. + +Code: /src/names/NameRegistry.sol + +### Migration + +The Migration contract facilitates the transition from Circles v1 to v2, ensuring the ability to migrate token balances: + +- Converts v1 Circles to v2 Circles, accounting for inflation and demurrage +- Uses a linear interpolation method to calculate the conversion rate. Corrects for the original convention in hub v1 where 1/3 CRC per hour is issued (8 CRC per day) +- Allows migration of multiple types of Circles balances in a single transaction by one owner +- Locks v1 tokens in the Migration contract and mints equivalent v2 tokens. +- Ensures upon migrating balances that humans are auto-registered in Hub v2 - so that their token is defined +- owners of Circles in v1 can migrate their balances at any time and for any amount they chose to Circles v2. + +This Migration system ensures a controlled and secure transition from Circles v1 to v2, maintaining integrity throughout the upgrade process. + +Code: /src/migration/Migration.sol + +### Groups, Policies and Treasury + +The Circles ecosystem includes a system for managing group currencies, which allows communities and actors to create their own Circles with customizable policies. This system involves several interconnected components: + +#### Groups + +Group avatars (unlike human avatars) cannot mint Circles based on time. Rather group Circles are minted by collaterlising existing Circles into the group if the group trusts that collateral - and a group mint policy can further refine the conditions under which minting is possible. + +Groups register as a group avatar in the Hub contract. They have two registration options: + +- `registerGroup()`: Uses the `StandardTreasury` contract (recommended). +- `registerCustomGroup()`: Allows the use of a custom treasury contract. + +It is recommended that all groups rely on the standard treasury contract. Users should exercise caution when interacting with custom groups. + +Groups require a `MintPolicy` upon registration, which defines the rules for minting, burning, and redeeming the group's currency. + +To explicitly mint group Circles, the owner of collateral for a group can call `hub:groupMint()`. Code: /src/hub/Hub.sol:groupMint() + +#### Standard Treasury + +The Standard Treasury manages collateral for group currencies: + +- Handles minting (indirectly) and redemption of group Circles +- To mint group circles, the minter must act through the Hub contract: + - either by calling `Hub:groupMint()`, upon which the Hub will structure data for the treasury to forward the collateral to the correct vault of the group + - or over path-based transfers, Circles can be minted into group Circles on the fly + - if one sends collateral directly to the Standard Treasury without data or with incorrectly structured data, the treasury will reject the transfer to avoid that funds get lost as only the hub controls minting of group tokens + - if one sends tokens to the treasury with the correct data structure, bypassing the hub contract, the collateral will be locked in the treasury/vault, as the hub **will not mint your equivalent group Circles** +- To redeem group Cirlces for the underlying collateral from the `Vault`, the owner must send the group Circles to the treasury with a correctly structured data package: + - the treasury decodes the data to check whether the intent is to redeem + - the treasury passes the user data to the group mint policy, for it to determine the conditions of redemption (treasury is agnostic to data format for group mint policy) + - the treasury can execute the option of burning a portion of the collateral upon redemption + - the treasury can return the collateral to the redeemer -- but checks that the policy's burn amount and return amounts add up to the group currency amount +- `onERC1155Received`: Handles single token transfers (minting or redemption) +- `onERC1155BatchReceived`: Handles batch token transfers (minting) +- Acts as a factory for `Vaults`, deployed for each group to hold their collateral +- Creates Vaults for groups as needed + +Code: /src/treasury/StandardTreasury.sol + +#### Vaults + +Vaults securely store collateral for group currencies: + +- Deployed by `StandardTreasury` using a factory pattern +- External functions only accessible by `StandardTreasury` +- Each group has its own `Vault` to easily query the balance of the vault address for that group + +Code: /src/treasury/StandardVault.sol + +#### Mint Policy + +Groups can assign a policy contract of their chosing upon registering. Once registered the policy address is immutable, but a policy contract be written: + +- for one specific group, or +- to be reusable for many groups to rely on, +- to be stateful or stateless, +- can be parametrized with settable parameters with some governance +- can be deployed as an upgradeable proxy contract + +The `BaseMintPolicy` is the simplest possible definition for a sensible group policy. It serves as a reference implementation, but developers are invited to explore and build their own policies + +In general a group (mint) policy must be a contract that implements the rules for minting, burning, and redeeming group currencies: + +- Customizable for different group needs +- Default implementation (`BaseMintPolicy.sol`) allows all mints/burns and user-specified collateral for redemptions +- `beforeMintPolicy`: Validates minting requests +- `beforeBurnPolicy`: Validates burning requests +- `beforeRedeemPolicy`: Specifies redemption logic + +Code: /src/groups/BaseMintPolicy.sol + +#### System Interaction + +1. **Group Creation**: + - User calls `hub.registerGroup()` + - Hub assigns Standard Treasury + - Standard Treasury creates a Vault for the group upon first group mint +2. **Minting Group Circles**: + - Collateral transferred to Treasury + - Treasury forwards collateral to group's Vault + - Mint Policy consulted for approval + - Group Circles minted to user +3. **Redeeming Group Circles**: + - User sends group Circles to Treasury + - Treasury consults Mint Policy for redemption logic + - Vault returns specified collateral to user + - Part of collateral burned if specified by policy + +This system provides a flexible framework for creating and managing group currencies within the Circles ecosystem. It allows for customizable minting and redemption policies while ensuring proper collateralization and secure storage of assets. + +#### Remarks +- Circles permits the creation of groups with custom treasury contracts. However, the community should approach such groups with caution until these foreign treasury contracts have been thoroughly vetted. +- Groups have the capability to trust and accept other groups as collateral. This feature enables the construction of sophisticated hierarchical group structures. However, it also introduces the possibility of cyclical collateralization. While this doesn't increase the total number of Circles in circulation, it does allow for arbitrary inflation of collateral through repeated cyclic collateralization. To mitigate this risk, groups may implement protective measures within their group mint policy. + +## Token Representations + +### Circles (ERC1155) + +The core representation of Circles currencies uses the ERC1155 standard, allowing for efficient management of multiple token types (personal and group currencies) within a single contract: + +- Code: /src/circles/Circles.sol +- Code: /src/circles/ERC1155.sol +- Code: /src/circles/DiscountedBalances.sol +- Code: /src/circles/Demurrage.sol + +### ERC20 Wrappers +To enhance compatibility with existing smart contract ecosystems, Circles provides two types of ERC20 wrappers: + +- **Demurrage ERC20**: This wrapper represents Circles with demurrage applied. It results in rebalancing amounts, reflecting the daily decrease in the balances over time over all Circles. +- **Inflationary ERC20**: This wrapper represents Circles in their inflationary form. Balances remain static (when not transacted), but the issuance rate for personal Circles mints increases daily. This mechanism offsets the static supply of Circles in circulation. + +For every Circles identifier (human or group Circles) either/both ERC20 contract can be deployed upon demand by calling `hub:wrap()`, and it will ensure the ERC20 contract is deployed if it doesn't already exist. ERC20 contracts can also be created explicitly before wrapping. + +If the ERC20 contract already exists, one can also wrap the ERC1155 Circles into ERC20 by directly sending (the correct Circles) to the relevant ERC20 contract. + +Both demurrage and inflationary ERC20 Circles can be converted back into demurraged ERC1155 Circles by calling `ECR20:unwrap()` as the owner of a balance on the desired ERC20 contract. + +Both approaches allow Circles to interact more seamlessly with standard ERC20-compatible platforms and protocols while preserving the core economic principles of the Circles system. + +ERC20 contracts also implement [ERC-2612](https://eips.ethereum.org/EIPS/eip-2612), aka `ERC20Permit`. + +- Code: /src/lift/DemurrageCircles.sol +- Code: /src/lift/ERC20DiscountedBalances.sol +- Code: /src/lift/InflationaryCircles.sol +- Code: /src/lift/ERC20InflationaryBalances.sol +- Code: /src/circles/BatchedDemurrage.sol +- Code: /src/circles/Demurrage.sol + +### ERC20Lift + +The ERC20Lift contract serves as a factory-bridge between the ERC1155 and ERC20 representations, ensuring ERC20 contracts are deployed (ahead of time). + +Code: /src/lift/ERC20Lift.sol + +## Circles v1 Components (Legacy) + +### Hub v1 + +The original Hub contract from Circles v1. Hub v1 only has a concept of human avatars ("users") and organizations. Groups have been built on top of Hub v1. Therefore when migrating tokens from Hub v1 to Hub v2, all tokens are all associated to a human avatar (as an organization does not have its own token). + +- Legacy Code: Circles-Contracts/contracts/Hub.sol (v1) +- Legacy Documentation: Join Circles handbook (v1) + +### Token + +The individual ERC20 token contracts for personal currencies in Circles v1 are deployed from the hub as a factory pattern upon a user (human) registering. + +Legacy Code: Circles-Contracts/contracts/Token.sol (v1) + +## Conclusion + +Circles v2 architecture key points: + +- ERC1155 implementation for improved token management +- Dual token representation: Demurrage and Inflationary ERC20 wrappers +- Native group functionality with customizable treasury and mint policies +- Improved settlement efficiency through batched path-transfers using flow matrix representation +- Backward compatibility with v1 through migration support, and reactivation of frozen accounts in v1 +- Technical debt reduction from Hub v1 + +The architecture maintains a centralized hub while allowing component-level flexibility. This design facilitates future extensions and improvements without compromising system integrity or existing functionality. The flow matrix representation for batched transfers significantly enhances the system's scalability and transaction throughput. \ No newline at end of file diff --git a/docs/docs/index.md b/docs/docs/index.md new file mode 100644 index 0000000..d876949 --- /dev/null +++ b/docs/docs/index.md @@ -0,0 +1,75 @@ +# Circles Documentation + +Welcome to the Circles documentation. This guide will help you understand the Circles project, its architecture, and core functionalities. + +## Table of Contents + +1. [Introduction to Circles](introduction.md) + - Brief overview of the Circles project + - Purpose and goals of Circles + - Key concepts: personal currencies, trust networks, and demurrage + - Total Supply and Equilibrium + +2. [Architectural Overview](architecture.md) + - System Architecture Diagram + - Core Components + - Token Representations + - Circles v1 Components (legacy) + +3. [Advanced Topics](advanced-topics/index.md) + - [Inflation and demurrage calculations](advanced-topics/inflation-demurrage.md) + - [Path-based transactions and flow matrices](advanced-topics/path-based-transactions.md) + + + + + + \ No newline at end of file diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md new file mode 100644 index 0000000..c8a0629 --- /dev/null +++ b/docs/docs/introduction.md @@ -0,0 +1,105 @@ +# Introduction to Circles + +## Brief Overview + +Circles is a digital protocol designed to create and distribute fair and social money through personal currencies. It harnesses the power of decentralized technology to implement a system of interconnected, individual economic units that collectively form a larger, more equitable economic network. + +The Circles protocol is built on the Gnosis Chain blockchain, utilizing smart contracts to manage the creation, distribution, and transfer of personal currencies. At its core, Circles employs an ERC1155 multi-token standard, enabling efficient handling of multiple token types (different personal and group Circles -- more on groups later) within a single contract. + +## Purpose and Goals of Circles + +The primary purpose of Circles is to create a more inclusive and sustainable economic system through the equitable issuance of money to all participants. In pursuing this vision, Circles aims to: + +1. Introduce community currencies that reduce economic inequality by ensuring a baseline level of economic participation for all. +2. Foster community connections and strengthen local economies through trust-based currency networks. +3. Promote sustainable economic growth by implementing a demurrage system that discourages hoarding and encourages circulation. +4. Provide a flexible framework for various economic experiments and community-driven initiatives. +5. Empower individuals and communities to have greater control over their economic interactions and monetary systems. + +## Key Concepts + +### Personal Currencies + +In the Circles ecosystem, each individual can mint their own personal currency. This feature of the protocol empowers every participant to become an issuer of their own personal Circles. The Hub contract manages both the registration of individuals (referred to as "humans" in the contract) and the issuance of their personal currencies. + +Key points about personal currencies: + +- Each registered human can mint a deterministic amount of their personal currency at a consistent rate of one Circle per hour. +- Minting is retroactive, allowing claims for up to 14 days of past elapsed time. +- The mintable amount is calculated based on the number of complete hours passed since the last issuance of Circles. +- Circles undergo daily demurrage at a rate equivalent to 7% per year. Issuance for past days accounts for this demurrage, ensuring fair distribution over time. (Further details on demurrage are discussed in a later section) +- Personal currencies are represented as unique tokens within the ERC1155 multi-token system, with each token ID derived from the address of the human's avatar. +- The `personalMint()` function in the Hub contract manages the minting process. + +This system ensures a fair, time-based issuance of personal currencies while implementing mechanisms to encourage active participation in the Circles economy. + +### Trust Networks + +Trust is a fundamental concept in the Circles protocol. It allows personal currencies to become valuable and transferable within the network. The trust system is implemented in the Hub contract through the following mechanisms: + +- People can establish trust relationships with other entities (people, organizations, or groups) using the `trust()` function. +- Trust relationships can be set with expiration times, allowing for dynamic trust networks. Alternatively, trust can be established indefinitely by setting the expiration to the maximum possible future time. +- The trust network is leveraged to enable transitive transfers of Circles along paths of trust. The `isPermittedFlow()` function verifies if a transitive transfer is permissible based on the trust relationships between the involved parties and the specific currency being transferred. +- Circles still function as a normal token, for explicit `ERC1155:safe(Batch)TransferFrom()` or `ERC20:transfer()` no constraints of the transitive transfer of the trust network apply. +- Trust relationships can be established not only between individuals but also between people, organizations, and groups, creating a diverse and interconnected economic ecosystem. + +Trust networks enable: + +- Path-based transactions, where currencies can be exchanged through chains of trust connections. +- Community-building, as users create economic connections with individuals and entities they trust. +- A decentralized approach to currency valuation and acceptance, based on social and organizational relationships rather than centralized authority. +- Flexible economic interactions between various types of actors within the Circles ecosystem. + +### Demurrage + +Demurrage in currency systems is an economic concept where a cost is associated with holding a currency over time. In Circles, this mechanism is implemented to encourage circulation of the currency and mitigate extreme inequities. Demurrage ensures that at any future point, one hour can be issued as one Circle, while maintaining a maximum total supply of Circles. + +In the Hub contract, all balances and transfer amounts used as function arguments are, by default, understood as demurraged amounts for the present day. However, to facilitate interactions with other smart contracts, Circles also offers a static (non-rebalancing) token representation. This static, inflationary representation of all balances and transfer functions is available both in the ERC1155 and ERC20 representations. + +The Circles contract incorporates a demurrage system with the following key characteristics: + +- Circles have a 7% p.a. demurrage cost applied to them in the contracts, rebalancing the amounts. +- Demurrage is applied on an equivalent daily basis, ensuring that during a period of a day balances are not continuously adjusted. +- Balances are stored as "discounted balances" that automatically decrease in value over time. +- The `calculateIssuance()` function in the Circles contract factors in demurrage when determining the amount of new currency to mint for an individual. +- Demurrage applies uniformly to both personal currencies and group currencies. + +This system ensures that: + +- The currency remains active and circulating within the community. +- Circles are issued equitably across individuals and over time. +- A clear unit of account is established, with one Circle representing one hour of an individual's time. +- Circles serves as both a robust store of value and an effective means of exchange. + +By integrating these key concepts - personal currencies, trust networks, and demurrage - Circles creates an economic system that aims to provide a fairly issued, socially-rooted monetary framework, foster community connections and promote active participation in the local economy. + +## Total Supply and Equilibrium + +The Circles protocol implements an economic model where the minting of new Circles and the demurrage mechanism work together to create an equilibrium in the total supply. This balance is crucial for maintaining the long-term stability and fairness of the system. + +Key aspects of the total supply mechanism: + +1. Issuance Rate: Each registered human can mint one Circle per hour, which translates to 24 Circles per day or 8760 Circles per year (not accounting for leap years). +2. Demurrage Rate: All Circles undergo a 7% annual demurrage, applied on a daily basis. +3. Equilibrium Point: The issuance and demurrage rates are carefully calibrated so that they balance each other out at a specific point, creating a maximum total supply for each personal currency. +4. Maximum Total Supply Calculation: + - Let x be the maximum total supply in Circles. + - Annual issuance: 8760 Circles + - Annual demurrage: 7% of x + - At equilibrium: 8760 = 0.07x + - Solving for x: x = 8760 / 0.07 = 125,142.86 Circles +5. Dynamic Balance: As new Circles are minted, they contribute to the total supply. However, the demurrage mechanism ensures that the total value of existing Circles decreases over time. This creates a dynamic where the total supply approaches but never exceeds the equilibrium point. +6. Practical Implications: + - For a new participant, after 14 years of continuous minting they would reach 62% of the maximum supply, assuming no spending. To reach 95% of the total supply, 42.79 years of minting is required. + - In practice, as people might not mint all their Circles, or Circles get burnt in usage the total supply of their personal Circles token will fluctuate below this theoretical maximum. + - Each person, organization, group or account can earn Circles from others though in an open economy so anyone's balance can well exceed 125k Circles by holding a variety of different Circles in their wallet. +7. System-wide Effects: While each personal currency has its own maximum supply, the trust network and transferability of Circles create a larger, interconnected economy. The total supply in effect can be thought of as a multiple of 125k CRC for every non-sybil human participating in the network. + +This equilibrium mechanism is crucial for several reasons: + +- It ensures long-term stability in the value of Circles. +- It maintains fairness by preventing early adopters from gaining disproportionate economic power. +- It creates a predictable and sustainable monetary policy for the Circles ecosystem. + +The total supply mechanism is implemented through the interaction of the `personalMint()` function and the demurrage calculations in the Circles contract. +By dynamically managing the total supply through this issuance and demurrage equilibrium, Circles creates a fair, stable, and sustainable economic system that aligns with its goals of reducing inequality and fostering community connections. \ No newline at end of file diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml new file mode 100644 index 0000000..138d9ed --- /dev/null +++ b/docs/mkdocs.yml @@ -0,0 +1,36 @@ +site_name: Circles Protocol +theme: readthedocs +site_name: Circles Protocol +theme: readthedocs +nav: + - Home: index.md + - About: about.md + - Introduction: introduction.md + - Architectural Overview: architecture.md + # - Core Functionality: + # - Overview: core-functionality/index.md + # - Hub Contract: core-functionality/hub-contract.md + # - Circles Contract: core-functionality/circles-contract.md + # - Key Features: key-features.md + # - Contract Interactions: contract-interactions.md + - Advanced Topics: + # - Overview: advanced-topics/index.md + - Inflation and Demurrage: advanced-topics/inflation-demurrage.md + - Path-based Transactions: advanced-topics/path-based-transactions.md + # - Group Mint Policies: advanced-topics/group-mint-policies.md + # - User Guides: + # - Overview: user-guides/index.md + # - Registration: user-guides/registration.md + # - Trust Management: user-guides/trust-management.md + # - Minting and Transferring: user-guides/minting-transferring.md + # - Group Currencies: user-guides/group-currencies.md + # - Developer Resources: + # - Overview: developer-resources/index.md + # - Contract ABIs: developer-resources/contract-abis.md + # - Integration Guidelines: developer-resources/integration-guidelines.md + # - Best Practices: developer-resources/best-practices.md + # - Glossary: glossary.md + # - Appendices: + # - Overview: appendices/index.md + # - Contract Addresses: appendices/contract-addresses.md + # - External Resources: appendices/external-resources.md diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 0000000..b854bca --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1 @@ +mkdocs \ No newline at end of file diff --git a/docs/unwritten-docs/appendices/contract-addresses.md b/docs/unwritten-docs/appendices/contract-addresses.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/appendices/external-resources.md b/docs/unwritten-docs/appendices/external-resources.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/appendices/index.md b/docs/unwritten-docs/appendices/index.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/contract-interactions.md b/docs/unwritten-docs/contract-interactions.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/core-functionality/circles-contract.md b/docs/unwritten-docs/core-functionality/circles-contract.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/core-functionality/hub-contract.md b/docs/unwritten-docs/core-functionality/hub-contract.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/core-functionality/index.md b/docs/unwritten-docs/core-functionality/index.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/developer-resources/best-practices.md b/docs/unwritten-docs/developer-resources/best-practices.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/developer-resources/contract-abis.md b/docs/unwritten-docs/developer-resources/contract-abis.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/developer-resources/index.md b/docs/unwritten-docs/developer-resources/index.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/developer-resources/integration-guidelines.md b/docs/unwritten-docs/developer-resources/integration-guidelines.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/glossary.md b/docs/unwritten-docs/glossary.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/key-features.md b/docs/unwritten-docs/key-features.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/user-guides/group-currencies.md b/docs/unwritten-docs/user-guides/group-currencies.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/user-guides/index.md b/docs/unwritten-docs/user-guides/index.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/user-guides/minting-transferring.md b/docs/unwritten-docs/user-guides/minting-transferring.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/user-guides/registration.md b/docs/unwritten-docs/user-guides/registration.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/unwritten-docs/user-guides/trust-management.md b/docs/unwritten-docs/user-guides/trust-management.md new file mode 100644 index 0000000..e69de29 diff --git a/src/hub/Hub.sol b/src/hub/Hub.sol index 3f77bc3..b99a4a9 100644 --- a/src/hub/Hub.sol +++ b/src/hub/Hub.sol @@ -538,8 +538,6 @@ contract Hub is Circles, TypeDefinitions, IHubErrors { return erc20Wrapper; } - // todo: if we have space, possibly have a wrapBatch function - function operateFlowMatrix( address[] calldata _flowVertices, FlowEdge[] calldata _flow, @@ -638,15 +636,15 @@ contract Hub is Circles, TypeDefinitions, IHubErrors { * @return permitted true if the flow is permitted, false otherwise */ function isPermittedFlow(address _from, address _to, address _circlesAvatar) public view returns (bool) { - // if receiver does not trust the Circles being sent, then the flow is not permitted regardless + // Check if receiver trusts the Circles being sent if (uint256(trustMarkers[_to][_circlesAvatar].expiry) < block.timestamp) return false; - // if the advanced usage flag does not enables consented flow, - // then the uni-directional trust is sufficient, ie. no consented flow applies for sender + + // Check if sender has enabled consented flow if (advancedUsageFlags[_from] & ADVANCED_FLAG_ENABLE_CONSENTEDFLOW == bytes32(0)) { - return true; + return true; // If not enabled, standard trust is sufficient } - // however, recursive consented flow also requires sender to trust the receiver - // and for that receiver themselves to have consented flow enabled + // For consented flow, check sender trusts receiver, + // and receiver has consented flow enabled too return ( uint256(trustMarkers[_from][_to].expiry) >= block.timestamp && advancedUsageFlags[_to] & ADVANCED_FLAG_ENABLE_CONSENTEDFLOW != bytes32(0) diff --git a/src/hub/TypeDefinitions.sol b/src/hub/TypeDefinitions.sol index ba5d4ce..79665bf 100644 --- a/src/hub/TypeDefinitions.sol +++ b/src/hub/TypeDefinitions.sol @@ -17,7 +17,7 @@ contract TypeDefinitions { struct FlowEdge { uint16 streamSinkId; - uint192 amount; // todo: set this to uint192 (align with demurrage), and leave it to compiler to pad + uint192 amount; } struct Stream { diff --git a/src/lift/ERC20DiscountedBalances.sol b/src/lift/ERC20DiscountedBalances.sol index 139d406..9efbb13 100644 --- a/src/lift/ERC20DiscountedBalances.sol +++ b/src/lift/ERC20DiscountedBalances.sol @@ -2,11 +2,11 @@ pragma solidity >=0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -import "../circles/Demurrage.sol"; +import "../circles/BatchedDemurrage.sol"; import "../errors/Errors.sol"; import "./ERC20Permit.sol"; -contract ERC20DiscountedBalances is ERC20Permit, Demurrage, IERC20 { +contract ERC20DiscountedBalances is ERC20Permit, BatchedDemurrage, IERC20 { // Constants // State variables