├── .devcontainer ├── Dockerfile ├── devcontainer.json ├── docker-compose.yaml ├── scripts │ └── install_solidity.sh └── starship.toml ├── .gitattributes ├── .github ├── .dependabot.yml └── workflows │ ├── build.yml │ ├── build_with_foundry.yml │ ├── errorcodes_events.yml │ └── scripts │ ├── list_all_errorcodes.sh │ ├── prepare_environment.sh │ ├── validate_errorcodes.sh │ └── validate_events.sh ├── .gitignore ├── .gitmodules ├── .prettierrc ├── .solhint.json ├── .solhint.prettier.json ├── .vscode └── settings.json ├── Dockerfile ├── LICENSE ├── README.md ├── brownie-config.yaml ├── contracts ├── components │ ├── BasicRiskpool.sol │ ├── Component.sol │ ├── IComponent.sol │ ├── IOracle.sol │ ├── IProduct.sol │ ├── IRiskpool.sol │ ├── Oracle.sol │ ├── Product.sol │ └── Riskpool.sol ├── modules │ ├── IAccess.sol │ ├── IBundle.sol │ ├── IComponentEvents.sol │ ├── ILicense.sol │ ├── IPolicy.sol │ ├── IPool.sol │ ├── IQuery.sol │ ├── IRegistry.sol │ └── ITreasury.sol ├── services │ ├── IComponentOwnerService.sol │ ├── IInstanceOperatorService.sol │ ├── IInstanceService.sol │ ├── IOracleService.sol │ ├── IProductService.sol │ └── IRiskpoolService.sol ├── shared │ └── ICoreProxy.sol └── tokens │ └── IBundleToken.sol ├── docs ├── ayii_product_new_application.md ├── ayii_product_trigger_oracle.md └── component_states.md ├── foundry.toml ├── package-lock.json ├── package.json └── tests_foundry └── .keep /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster 2 | ARG VARIANT=3-bullseye 3 | FROM mcr.microsoft.com/devcontainers/python:${VARIANT} 4 | 5 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 6 | ARG NODE_VERSION="16" 7 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 8 | 9 | # install mcfly as root 10 | RUN curl -LSfs https://raw.githubusercontent.com/cantino/mcfly/master/ci/install.sh | sh -s -- --git cantino/mcfly 11 | 12 | USER vscode 13 | 14 | # Shell customizations 15 | 16 | # 1) Install and configure starship.rs prompt 17 | RUN curl -fsSL https://starship.rs/install.sh | sh -s -- --yes 18 | RUN echo "eval \"\$(starship init bash)\"" >> ~/.bashrc && echo "eval \"\$(starship init zsh)\"" >> ~/.zshrc 19 | RUN mkdir -p /home/vscode/.config/ 20 | COPY .devcontainer/starship.toml /home/vscode/.config/starship.toml 21 | 22 | # 2) install thefuck 23 | RUN pip3 install thefuck --user \ 24 | && echo 'eval "$(thefuck --alias)"' >> ~/.bashrc \ 25 | && echo 'eval "$(thefuck --alias)"' >> ~/.zshrc 26 | 27 | # 3) install mcfly config 28 | RUN echo 'eval "$(mcfly init zsh)"' >> ~/.zshrc \ 29 | && touch ~/.zsh_history 30 | 31 | 32 | # Install brownie & other devtools 33 | 34 | # COPY requirements.txt /tmp/pip-tmp/ 35 | RUN wget https://raw.githubusercontent.com/eth-brownie/brownie/master/requirements.txt -O /tmp/pip-requirements.txt 36 | 37 | RUN python3 -m pip install --user pipx \ 38 | && python3 -m pipx ensurepath \ 39 | && pipx install eth-brownie 40 | 41 | # [Optional] Uncomment this line to install global node packages. 42 | RUN npm install -g ganache solhint prettier prettier-plugin-solidity solhint-plugin-prettier 43 | 44 | # download required solidity compiler 45 | COPY .devcontainer/scripts/install_solidity.sh /tmp 46 | RUN /tmp/install_solidity.sh 47 | 48 | ARG VERSION_OPEN_ZEPPELIN=4.7.3 49 | RUN wget -O /tmp/v${VERSION_OPEN_ZEPPELIN}.tar.gz https://github.com/OpenZeppelin/openzeppelin-contracts/archive/refs/tags/v${VERSION_OPEN_ZEPPELIN}.tar.gz 50 | RUN mkdir -p /home/vscode/.brownie/packages/OpenZeppelin \ 51 | && cd /home/vscode/.brownie/packages/OpenZeppelin \ 52 | && tar xvfz /tmp/v${VERSION_OPEN_ZEPPELIN}.tar.gz \ 53 | && mv openzeppelin-contracts-${VERSION_OPEN_ZEPPELIN} openzeppelin-contracts@${VERSION_OPEN_ZEPPELIN} 54 | 55 | # [Optional] Uncomment this section to install additional OS packages. 56 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 57 | # && apt-get -y install --no-install-recommends 58 | 59 | # install foundry 60 | RUN curl -L https://foundry.paradigm.xyz | bash 61 | RUN echo 'export PATH="$PATH:/home/vscode/.foundry/bin"' >> ~/.zshrc 62 | RUN /home/vscode/.foundry/bin/foundryup 63 | 64 | WORKDIR /workspace 65 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.183.0/containers/ruby 3 | { 4 | "name": "gif-interfaces", 5 | "dockerComposeFile": "docker-compose.yaml", 6 | "service": "brownie", 7 | "workspaceFolder": "/workspace", 8 | // Set *default* container specific settings.json values on container create. 9 | 10 | // "features": { 11 | // "github-cli": "latest", 12 | // "docker-from-docker": { 13 | // "version": "latest", 14 | // "moby": true 15 | // } 16 | // }, 17 | 18 | "customizations": { 19 | "vscode": { 20 | "settings": { 21 | //"terminal.integrated.shell.linux": "/bin/bash" 22 | "editor.fontFamily": "'JetBrainsMono Nerd Font Mono', Menlo, Monaco, 'Courier New', monospace", 23 | "editor.fontSize": 13, 24 | }, 25 | "extensions": [ 26 | "ms-python.python", 27 | "ms-python.vscode-pylance", 28 | "juanblanco.solidity", 29 | "tintinweb.solidity-visual-auditor", 30 | "github.vscode-pull-request-github", 31 | "github.copilot", 32 | "mhutchie.git-graph", 33 | "eamodio.gitlens", 34 | "gruntfuggly.todo-tree", 35 | "oderwat.indent-rainbow", 36 | "johnpapa.vscode-peacock", 37 | "vikas.code-navigation", 38 | ], 39 | } 40 | }, 41 | 42 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 43 | "forwardPorts": [8000], 44 | 45 | // Use 'postCreateCommand' to run commands after the container is created. 46 | "postCreateCommand": "touch .env && brownie compile --all && python --version", 47 | 48 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 49 | "remoteUser": "vscode" 50 | } -------------------------------------------------------------------------------- /.devcontainer/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | 4 | services: 5 | brownie: 6 | # See https://aka.ms/vscode-remote/containers/non-root for details. 7 | user: vscode 8 | build: 9 | context: .. 10 | dockerfile: .devcontainer/Dockerfile 11 | args: 12 | VARIANT: 3.10-bookworm 13 | USER_UID: 1000 14 | USER_GID: 1000 15 | INSTALL_NODE: "true" 16 | NODE_VERSION: "lts/*" 17 | volumes: 18 | - ..:/workspace:cached 19 | #- $HOME/.ssh/:/home/vscode/.ssh/ # Mount the ssh folder to authenticate with github 20 | # Overrides default command so things don't shut down after the process ends. 21 | command: sleep infinity 22 | -------------------------------------------------------------------------------- /.devcontainer/scripts/install_solidity.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | mkdir -p /home/vscode/.solcx/ 4 | 5 | if [[ $(uname -m) == 'aarch64' ]]; then 6 | wget -O /home/vscode/.solcx/solc-v0.8.2 https://github.com/nikitastupin/solc/raw/main/linux/aarch64/solc-v0.8.2 7 | else 8 | wget -O /home/vscode/.solcx/solc-v0.8.2 https://binaries.soliditylang.org/linux-amd64/solc-linux-amd64-v0.8.2+commit.661d1103 9 | fi 10 | 11 | chmod 755 /home/vscode/.solcx/solc* 12 | -------------------------------------------------------------------------------- /.devcontainer/starship.toml: -------------------------------------------------------------------------------- 1 | [nodejs] 2 | disabled = true 3 | 4 | [package] 5 | disabled = true 6 | 7 | [python] 8 | detect_folders = ["scripts","tests"] 9 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | *.vy linguist-language=Python 3 | -------------------------------------------------------------------------------- /.github/.dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | # - package-ecosystem: "docker" 9 | # directory: "/.devcontainer" 10 | # schedule: 11 | # interval: "weekly" 12 | - package-ecosystem: "github-actions" 13 | directory: "/" 14 | schedule: 15 | interval: "weekly" 16 | 17 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ main, develop ] 7 | tags: 8 | - '*' 9 | pull_request: 10 | branches: [ main, develop ] 11 | 12 | jobs: 13 | compile: 14 | name: Compile contracts 15 | # only run if tests successfull and contracts have changed 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v3 20 | 21 | - name: Set up Python 22 | uses: actions/setup-python@v4 23 | with: 24 | python-version: '3.10' 25 | - name: Setup node environment 26 | uses: actions/setup-node@v3 27 | with: 28 | node-version: 16 29 | 30 | - name: Prepare environment 31 | run: .github/workflows/scripts/prepare_environment.sh 32 | 33 | - name: Compile contracts 34 | run: brownie compile --all 35 | 36 | - name: Install solhint linter 37 | run: npm install --global solhint 38 | 39 | - name: Run solhint linter 40 | run: solhint contracts/**/*.sol 41 | 42 | - name: Archive build artifacts 43 | uses: actions/upload-artifact@v3 44 | with: 45 | name: contracts 46 | path: | 47 | build 48 | 49 | 50 | publish: 51 | name: Publish package to npmjs 52 | runs-on: ubuntu-latest 53 | permissions: 54 | contents: read 55 | id-token: write 56 | needs: [compile] 57 | steps: 58 | - name: Checkout 59 | uses: actions/checkout@v3 60 | 61 | - name: Download build artifacts 62 | uses: actions/download-artifact@v3 63 | with: 64 | name: contracts 65 | path: build 66 | 67 | - name: Setup node environment 68 | uses: actions/setup-node@v3 69 | with: 70 | node-version: 18 71 | registry-url: 'https://registry.npmjs.org' 72 | # latest npm required for provenance 73 | - run: npm install -g npm 74 | 75 | - run: npm ci 76 | 77 | - name: Set build version identifier 78 | run: npm version "`npm version patch --no-git-tag-version`-`git rev-parse --short HEAD`" --no-git-tag-version 79 | 80 | - run: npm publish --tag next --provenance 81 | env: 82 | NODE_AUTH_TOKEN: ${{ secrets.NPMJS_ACCESS_TOKEN }} 83 | -------------------------------------------------------------------------------- /.github/workflows/build_with_foundry.yml: -------------------------------------------------------------------------------- 1 | name: Build with Foundry 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ main, develop ] 7 | tags: 8 | - '*' 9 | pull_request: 10 | branches: [ main, develop ] 11 | 12 | jobs: 13 | test: 14 | name: Compile and run tests with foundry 15 | # only run if contracts have changed 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v3 20 | with: 21 | submodules: recursive 22 | 23 | - name: Install Foundry 24 | uses: foundry-rs/foundry-toolchain@v1 25 | 26 | - name: Build 27 | run: forge build 28 | 29 | # currently no tests 30 | # - name: Execute tests 31 | # run: forge test -vvvv 32 | 33 | -------------------------------------------------------------------------------- /.github/workflows/errorcodes_events.yml: -------------------------------------------------------------------------------- 1 | name: Error codes and events 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ main, develop ] 7 | tags: 8 | - '*' 9 | pull_request: 10 | 11 | jobs: 12 | inspect: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3 17 | 18 | - name: Validate error codes 19 | run: .github/workflows/scripts/validate_errorcodes.sh 20 | 21 | - run: mkdir tmp 22 | 23 | - name: Find all error codes 24 | run: .github/workflows/scripts/list_all_errorcodes.sh > tmp/errorcodes.md 25 | 26 | - name: Archive error codes 27 | uses: actions/upload-artifact@v3 28 | with: 29 | name: error-codes 30 | path: tmp/errorcodes.md 31 | 32 | - name: Validate events 33 | run: .github/workflows/scripts/validate_events.sh 34 | -------------------------------------------------------------------------------- /.github/workflows/scripts/list_all_errorcodes.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | printf "|Errorcode|File|\n|:--|:--|\n" 4 | egrep -or "(ERROR\:[A-Z0-9_-]+\:[A-Z0-9_-]+)" contracts/* | sed -E "s/([^\:]+)\:(.+)/|\2|\1|/g" | sort 5 | -------------------------------------------------------------------------------- /.github/workflows/scripts/prepare_environment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/env bash 2 | 3 | # Install required solidity compiler version 4 | mkdir -p ~/.solcx/ 5 | wget -O ~/.solcx/solc-v0.8.2 https://binaries.soliditylang.org/linux-amd64/solc-linux-amd64-v0.8.2+commit.661d1103 6 | chmod 755 ~/.solcx/solc* 7 | 8 | # Retrieve brownie dependencies 9 | export VERSION_OPEN_ZEPPELIN=4.7.3 10 | wget -O /tmp/v${VERSION_OPEN_ZEPPELIN}.tar.gz https://github.com/OpenZeppelin/openzeppelin-contracts/archive/refs/tags/v${VERSION_OPEN_ZEPPELIN}.tar.gz 11 | mkdir -p ~/.brownie/packages/OpenZeppelin 12 | cd ~/.brownie/packages/OpenZeppelin 13 | tar xvfz /tmp/v${VERSION_OPEN_ZEPPELIN}.tar.gz 14 | mv openzeppelin-contracts-${VERSION_OPEN_ZEPPELIN} openzeppelin-contracts@${VERSION_OPEN_ZEPPELIN} 15 | 16 | # Install ganache 17 | npm install --global ganache 18 | 19 | # Install brownie 20 | python3 -m pip install --user pipx 21 | python3 -m pipx ensurepath 22 | pipx install eth-brownie 23 | 24 | -------------------------------------------------------------------------------- /.github/workflows/scripts/validate_errorcodes.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DUPES=`egrep -or "(ERROR\:[A-Z0-9_-]+)" contracts/* | sort | uniq -cd` 4 | 5 | if [ -z "$DUPES" ]; then 6 | echo "No duplicate error codes found" 7 | else 8 | echo "Duplicate error codes found:" 9 | echo "$DUPES" 10 | exit 1 11 | fi 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/scripts/validate_events.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # match any string that starts with "event" and its name does not start with Log 4 | EVT=`grep -orP '$\s+event\s+(?!Log)(\w+)\s*' contracts/*` 5 | 6 | if [ -z "$EVT" ]; then 7 | echo "All event definitions start with 'Log'" 8 | else 9 | echo "Found event definitions not starting with 'Log':" 10 | echo "$EVT" 11 | exit 1 12 | fi 13 | 14 | # check for event defintions with attributes 'policyId', 'applicationId' or 'metadataId' 15 | EVT=`grep -orP '$\s+event\s+\w+\s*\(.*(policyId|applicationId|metadataId).*\)' contracts/*` 16 | 17 | if [ -z "$EVT" ]; then 18 | echo "No event definitions contain attributes 'policyId', 'applicationId' or 'metadataId'" 19 | else 20 | echo "Found event definitions containing attributes 'policyId', 'applicationId' or 'metadataId':" 21 | echo "$EVT" 22 | exit 1 23 | fi 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .env 3 | .history 4 | .hypothesis/ 5 | build/ 6 | build_foundry/ 7 | reports/ 8 | /node_modules/ 9 | etherisc*.tgz 10 | 11 | cache/solidity-files-cache.json 12 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/openzeppelin-contracts"] 2 | path = lib/openzeppelin-contracts 3 | url = https://github.com/OpenZeppelin/openzeppelin-contracts 4 | [submodule "lib/forge-std"] 5 | path = lib/forge-std 6 | url = https://github.com/foundry-rs/forge-std 7 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "overrides": [ 3 | { 4 | "files": "*.sol", 5 | "options": { 6 | "endOfLine": "auto" 7 | } 8 | } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": [], 4 | "rules": { 5 | "compiler-version": ["error", "^0.8.0"], 6 | "func-visibility": ["warn", {"ignoreConstructors": true}], 7 | "reason-string": ["warn",{"maxLength": 64}] 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.solhint.prettier.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "solhint:recommended", 3 | "plugins": ["prettier"], 4 | "rules": { 5 | "compiler-version": ["error", "^0.8.0"], 6 | "func-visibility": ["warn", {"ignoreConstructors": true}], 7 | "prettier/prettier": "warn" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "terminal.integrated.defaultProfile.linux": "zsh", 3 | "solidity.remappingsUnix": [ 4 | "@openzeppelin/=/home/vscode/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.7.0", 5 | ], 6 | "solidity.compileUsingRemoteVersion": "v0.8.2+commit.661d1103", 7 | "peacock.remoteColor": "#132F13", 8 | "workbench.colorCustomizations": { 9 | "activityBar.activeBackground": "#225322", 10 | "activityBar.background": "#225322", 11 | "activityBar.foreground": "#e7e7e7", 12 | "activityBar.inactiveForeground": "#e7e7e799", 13 | "activityBarBadge.background": "#13132d", 14 | "activityBarBadge.foreground": "#e7e7e7", 15 | "commandCenter.border": "#e7e7e799", 16 | "sash.hoverBorder": "#225322", 17 | "statusBar.background": "#132f13", 18 | "statusBar.foreground": "#e7e7e7", 19 | "statusBarItem.hoverBackground": "#225322", 20 | "statusBarItem.remoteBackground": "#132f13", 21 | "statusBarItem.remoteForeground": "#e7e7e7", 22 | "titleBar.activeBackground": "#132f13", 23 | "titleBar.activeForeground": "#e7e7e7", 24 | "titleBar.inactiveBackground": "#132f1399", 25 | "titleBar.inactiveForeground": "#e7e7e799" 26 | } 27 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # this dockerfile from https://github.com/eth-brownie/brownie 2 | FROM python:3.7 3 | 4 | # Set up code directory 5 | RUN mkdir -p /usr/src/app 6 | WORKDIR /usr/src/app 7 | 8 | # Install linux dependencies 9 | RUN apt-get update && apt-get install -y libssl-dev 10 | RUN apt-get update && apt-get install -y npm 11 | 12 | RUN npm install --global ganache 13 | 14 | RUN wget https://raw.githubusercontent.com/eth-brownie/brownie/master/requirements.txt 15 | 16 | RUN pip install -r requirements.txt 17 | RUN pip install eth-brownie 18 | 19 | # Add some aliases 20 | RUN echo "alias rm='rm -i'" >> /root/.bashrc 21 | RUN echo "alias l='ls -CF'" >> /root/.bashrc 22 | RUN echo "alias la='ls -A'" >> /root/.bashrc 23 | RUN echo "alias ll='ls -alF'" >> /root/.bashrc 24 | 25 | WORKDIR /projects 26 | 27 | ENTRYPOINT [ "bash" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Etherisc GmbH 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Build](https://github.com/etherisc/gif-interface/actions/workflows/build.yml/badge.svg) 2 | [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 3 | [![](https://dcbadge.vercel.app/api/server/cVsgakVG4R?style=flat)](https://discord.gg/Qb6ZjgE8) 4 | 5 | # GIF Interface Contracts 6 | 7 | This repository holds the necessary interfaces and base contracts to interact with an existing GIF instance. 8 | The repository is not intended to be used on its own. 9 | 10 | ## Repository settings 11 | 12 | The repository uses [Gitflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) . 13 | New features/fixes are to be based on the `develop` branch. 14 | Releases are to be created from the `main` or a `release/` branch. 15 | Hotfixes on releases are to based on the affected `release/` or the `main` branch. 16 | 17 | Github Actions will automatically publish npm packages (with tag `next`) to npm.js containing the latest contracts. 18 | The only exception is the `main` branch, which requires manual releases using `npm publish` (without any tags). 19 | 20 | ## Clone Repo 21 | 22 | ``` 23 | git clone https://github.com/etherisc/gif-interface.git 24 | cd gif-interface 25 | ``` 26 | 27 | ## Fully configure IDE 28 | 29 | To use our fully configured IDE see the instructions at [https://github.com/etherisc/gif-sandbox/blob/master/docs/development_environment.md](https://github.com/etherisc/gif-sandbox/blob/master/docs/development_environment.md). 30 | In this case you can skip the next two steps as the _devcontainer_ is based on the (updated) _brownie_ image. 31 | 32 | 33 | ## Create Brownie Docker Image 34 | 35 | [Brownie](https://eth-brownie.readthedocs.io/en/stable) is used for development of the contracts in this repository. 36 | 37 | Alternatively to installing a python development environment and the brownie framework, wokring with Brownie is also possible via Docker. 38 | For this, build the brownie Docker image as shown below. 39 | The Dockerfile in this repository is a trimmed down version from [Brownie Github]((https://github.com/eth-brownie/brownie)) 40 | 41 | ```bash 42 | docker build -t brownie . 43 | ``` 44 | 45 | ## Run Brownie Container 46 | 47 | ```bash 48 | docker run -it --rm -v $PWD:/projects brownie 49 | ``` 50 | 51 | ## Compile the GIF Interface Contracts 52 | 53 | Inside the brownie container compile the contracts/interfaces 54 | 55 | ```bash 56 | brownie compile --all 57 | ``` 58 | 59 | ## Run linter 60 | 61 | Linter findings are shown automatically in vscode. To execute it manually, run the following command: 62 | 63 | ```bash 64 | solhint contracts/**/*.sol 65 | ``` 66 | and including _prettier_ formatting 67 | 68 | ```bash 69 | solhint --config .solhint.prettier.json contracts/**/*.sol 70 | ``` 71 | 72 | ## Publish release to NPMJS 73 | 74 | ```bash 75 | npm ci 76 | npm version patch/minor/major --no-git-tag-version 77 | npm publish 78 | git commit -m 'bump version' 79 | ``` 80 | 81 | 82 | ## Build and test using foundry 83 | 84 | Foundry is a new tool to build and test smart contracts. 85 | More documentation about foundry can be found in the foundry [https://book.getfoundry.sh/](Foundry book). 86 | 87 | The project is configured to use foundry. 88 | All contracts in the `contracts` folder can be compiled using foundry as well as brownie (results are stored in `build_foundry`). 89 | Foundry tests are writte in solidy and can be found in the `tests_foundry` folder (they need to be separate from brownie based tests). 90 | Dependencies are stored in the `lib` folder and are mapped in the `foundry.yaml` config file. 91 | 92 | To compile the contracts using foundry, run the following command: 93 | 94 | ```bash 95 | forge build 96 | ``` 97 | 98 | To run the foundry based tests, run the following command: 99 | 100 | ```bash 101 | forge test 102 | ``` 103 | -------------------------------------------------------------------------------- /brownie-config.yaml: -------------------------------------------------------------------------------- 1 | # brownie default values made explicit 2 | compiler: 3 | evm_version: null 4 | solc: 5 | version: 0.8.2 6 | optimizer: 7 | enabled: true 8 | runs: 200 9 | # https://eth-brownie.readthedocs.io/en/stable/compile.html#compiler-settings 10 | remappings: 11 | - "@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.7.3" 12 | vyper: 13 | version: null 14 | 15 | # packages below will be added to brownie 16 | # you may use 'brownie pm list' after 'brownie compile' 17 | # to list the packages installed via the dependency list below 18 | dependencies: 19 | # github dependency format: /@ 20 | - OpenZeppelin/openzeppelin-contracts@4.7.3 21 | -------------------------------------------------------------------------------- /contracts/components/BasicRiskpool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./Riskpool.sol"; 5 | import "../modules/IBundle.sol"; 6 | import "../modules/IPolicy.sol"; 7 | 8 | // basic riskpool always collateralizes one application using exactly one bundle 9 | abstract contract BasicRiskpool is Riskpool { 10 | 11 | event LogBasicRiskpoolBundlesAndPolicies(uint256 activeBundles, uint256 policies); 12 | event LogBasicRiskpoolCandidateBundleAmountCheck(uint256 index, uint256 bundleId, uint256 maxAmount, uint256 collateralAmount); 13 | 14 | // remember bundleId for each processId 15 | // approach only works for basic risk pool where a 16 | // policy is collateralized by exactly one bundle 17 | mapping(bytes32 /* processId */ => uint256 /** bundleId */) internal _collateralizedBy; 18 | uint32 private _policiesCounter = 0; 19 | 20 | constructor( 21 | bytes32 name, 22 | uint256 collateralization, 23 | uint256 sumOfSumInsuredCap, 24 | address erc20Token, 25 | address wallet, 26 | address registry 27 | ) 28 | Riskpool(name, collateralization, sumOfSumInsuredCap, erc20Token, wallet, registry) 29 | { } 30 | 31 | 32 | 33 | // needs to remember which bundles helped to cover ther risk 34 | // simple (retail) approach: single policy covered by single bundle 35 | // first bundle with a match and sufficient capacity wins 36 | // Component <- Riskpool <- BasicRiskpool <- TestRiskpool 37 | // complex (wholesale) approach: single policy covered by many bundles 38 | // Component <- Riskpool <- AdvancedRiskpool <- TestRiskpool 39 | function _lockCollateral(bytes32 processId, uint256 collateralAmount) 40 | internal override 41 | returns(bool success) 42 | { 43 | uint256 activeBundles = activeBundles(); 44 | uint256 capital = getCapital(); 45 | uint256 lockedCapital = getTotalValueLocked(); 46 | 47 | emit LogBasicRiskpoolBundlesAndPolicies(activeBundles, _policiesCounter); 48 | require(activeBundles > 0, "ERROR:BRP-001:NO_ACTIVE_BUNDLES"); 49 | require(capital > lockedCapital, "ERROR:BRP-002:NO_FREE_CAPITAL"); 50 | 51 | // ensure there is a chance to find the collateral 52 | if(capital >= lockedCapital + collateralAmount) { 53 | IPolicy.Application memory application = _instanceService.getApplication(processId); 54 | 55 | // initialize bundle idx with round robin based on active bundles 56 | uint idx = _policiesCounter % activeBundles; 57 | 58 | // basic riskpool implementation: policy coverage by single bundle only/ 59 | // the initial bundle is selected via round robin based on the policies counter. 60 | // If a bundle does not match (application not matching or insufficient funds for collateral) the next one is tried. 61 | // This is continued until all bundles have been tried once. If no bundle matches the policy is rejected. 62 | for (uint256 i = 0; i < activeBundles && !success; i++) { 63 | uint256 bundleId = getActiveBundleId(idx); 64 | IBundle.Bundle memory bundle = _instanceService.getBundle(bundleId); 65 | bool isMatching = bundleMatchesApplication(bundle, application); 66 | emit LogRiskpoolBundleMatchesPolicy(bundleId, isMatching); 67 | 68 | if (isMatching) { 69 | uint256 maxAmount = bundle.capital - bundle.lockedCapital; 70 | emit LogBasicRiskpoolCandidateBundleAmountCheck(idx, bundleId, maxAmount, collateralAmount); 71 | 72 | if (maxAmount >= collateralAmount) { 73 | _riskpoolService.collateralizePolicy(bundleId, processId, collateralAmount); 74 | _collateralizedBy[processId] = bundleId; 75 | success = true; 76 | _policiesCounter++; 77 | } else { 78 | idx = (idx + 1) % activeBundles; 79 | } 80 | } 81 | } 82 | } 83 | } 84 | 85 | function _processPayout(bytes32 processId, uint256 amount) 86 | internal override 87 | { 88 | uint256 bundleId = _collateralizedBy[processId]; 89 | _riskpoolService.processPayout(bundleId, processId, amount); 90 | } 91 | 92 | function _processPremium(bytes32 processId, uint256 amount) 93 | internal override 94 | { 95 | uint256 bundleId = _collateralizedBy[processId]; 96 | _riskpoolService.processPremium(bundleId, processId, amount); 97 | } 98 | 99 | function _releaseCollateral(bytes32 processId) 100 | internal override 101 | returns(uint256 collateralAmount) 102 | { 103 | uint256 bundleId = _collateralizedBy[processId]; 104 | collateralAmount = _riskpoolService.releasePolicy(bundleId, processId); 105 | } 106 | } -------------------------------------------------------------------------------- /contracts/components/Component.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IComponent.sol"; 5 | import "../modules/IAccess.sol"; 6 | import "../modules/IComponentEvents.sol"; 7 | import "../modules/IRegistry.sol"; 8 | import "../services/IComponentOwnerService.sol"; 9 | import "../services/IInstanceService.sol"; 10 | import "@openzeppelin/contracts/access/Ownable.sol"; 11 | 12 | 13 | // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/GUIDELINES.md#style-guidelines 14 | abstract contract Component is 15 | IComponent, 16 | IComponentEvents, 17 | Ownable 18 | { 19 | bytes32 private _componentName; 20 | uint256 private _componentId; 21 | IComponent.ComponentType private _componentType; 22 | 23 | IRegistry private _registry; 24 | IAccess private _access; 25 | IComponentOwnerService private _componentOwnerService; 26 | IInstanceService private _instanceService; 27 | 28 | modifier onlyInstanceOperatorService() { 29 | require( 30 | _msgSender() == _getContractAddress("InstanceOperatorService"), 31 | "ERROR:CMP-001:NOT_INSTANCE_OPERATOR_SERVICE"); 32 | _; 33 | } 34 | 35 | modifier onlyComponent() { 36 | require( 37 | _msgSender() == _getContractAddress("Component"), 38 | "ERROR:CMP-002:NOT_COMPONENT"); 39 | _; 40 | } 41 | 42 | modifier onlyComponentOwnerService() { 43 | require( 44 | _msgSender() == address(_componentOwnerService), 45 | "ERROR:CMP-003:NOT_COMPONENT_OWNER_SERVICE"); 46 | _; 47 | } 48 | 49 | constructor( 50 | bytes32 name, 51 | IComponent.ComponentType componentType, 52 | address registry 53 | ) 54 | Ownable() 55 | { 56 | require(registry != address(0), "ERROR:CMP-004:REGISTRY_ADDRESS_ZERO"); 57 | 58 | _registry = IRegistry(registry); 59 | _access = _getAccess(); 60 | _componentOwnerService = _getComponentOwnerService(); 61 | _instanceService = _getInstanceService(); 62 | 63 | _componentName = name; 64 | _componentType = componentType; 65 | 66 | emit LogComponentCreated( 67 | _componentName, 68 | _componentType, 69 | address(this), 70 | address(_registry)); 71 | } 72 | 73 | function setId(uint256 id) external override onlyComponent { _componentId = id; } 74 | 75 | function getName() public override view returns(bytes32) { return _componentName; } 76 | function getId() public override view returns(uint256) { return _componentId; } 77 | function getType() public override view returns(IComponent.ComponentType) { return _componentType; } 78 | function getState() public override view returns(IComponent.ComponentState) { return _instanceService.getComponentState(_componentId); } 79 | function getOwner() public override view returns(address) { return owner(); } 80 | 81 | function isProduct() public override view returns(bool) { return _componentType == IComponent.ComponentType.Product; } 82 | function isOracle() public override view returns(bool) { return _componentType == IComponent.ComponentType.Oracle; } 83 | function isRiskpool() public override view returns(bool) { return _componentType == IComponent.ComponentType.Riskpool; } 84 | 85 | function getRegistry() external override view returns(IRegistry) { return _registry; } 86 | 87 | function proposalCallback() public override onlyComponent { _afterPropose(); } 88 | function approvalCallback() public override onlyComponent { _afterApprove(); } 89 | function declineCallback() public override onlyComponent { _afterDecline(); } 90 | function suspendCallback() public override onlyComponent { _afterSuspend(); } 91 | function resumeCallback() public override onlyComponent { _afterResume(); } 92 | function pauseCallback() public override onlyComponent { _afterPause(); } 93 | function unpauseCallback() public override onlyComponent { _afterUnpause(); } 94 | function archiveCallback() public override onlyComponent { _afterArchive(); } 95 | 96 | // these functions are intended to be overwritten to implement 97 | // component specific notification handling 98 | function _afterPropose() internal virtual {} 99 | function _afterApprove() internal virtual {} 100 | function _afterDecline() internal virtual {} 101 | function _afterSuspend() internal virtual {} 102 | function _afterResume() internal virtual {} 103 | function _afterPause() internal virtual {} 104 | function _afterUnpause() internal virtual {} 105 | function _afterArchive() internal virtual {} 106 | 107 | function _getAccess() internal view returns (IAccess) { 108 | return IAccess(_getContractAddress("Access")); 109 | } 110 | 111 | function _getInstanceService() internal view returns (IInstanceService) { 112 | return IInstanceService(_getContractAddress("InstanceService")); 113 | } 114 | 115 | function _getComponentOwnerService() internal view returns (IComponentOwnerService) { 116 | return IComponentOwnerService(_getContractAddress("ComponentOwnerService")); 117 | } 118 | 119 | function _getContractAddress(bytes32 contractName) internal view returns (address) { 120 | return _registry.getContract(contractName); 121 | } 122 | 123 | } 124 | -------------------------------------------------------------------------------- /contracts/components/IComponent.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "../modules/IRegistry.sol"; 5 | 6 | interface IComponent { 7 | 8 | enum ComponentType { 9 | Oracle, 10 | Product, 11 | Riskpool 12 | } 13 | 14 | enum ComponentState { 15 | Created, 16 | Proposed, 17 | Declined, 18 | Active, 19 | Paused, 20 | Suspended, 21 | Archived 22 | } 23 | 24 | event LogComponentCreated ( 25 | bytes32 componentName, 26 | IComponent.ComponentType componentType, 27 | address componentAddress, 28 | address registryAddress); 29 | 30 | function setId(uint256 id) external; 31 | 32 | function getName() external view returns(bytes32); 33 | function getId() external view returns(uint256); 34 | function getType() external view returns(ComponentType); 35 | function getState() external view returns(ComponentState); 36 | function getOwner() external view returns(address); 37 | 38 | function isProduct() external view returns(bool); 39 | function isOracle() external view returns(bool); 40 | function isRiskpool() external view returns(bool); 41 | 42 | function getRegistry() external view returns(IRegistry); 43 | 44 | function proposalCallback() external; 45 | function approvalCallback() external; 46 | function declineCallback() external; 47 | function suspendCallback() external; 48 | function resumeCallback() external; 49 | function pauseCallback() external; 50 | function unpauseCallback() external; 51 | function archiveCallback() external; 52 | } -------------------------------------------------------------------------------- /contracts/components/IOracle.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IComponent.sol"; 5 | 6 | interface IOracle is IComponent { 7 | 8 | event LogOracleCreated (address oracleAddress); 9 | event LogOracleProposed (uint256 componentId); 10 | event LogOracleApproved (uint256 componentId); 11 | event LogOracleDeclined (uint256 componentId); 12 | 13 | function request(uint256 requestId, bytes calldata input) external; 14 | function cancel(uint256 requestId) external; 15 | } 16 | -------------------------------------------------------------------------------- /contracts/components/IProduct.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IComponent.sol"; 5 | 6 | interface IProduct is IComponent { 7 | 8 | event LogProductCreated (address productAddress); 9 | event LogProductProposed (uint256 componentId); 10 | event LogProductApproved (uint256 componentId); 11 | event LogProductDeclined (uint256 componentId); 12 | 13 | function getToken() external view returns(address token); 14 | function getPolicyFlow() external view returns(address policyFlow); 15 | function getRiskpoolId() external view returns(uint256 riskpoolId); 16 | 17 | function getApplicationDataStructure() external view returns(string memory dataStructure); 18 | function getClaimDataStructure() external view returns(string memory dataStructure); 19 | function getPayoutDataStructure() external view returns(string memory dataStructure); 20 | 21 | function riskPoolCapacityCallback(uint256 capacity) external; 22 | } 23 | -------------------------------------------------------------------------------- /contracts/components/IRiskpool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IComponent.sol"; 5 | import "../modules/IBundle.sol"; 6 | import "../modules/IPolicy.sol"; 7 | 8 | interface IRiskpool is IComponent { 9 | 10 | event LogRiskpoolCreated (address riskpoolAddress); 11 | event LogRiskpoolProposed (uint256 id); 12 | event LogRiskpoolApproved (uint256 id); 13 | event LogRiskpoolDeclined (uint256 id); 14 | 15 | event LogRiskpoolBundleCreated(uint256 bundleId, uint256 amount); 16 | event LogRiskpoolBundleMatchesPolicy(uint256 bundleId, bool isMatching); 17 | event LogRiskpoolCollateralLocked(bytes32 processId, uint256 collateralAmount, bool isSecured); 18 | 19 | event LogRiskpoolPremiumProcessed(bytes32 processId, uint256 amount); 20 | event LogRiskpoolPayoutProcessed(bytes32 processId, uint256 amount); 21 | event LogRiskpoolCollateralReleased(bytes32 processId, uint256 collateralAmount); 22 | 23 | 24 | function createBundle(bytes memory filter, uint256 initialAmount) external returns(uint256 bundleId); 25 | function fundBundle(uint256 bundleId, uint256 amount) external returns(uint256 netAmount); 26 | function defundBundle(uint256 bundleId, uint256 amount) external returns(uint256 netAmount); 27 | 28 | function lockBundle(uint256 bundleId) external; 29 | function unlockBundle(uint256 bundleId) external; 30 | function closeBundle(uint256 bundleId) external; 31 | function burnBundle(uint256 bundleId) external; 32 | 33 | function collateralizePolicy(bytes32 processId, uint256 collateralAmount) external returns(bool isSecured); 34 | function processPolicyPremium(bytes32 processId, uint256 amount) external; 35 | function processPolicyPayout(bytes32 processId, uint256 amount) external; 36 | function releasePolicy(bytes32 processId) external; 37 | 38 | function getCollateralizationLevel() external view returns (uint256); 39 | function getFullCollateralizationLevel() external view returns (uint256); 40 | 41 | function bundleMatchesApplication( 42 | IBundle.Bundle memory bundle, 43 | IPolicy.Application memory application 44 | ) 45 | external view returns(bool isMatching); 46 | 47 | function getFilterDataStructure() external view returns(string memory); 48 | 49 | function bundles() external view returns(uint256); 50 | function getBundleId(uint256 idx) external view returns(uint256 bundleId); 51 | 52 | function activeBundles() external view returns(uint256); 53 | function getActiveBundleId(uint256 idx) external view returns(uint256 bundleId); 54 | 55 | function getWallet() external view returns(address); 56 | function getErc20Token() external view returns(address); 57 | 58 | function getSumOfSumInsuredCap() external view returns (uint256); 59 | function getCapital() external view returns(uint256); 60 | function getTotalValueLocked() external view returns(uint256); 61 | function getCapacity() external view returns(uint256); 62 | function getBalance() external view returns(uint256); 63 | 64 | function setMaximumNumberOfActiveBundles(uint256 maximumNumberOfActiveBundles) external; 65 | function getMaximumNumberOfActiveBundles() external view returns(uint256 maximumNumberOfActiveBundles); 66 | } 67 | -------------------------------------------------------------------------------- /contracts/components/Oracle.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IOracle.sol"; 5 | import "./Component.sol"; 6 | import "./IComponent.sol"; 7 | import "../services/IOracleService.sol"; 8 | 9 | abstract contract Oracle is 10 | IOracle, 11 | Component 12 | { 13 | IOracleService private _oracleService; 14 | 15 | modifier onlyQuery { 16 | require( 17 | _msgSender() == _getContractAddress("Query"), 18 | "ERROR:ORA-001:ACCESS_DENIED" 19 | ); 20 | _; 21 | } 22 | 23 | constructor( 24 | bytes32 name, 25 | address registry 26 | ) 27 | Component(name, ComponentType.Oracle, registry) 28 | { 29 | _oracleService = IOracleService(_getContractAddress("OracleService")); 30 | emit LogOracleCreated(address(this)); 31 | } 32 | 33 | // default callback function implementations 34 | function _afterApprove() internal override { 35 | emit LogOracleApproved(getId()); 36 | } 37 | 38 | function _afterPropose() internal override { emit LogOracleProposed(getId()); } 39 | function _afterDecline() internal override { emit LogOracleDeclined(getId()); } 40 | 41 | function _respond(uint256 requestId, bytes memory data) internal { 42 | _oracleService.respond(requestId, data); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /contracts/components/Product.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IProduct.sol"; 5 | import "./Component.sol"; 6 | import "../modules/IPolicy.sol"; 7 | import "../services/IInstanceService.sol"; 8 | import "../services/IProductService.sol"; 9 | 10 | abstract contract Product is 11 | IProduct, 12 | Component 13 | { 14 | string public constant DEFAULT_DATA_STRUCTURE = ""; 15 | 16 | address private _policyFlow; // policy flow contract to use for this procut 17 | address private _token; // erc20 token to use for this product 18 | uint256 private _riskpoolId; // id of riskpool responsible for this product 19 | 20 | IProductService internal _productService; 21 | IInstanceService internal _instanceService; 22 | 23 | modifier onlyPolicyHolder(bytes32 policyId) { 24 | address policyHolder = _instanceService.getMetadata(policyId).owner; 25 | require( 26 | _msgSender() == policyHolder, 27 | "ERROR:PRD-001:POLICY_OR_HOLDER_INVALID" 28 | ); 29 | _; 30 | } 31 | 32 | modifier onlyLicence { 33 | require( 34 | _msgSender() == _getContractAddress("Licence"), 35 | "ERROR:PRD-002:ACCESS_DENIED" 36 | ); 37 | _; 38 | } 39 | 40 | modifier onlyOracle { 41 | require( 42 | _msgSender() == _getContractAddress("Query"), 43 | "ERROR:PRD-003:ACCESS_DENIED" 44 | ); 45 | _; 46 | } 47 | 48 | constructor( 49 | bytes32 name, 50 | address token, 51 | bytes32 policyFlow, 52 | uint256 riskpoolId, 53 | address registry 54 | ) 55 | Component(name, ComponentType.Product, registry) 56 | { 57 | _token = token; 58 | _riskpoolId = riskpoolId; 59 | 60 | // TODO add validation for policy flow 61 | _policyFlow = _getContractAddress(policyFlow); 62 | _productService = IProductService(_getContractAddress("ProductService")); 63 | _instanceService = IInstanceService(_getContractAddress("InstanceService")); 64 | 65 | emit LogProductCreated(address(this)); 66 | } 67 | 68 | function getToken() public override view returns(address) { 69 | return _token; 70 | } 71 | 72 | function getPolicyFlow() public view override returns(address) { 73 | return _policyFlow; 74 | } 75 | 76 | function getRiskpoolId() public override view returns(uint256) { 77 | return _riskpoolId; 78 | } 79 | 80 | // default callback function implementations 81 | function _afterApprove() internal override { emit LogProductApproved(getId()); } 82 | 83 | function _afterPropose() internal override { emit LogProductProposed(getId()); } 84 | function _afterDecline() internal override { emit LogProductDeclined(getId()); } 85 | 86 | function _newApplication( 87 | address applicationOwner, 88 | uint256 premiumAmount, 89 | uint256 sumInsuredAmount, 90 | bytes memory metaData, 91 | bytes memory applicationData 92 | ) 93 | internal 94 | returns(bytes32 processId) 95 | { 96 | processId = _productService.newApplication( 97 | applicationOwner, 98 | premiumAmount, 99 | sumInsuredAmount, 100 | metaData, 101 | applicationData); 102 | } 103 | 104 | function _collectPremium(bytes32 processId) 105 | internal 106 | returns( 107 | bool success, 108 | uint256 feeAmount, 109 | uint256 netAmount 110 | ) 111 | { 112 | IPolicy.Policy memory policy = _getPolicy(processId); 113 | 114 | if (policy.premiumPaidAmount < policy.premiumExpectedAmount) { 115 | (success, feeAmount, netAmount) 116 | = _collectPremium( 117 | processId, 118 | policy.premiumExpectedAmount - policy.premiumPaidAmount 119 | ); 120 | } 121 | } 122 | 123 | function _collectPremium( 124 | bytes32 processId, 125 | uint256 amount 126 | ) 127 | internal 128 | returns( 129 | bool success, 130 | uint256 feeAmount, 131 | uint256 netAmount 132 | ) 133 | { 134 | (success, feeAmount, netAmount) = _productService.collectPremium(processId, amount); 135 | } 136 | 137 | function _adjustPremiumSumInsured( 138 | bytes32 processId, 139 | uint256 expectedPremiumAmount, 140 | uint256 sumInsuredAmount 141 | ) internal { 142 | _productService.adjustPremiumSumInsured(processId, expectedPremiumAmount, sumInsuredAmount); 143 | } 144 | 145 | function _revoke(bytes32 processId) internal { 146 | _productService.revoke(processId); 147 | } 148 | 149 | function _underwrite(bytes32 processId) internal returns(bool success) { 150 | success = _productService.underwrite(processId); 151 | } 152 | 153 | function _decline(bytes32 processId) internal { 154 | _productService.decline(processId); 155 | } 156 | 157 | function _expire(bytes32 processId) internal { 158 | _productService.expire(processId); 159 | } 160 | 161 | function _close(bytes32 processId) internal { 162 | _productService.close(processId); 163 | } 164 | 165 | function _newClaim( 166 | bytes32 processId, 167 | uint256 claimAmount, 168 | bytes memory data 169 | ) 170 | internal 171 | returns (uint256 claimId) 172 | { 173 | claimId = _productService.newClaim( 174 | processId, 175 | claimAmount, 176 | data); 177 | } 178 | 179 | function _confirmClaim( 180 | bytes32 processId, 181 | uint256 claimId, 182 | uint256 payoutAmount 183 | ) 184 | internal 185 | { 186 | _productService.confirmClaim( 187 | processId, 188 | claimId, 189 | payoutAmount); 190 | } 191 | 192 | function _declineClaim(bytes32 processId, uint256 claimId) internal { 193 | _productService.declineClaim(processId, claimId); 194 | } 195 | 196 | function _closeClaim(bytes32 processId, uint256 claimId) internal { 197 | _productService.closeClaim(processId, claimId); 198 | } 199 | 200 | function _newPayout( 201 | bytes32 processId, 202 | uint256 claimId, 203 | uint256 amount, 204 | bytes memory data 205 | ) 206 | internal 207 | returns(uint256 payoutId) 208 | { 209 | payoutId = _productService.newPayout(processId, claimId, amount, data); 210 | } 211 | 212 | function _processPayout( 213 | bytes32 processId, 214 | uint256 payoutId 215 | ) 216 | internal 217 | returns( 218 | uint256 feeAmount, 219 | uint256 netPayoutAmount 220 | ) 221 | { 222 | ( 223 | feeAmount, 224 | netPayoutAmount 225 | ) = _productService.processPayout(processId, payoutId); 226 | } 227 | 228 | function _request( 229 | bytes32 processId, 230 | bytes memory input, 231 | string memory callbackMethodName, 232 | uint256 responsibleOracleId 233 | ) 234 | internal 235 | returns (uint256 requestId) 236 | { 237 | requestId = _productService.request( 238 | processId, 239 | input, 240 | callbackMethodName, 241 | address(this), 242 | responsibleOracleId 243 | ); 244 | } 245 | 246 | function _cancelRequest(uint256 requestId) 247 | internal 248 | { 249 | _productService.cancelRequest(requestId); 250 | } 251 | 252 | function _getMetadata(bytes32 processId) 253 | internal 254 | view 255 | returns (IPolicy.Metadata memory metadata) 256 | { 257 | return _instanceService.getMetadata(processId); 258 | } 259 | 260 | function _getApplication(bytes32 processId) 261 | internal 262 | view 263 | returns (IPolicy.Application memory application) 264 | { 265 | return _instanceService.getApplication(processId); 266 | } 267 | 268 | function _getPolicy(bytes32 processId) 269 | internal 270 | view 271 | returns (IPolicy.Policy memory policy) 272 | { 273 | return _instanceService.getPolicy(processId); 274 | } 275 | 276 | function _getClaim(bytes32 processId, uint256 claimId) 277 | internal 278 | view 279 | returns (IPolicy.Claim memory claim) 280 | { 281 | return _instanceService.getClaim(processId, claimId); 282 | } 283 | 284 | function _getPayout(bytes32 processId, uint256 payoutId) 285 | internal 286 | view 287 | returns (IPolicy.Payout memory payout) 288 | { 289 | return _instanceService.getPayout(processId, payoutId); 290 | } 291 | 292 | function getApplicationDataStructure() external override virtual pure returns(string memory dataStructure) { 293 | return DEFAULT_DATA_STRUCTURE; 294 | } 295 | 296 | function getClaimDataStructure() external override virtual pure returns(string memory dataStructure) { 297 | return DEFAULT_DATA_STRUCTURE; 298 | } 299 | 300 | function getPayoutDataStructure() external override virtual pure returns(string memory dataStructure) { 301 | return DEFAULT_DATA_STRUCTURE; 302 | } 303 | 304 | function riskPoolCapacityCallback(uint256 capacity) external override virtual { } 305 | } 306 | -------------------------------------------------------------------------------- /contracts/components/Riskpool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "./IRiskpool.sol"; 5 | import "./Component.sol"; 6 | 7 | import "../modules/IBundle.sol"; 8 | import "../modules/IPolicy.sol"; 9 | import "../services/IInstanceService.sol"; 10 | import "../services/IRiskpoolService.sol"; 11 | 12 | import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; 13 | 14 | abstract contract Riskpool is 15 | IRiskpool, 16 | Component 17 | { 18 | // used for representation of collateralization 19 | // collateralization between 0 and 1 (1=100%) 20 | // value might be larger when overcollateralization 21 | uint256 public constant FULL_COLLATERALIZATION_LEVEL = 10**18; 22 | string public constant DEFAULT_FILTER_DATA_STRUCTURE = ""; 23 | 24 | IInstanceService internal _instanceService; 25 | IRiskpoolService internal _riskpoolService; 26 | IERC721 internal _bundleToken; 27 | 28 | // keep track of bundles associated with this riskpool 29 | uint256 [] internal _bundleIds; 30 | 31 | address private _wallet; 32 | address private _erc20Token; 33 | uint256 private _collateralization; 34 | uint256 private _sumOfSumInsuredCap; 35 | uint256 private _maxNumberOfActiveBundles; 36 | 37 | modifier onlyPool { 38 | require( 39 | _msgSender() == _getContractAddress("Pool"), 40 | "ERROR:RPL-001:ACCESS_DENIED" 41 | ); 42 | _; 43 | } 44 | 45 | modifier onlyBundleOwner(uint256 bundleId) { 46 | IBundle.Bundle memory bundle = _instanceService.getBundle(bundleId); 47 | address bundleOwner = _bundleToken.ownerOf(bundle.tokenId); 48 | 49 | require( 50 | _msgSender() == bundleOwner, 51 | "ERROR:BUC-001:NOT_BUNDLE_OWNER" 52 | ); 53 | _; 54 | } 55 | 56 | constructor( 57 | bytes32 name, 58 | uint256 collateralization, 59 | uint256 sumOfSumInsuredCap, 60 | address erc20Token, 61 | address wallet, 62 | address registry 63 | ) 64 | Component(name, ComponentType.Riskpool, registry) 65 | { 66 | _collateralization = collateralization; 67 | 68 | require(sumOfSumInsuredCap != 0, "ERROR:RPL-002:SUM_OF_SUM_INSURED_CAP_ZERO"); 69 | _sumOfSumInsuredCap = sumOfSumInsuredCap; 70 | 71 | require(erc20Token != address(0), "ERROR:RPL-003:ERC20_ADDRESS_ZERO"); 72 | _erc20Token = erc20Token; 73 | 74 | require(wallet != address(0), "ERROR:RPL-004:WALLET_ADDRESS_ZERO"); 75 | _wallet = wallet; 76 | 77 | _instanceService = IInstanceService(_getContractAddress("InstanceService")); 78 | _riskpoolService = IRiskpoolService(_getContractAddress("RiskpoolService")); 79 | _bundleToken = _instanceService.getBundleToken(); 80 | } 81 | 82 | function _afterPropose() internal override virtual { 83 | _riskpoolService.registerRiskpool( 84 | _wallet, 85 | _erc20Token, 86 | _collateralization, 87 | _sumOfSumInsuredCap 88 | ); 89 | } 90 | 91 | function createBundle(bytes memory filter, uint256 initialAmount) 92 | public virtual override 93 | returns(uint256 bundleId) 94 | { 95 | address bundleOwner = _msgSender(); 96 | bundleId = _riskpoolService.createBundle(bundleOwner, filter, initialAmount); 97 | _bundleIds.push(bundleId); 98 | 99 | emit LogRiskpoolBundleCreated(bundleId, initialAmount); 100 | } 101 | 102 | function fundBundle(uint256 bundleId, uint256 amount) 103 | external override 104 | onlyBundleOwner(bundleId) 105 | returns(uint256 netAmount) 106 | { 107 | netAmount = _riskpoolService.fundBundle(bundleId, amount); 108 | } 109 | 110 | function defundBundle(uint256 bundleId, uint256 amount) 111 | external override 112 | onlyBundleOwner(bundleId) 113 | returns(uint256 netAmount) 114 | { 115 | netAmount = _riskpoolService.defundBundle(bundleId, amount); 116 | } 117 | 118 | function lockBundle(uint256 bundleId) 119 | external override 120 | onlyBundleOwner(bundleId) 121 | { 122 | _riskpoolService.lockBundle(bundleId); 123 | } 124 | 125 | function unlockBundle(uint256 bundleId) 126 | external override 127 | onlyBundleOwner(bundleId) 128 | { 129 | _riskpoolService.unlockBundle(bundleId); 130 | } 131 | 132 | function closeBundle(uint256 bundleId) 133 | external override 134 | onlyBundleOwner(bundleId) 135 | { 136 | _riskpoolService.closeBundle(bundleId); 137 | } 138 | 139 | function burnBundle(uint256 bundleId) 140 | external override 141 | onlyBundleOwner(bundleId) 142 | { 143 | _riskpoolService.burnBundle(bundleId); 144 | } 145 | 146 | function collateralizePolicy(bytes32 processId, uint256 collateralAmount) 147 | external override 148 | onlyPool 149 | returns(bool success) 150 | { 151 | success = _lockCollateral(processId, collateralAmount); 152 | emit LogRiskpoolCollateralLocked(processId, collateralAmount, success); 153 | } 154 | 155 | function processPolicyPayout(bytes32 processId, uint256 amount) 156 | external override 157 | onlyPool 158 | { 159 | _processPayout(processId, amount); 160 | emit LogRiskpoolPayoutProcessed(processId, amount); 161 | } 162 | 163 | function processPolicyPremium(bytes32 processId, uint256 amount) 164 | external override 165 | onlyPool 166 | { 167 | _processPremium(processId, amount); 168 | emit LogRiskpoolPremiumProcessed(processId, amount); 169 | } 170 | 171 | function releasePolicy(bytes32 processId) 172 | external override 173 | onlyPool 174 | { 175 | uint256 collateralAmount = _releaseCollateral(processId); 176 | emit LogRiskpoolCollateralReleased(processId, collateralAmount); 177 | } 178 | 179 | function setMaximumNumberOfActiveBundles(uint256 maximumNumberOfActiveBundles) 180 | external override 181 | onlyOwner 182 | { 183 | uint256 riskpoolId = getId(); 184 | _riskpoolService.setMaximumNumberOfActiveBundles(riskpoolId, maximumNumberOfActiveBundles); 185 | } 186 | 187 | function getMaximumNumberOfActiveBundles() 188 | public view override 189 | returns(uint256 maximumNumberOfActiveBundles) 190 | { 191 | uint256 riskpoolId = getId(); 192 | return _instanceService.getMaximumNumberOfActiveBundles(riskpoolId); 193 | } 194 | 195 | function getWallet() public view override returns(address) { 196 | return _wallet; 197 | } 198 | 199 | function getErc20Token() public view override returns(address) { 200 | return _erc20Token; 201 | } 202 | 203 | function getSumOfSumInsuredCap() public view override returns (uint256) { 204 | return _sumOfSumInsuredCap; 205 | } 206 | 207 | function getFullCollateralizationLevel() public pure override returns (uint256) { 208 | return FULL_COLLATERALIZATION_LEVEL; 209 | } 210 | 211 | function getCollateralizationLevel() public view override returns (uint256) { 212 | return _collateralization; 213 | } 214 | 215 | function bundles() public override view returns(uint256) { 216 | return _bundleIds.length; 217 | } 218 | 219 | function getBundleId(uint256 idx) public override view returns(uint256 bundleId) { 220 | require(idx < _bundleIds.length, "ERROR:RPL-006:BUNDLE_INDEX_TOO_LARGE"); 221 | bundleId = _bundleIds[idx]; 222 | } 223 | 224 | function activeBundles() public override view returns(uint256) { 225 | uint256 riskpoolId = getId(); 226 | return _instanceService.activeBundles(riskpoolId); 227 | } 228 | 229 | function getActiveBundleId(uint256 idx) public override view returns(uint256 bundleId) { 230 | uint256 riskpoolId = getId(); 231 | require(idx < _instanceService.activeBundles(riskpoolId), "ERROR:RPL-007:ACTIVE_BUNDLE_INDEX_TOO_LARGE"); 232 | 233 | return _instanceService.getActiveBundleId(riskpoolId, idx); 234 | } 235 | 236 | function getFilterDataStructure() external override virtual pure returns(string memory) { 237 | return DEFAULT_FILTER_DATA_STRUCTURE; 238 | } 239 | 240 | function getCapital() public override view returns(uint256) { 241 | uint256 riskpoolId = getId(); 242 | return _instanceService.getCapital(riskpoolId); 243 | } 244 | 245 | function getTotalValueLocked() public override view returns(uint256) { 246 | uint256 riskpoolId = getId(); 247 | return _instanceService.getTotalValueLocked(riskpoolId); 248 | } 249 | 250 | function getCapacity() public override view returns(uint256) { 251 | uint256 riskpoolId = getId(); 252 | return _instanceService.getCapacity(riskpoolId); 253 | } 254 | 255 | function getBalance() public override view returns(uint256) { 256 | uint256 riskpoolId = getId(); 257 | return _instanceService.getBalance(riskpoolId); 258 | } 259 | 260 | function bundleMatchesApplication( 261 | IBundle.Bundle memory bundle, 262 | IPolicy.Application memory application 263 | ) public override view virtual returns(bool isMatching); 264 | 265 | function _afterArchive() internal view override { 266 | uint256 riskpoolId = getId(); 267 | require( 268 | _instanceService.unburntBundles(riskpoolId) == 0, 269 | "ERROR:RPL-010:RISKPOOL_HAS_UNBURNT_BUNDLES" 270 | ); 271 | } 272 | 273 | function _lockCollateral(bytes32 processId, uint256 collateralAmount) internal virtual returns(bool success); 274 | function _processPremium(bytes32 processId, uint256 amount) internal virtual; 275 | function _processPayout(bytes32 processId, uint256 amount) internal virtual; 276 | function _releaseCollateral(bytes32 processId) internal virtual returns(uint256 collateralAmount); 277 | 278 | } -------------------------------------------------------------------------------- /contracts/modules/IAccess.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IAccess { 5 | function getDefaultAdminRole() external view returns(bytes32 role); 6 | function getProductOwnerRole() external view returns(bytes32 role); 7 | function getOracleProviderRole() external view returns(bytes32 role); 8 | function getRiskpoolKeeperRole() external view returns(bytes32 role); 9 | function hasRole(bytes32 role, address principal) external view returns(bool); 10 | 11 | function grantRole(bytes32 role, address principal) external; 12 | function revokeRole(bytes32 role, address principal) external; 13 | function renounceRole(bytes32 role, address principal) external; 14 | 15 | function addRole(bytes32 role) external; 16 | function invalidateRole(bytes32 role) external; 17 | } 18 | -------------------------------------------------------------------------------- /contracts/modules/IBundle.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IBundle { 5 | 6 | event LogBundleCreated( 7 | uint256 bundleId, 8 | uint256 riskpoolId, 9 | address owner, 10 | BundleState state, 11 | uint256 amount 12 | ); 13 | 14 | event LogBundleStateChanged(uint256 bundleId, BundleState oldState, BundleState newState); 15 | 16 | event LogBundleCapitalProvided(uint256 bundleId, address sender, uint256 amount, uint256 capacity); 17 | event LogBundleCapitalWithdrawn(uint256 bundleId, address recipient, uint256 amount, uint256 capacity); 18 | 19 | event LogBundlePolicyCollateralized(uint256 bundleId, bytes32 processId, uint256 amount, uint256 capacity); 20 | event LogBundlePayoutProcessed(uint256 bundleId, bytes32 processId, uint256 amount); 21 | event LogBundlePolicyReleased(uint256 bundleId, bytes32 processId, uint256 amount, uint256 capacity); 22 | 23 | enum BundleState { 24 | Active, 25 | Locked, 26 | Closed, 27 | Burned 28 | } 29 | 30 | struct Bundle { 31 | uint256 id; 32 | uint256 riskpoolId; 33 | uint256 tokenId; 34 | BundleState state; 35 | bytes filter; // required conditions for applications to be considered for collateralization by this bundle 36 | uint256 capital; // net investment capital amount (<= balance) 37 | uint256 lockedCapital; // capital amount linked to collateralizaion of non-closed policies (<= capital) 38 | uint256 balance; // total amount of funds: net investment capital + net premiums - payouts 39 | uint256 createdAt; 40 | uint256 updatedAt; 41 | } 42 | 43 | function create(address owner_, uint256 riskpoolId_, bytes calldata filter_, uint256 amount_) external returns(uint256 bundleId); 44 | function fund(uint256 bundleId, uint256 amount) external; 45 | function defund(uint256 bundleId, uint256 amount) external; 46 | 47 | function lock(uint256 bundleId) external; 48 | function unlock(uint256 bundleId) external; 49 | function close(uint256 bundleId) external; 50 | function burn(uint256 bundleId) external; 51 | 52 | function collateralizePolicy(uint256 bundleId, bytes32 processId, uint256 collateralAmount) external; 53 | function processPremium(uint256 bundleId, bytes32 processId, uint256 amount) external; 54 | function processPayout(uint256 bundleId, bytes32 processId, uint256 amount) external; 55 | function releasePolicy(uint256 bundleId, bytes32 processId) external returns(uint256 collateralAmount); 56 | } 57 | -------------------------------------------------------------------------------- /contracts/modules/IComponentEvents.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "../components/IComponent.sol"; 5 | 6 | interface IComponentEvents { 7 | 8 | event LogComponentProposed ( 9 | bytes32 componentName, 10 | IComponent.ComponentType componentType, 11 | address componentAddress, 12 | uint256 id); 13 | 14 | event LogComponentApproved (uint256 id); 15 | event LogComponentDeclined (uint256 id); 16 | 17 | event LogComponentSuspended (uint256 id); 18 | event LogComponentResumed (uint256 id); 19 | 20 | event LogComponentPaused (uint256 id); 21 | event LogComponentUnpaused (uint256 id); 22 | 23 | event LogComponentArchived (uint256 id); 24 | 25 | event LogComponentStateChanged ( 26 | uint256 id, 27 | IComponent.ComponentState stateOld, 28 | IComponent.ComponentState stateNew); 29 | } 30 | -------------------------------------------------------------------------------- /contracts/modules/ILicense.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface ILicense { 5 | 6 | function getAuthorizationStatus(address _sender) 7 | external 8 | view 9 | returns (uint256 productId, bool isAuthorized, address policyFlow); 10 | } 11 | -------------------------------------------------------------------------------- /contracts/modules/IPolicy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IPolicy { 5 | 6 | // Events 7 | event LogMetadataCreated( 8 | address owner, 9 | bytes32 processId, 10 | uint256 productId, 11 | PolicyFlowState state 12 | ); 13 | 14 | event LogMetadataStateChanged( 15 | bytes32 processId, 16 | PolicyFlowState state 17 | ); 18 | 19 | event LogApplicationCreated( 20 | bytes32 processId, 21 | uint256 premiumAmount, 22 | uint256 sumInsuredAmount 23 | ); 24 | 25 | event LogApplicationRevoked(bytes32 processId); 26 | event LogApplicationUnderwritten(bytes32 processId); 27 | event LogApplicationDeclined(bytes32 processId); 28 | 29 | event LogPolicyCreated(bytes32 processId); 30 | event LogPolicyExpired(bytes32 processId); 31 | event LogPolicyClosed(bytes32 processId); 32 | 33 | event LogPremiumCollected(bytes32 processId, uint256 amount); 34 | 35 | event LogApplicationSumInsuredAdjusted(bytes32 processId, uint256 sumInsuredAmountOld, uint256 sumInsuredAmount); 36 | event LogApplicationPremiumAdjusted(bytes32 processId, uint256 premiumAmountOld, uint256 premiumAmount); 37 | event LogPolicyPremiumAdjusted(bytes32 processId, uint256 premiumExpectedAmountOld, uint256 premiumExpectedAmount); 38 | 39 | event LogClaimCreated(bytes32 processId, uint256 claimId, uint256 claimAmount); 40 | event LogClaimConfirmed(bytes32 processId, uint256 claimId, uint256 confirmedAmount); 41 | event LogClaimDeclined(bytes32 processId, uint256 claimId); 42 | event LogClaimClosed(bytes32 processId, uint256 claimId); 43 | 44 | event LogPayoutCreated( 45 | bytes32 processId, 46 | uint256 claimId, 47 | uint256 payoutId, 48 | uint256 amount 49 | ); 50 | 51 | event LogPayoutProcessed( 52 | bytes32 processId, 53 | uint256 payoutId 54 | ); 55 | 56 | // States 57 | enum PolicyFlowState {Started, Active, Finished} 58 | enum ApplicationState {Applied, Revoked, Underwritten, Declined} 59 | enum PolicyState {Active, Expired, Closed} 60 | enum ClaimState {Applied, Confirmed, Declined, Closed} 61 | enum PayoutState {Expected, PaidOut} 62 | 63 | // Objects 64 | struct Metadata { 65 | address owner; 66 | uint256 productId; 67 | PolicyFlowState state; 68 | bytes data; 69 | uint256 createdAt; 70 | uint256 updatedAt; 71 | } 72 | 73 | struct Application { 74 | ApplicationState state; 75 | uint256 premiumAmount; 76 | uint256 sumInsuredAmount; 77 | bytes data; 78 | uint256 createdAt; 79 | uint256 updatedAt; 80 | } 81 | 82 | struct Policy { 83 | PolicyState state; 84 | uint256 premiumExpectedAmount; 85 | uint256 premiumPaidAmount; 86 | uint256 claimsCount; 87 | uint256 openClaimsCount; 88 | uint256 payoutMaxAmount; 89 | uint256 payoutAmount; 90 | uint256 createdAt; 91 | uint256 updatedAt; 92 | } 93 | 94 | struct Claim { 95 | ClaimState state; 96 | uint256 claimAmount; 97 | uint256 paidAmount; 98 | bytes data; 99 | uint256 createdAt; 100 | uint256 updatedAt; 101 | } 102 | 103 | struct Payout { 104 | uint256 claimId; 105 | PayoutState state; 106 | uint256 amount; 107 | bytes data; 108 | uint256 createdAt; 109 | uint256 updatedAt; 110 | } 111 | 112 | function createPolicyFlow( 113 | address owner, 114 | uint256 productId, 115 | bytes calldata data 116 | ) external returns(bytes32 processId); 117 | 118 | function createApplication( 119 | bytes32 processId, 120 | uint256 premiumAmount, 121 | uint256 sumInsuredAmount, 122 | bytes calldata data 123 | ) external; 124 | 125 | function revokeApplication(bytes32 processId) external; 126 | function underwriteApplication(bytes32 processId) external; 127 | function declineApplication(bytes32 processId) external; 128 | 129 | function collectPremium(bytes32 processId, uint256 amount) external; 130 | 131 | function adjustPremiumSumInsured( 132 | bytes32 processId, 133 | uint256 expectedPremiumAmount, 134 | uint256 sumInsuredAmount 135 | ) external; 136 | 137 | function createPolicy(bytes32 processId) external; 138 | function expirePolicy(bytes32 processId) external; 139 | function closePolicy(bytes32 processId) external; 140 | 141 | function createClaim( 142 | bytes32 processId, 143 | uint256 claimAmount, 144 | bytes calldata data 145 | ) external returns (uint256 claimId); 146 | 147 | function confirmClaim( 148 | bytes32 processId, 149 | uint256 claimId, 150 | uint256 confirmedAmount 151 | ) external; 152 | 153 | function declineClaim(bytes32 processId, uint256 claimId) external; 154 | function closeClaim(bytes32 processId, uint256 claimId) external; 155 | 156 | function createPayout( 157 | bytes32 processId, 158 | uint256 claimId, 159 | uint256 payoutAmount, 160 | bytes calldata data 161 | ) external returns (uint256 payoutId); 162 | 163 | function processPayout( 164 | bytes32 processId, 165 | uint256 payoutId 166 | ) external; 167 | } 168 | -------------------------------------------------------------------------------- /contracts/modules/IPool.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IPool { 5 | 6 | event LogRiskpoolRegistered( 7 | uint256 riskpoolId, 8 | address wallet, 9 | address erc20Token, 10 | uint256 collateralizationLevel, 11 | uint256 sumOfSumInsuredCap 12 | ); 13 | 14 | event LogRiskpoolRequiredCollateral(bytes32 processId, uint256 sumInsured, uint256 collateral); 15 | event LogRiskpoolCollateralizationFailed(uint256 riskpoolId, bytes32 processId, uint256 amount); 16 | event LogRiskpoolCollateralizationSucceeded(uint256 riskpoolId, bytes32 processId, uint256 amount); 17 | event LogRiskpoolCollateralReleased(uint256 riskpoolId, bytes32 processId, uint256 amount); 18 | 19 | struct Pool { 20 | uint256 id; // matches component id of riskpool 21 | address wallet; // riskpool wallet 22 | address erc20Token; // the value token of the riskpool 23 | uint256 collateralizationLevel; // required collateralization level to cover new policies 24 | uint256 sumOfSumInsuredCap; // max sum of sum insured the pool is allowed to secure 25 | uint256 sumOfSumInsuredAtRisk; // current sum of sum insured at risk in this pool 26 | uint256 capital; // net investment capital amount (<= balance) 27 | uint256 lockedCapital; // capital amount linked to collateralizaion of non-closed policies (<= capital) 28 | uint256 balance; // total amount of funds: net investment capital + net premiums - payouts 29 | uint256 createdAt; 30 | uint256 updatedAt; 31 | } 32 | 33 | function registerRiskpool( 34 | uint256 riskpoolId, 35 | address wallet, 36 | address erc20Token, 37 | uint256 collateralizationLevel, 38 | uint256 sumOfSumInsuredCap 39 | ) external; 40 | 41 | function setRiskpoolForProduct(uint256 productId, uint256 riskpoolId) external; 42 | 43 | function underwrite(bytes32 processId) external returns(bool success); 44 | function processPremium(bytes32 processId, uint256 amount) external; 45 | function processPayout(bytes32 processId, uint256 amount) external; 46 | function release(bytes32 processId) external; 47 | } 48 | -------------------------------------------------------------------------------- /contracts/modules/IQuery.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IQuery { 5 | 6 | struct OracleRequest { 7 | bytes32 processId; 8 | uint256 responsibleOracleId; 9 | address callbackContractAddress; 10 | string callbackMethodName; 11 | bytes data; 12 | uint256 createdAt; 13 | } 14 | 15 | event LogOracleRequested( 16 | bytes32 processId, 17 | uint256 requestId, 18 | uint256 responsibleOracleId 19 | ); 20 | 21 | event LogOracleResponded( 22 | bytes32 processId, 23 | uint256 requestId, 24 | address responder, 25 | bool success 26 | ); 27 | 28 | event LogOracleCanceled( 29 | uint256 requestId 30 | ); 31 | 32 | function request( 33 | bytes32 processId, 34 | bytes calldata input, 35 | string calldata callbackMethodName, 36 | address callbackContractAddress, 37 | uint256 responsibleOracleId 38 | ) external returns (uint256 requestId); 39 | 40 | function respond( 41 | uint256 requestId, 42 | address responder, 43 | bytes calldata data 44 | ) external; 45 | 46 | function cancel(uint256 requestId) external; 47 | 48 | } 49 | -------------------------------------------------------------------------------- /contracts/modules/IRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IRegistry { 5 | 6 | event LogContractRegistered( 7 | bytes32 release, 8 | bytes32 contractName, 9 | address contractAddress, 10 | bool isNew 11 | ); 12 | 13 | event LogContractDeregistered(bytes32 release, bytes32 contractName); 14 | 15 | event LogReleasePrepared(bytes32 release); 16 | 17 | function registerInRelease( 18 | bytes32 _release, 19 | bytes32 _contractName, 20 | address _contractAddress 21 | ) external; 22 | 23 | function register(bytes32 _contractName, address _contractAddress) external; 24 | 25 | function deregisterInRelease(bytes32 _release, bytes32 _contractName) 26 | external; 27 | 28 | function deregister(bytes32 _contractName) external; 29 | 30 | function prepareRelease(bytes32 _newRelease) external; 31 | 32 | function getContractInRelease(bytes32 _release, bytes32 _contractName) 33 | external 34 | view 35 | returns (address _contractAddress); 36 | 37 | function getContract(bytes32 _contractName) 38 | external 39 | view 40 | returns (address _contractAddress); 41 | 42 | function getRelease() external view returns (bytes32 _release); 43 | 44 | function ensureSender(address sender, bytes32 _contractName) external view returns(bool _senderMatches); 45 | 46 | function contracts() external view returns (uint256 _numberOfContracts); 47 | 48 | function contractName(uint256 idx) external view returns (bytes32 _contractName); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /contracts/modules/ITreasury.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 4 | 5 | interface ITreasury { 6 | 7 | event LogTreasurySuspended(); 8 | event LogTreasuryResumed(); 9 | 10 | event LogTreasuryProductTokenSet(uint256 productId, uint256 riskpoolId, address erc20Address); 11 | event LogTreasuryInstanceWalletSet(address walletAddress); 12 | event LogTreasuryRiskpoolWalletSet(uint256 riskpoolId, address walletAddress); 13 | 14 | event LogTreasuryPremiumFeesSet(uint256 productId, uint256 fixedFee, uint256 fractionalFee); 15 | event LogTreasuryCapitalFeesSet(uint256 riskpoolId, uint256 fixedFee, uint256 fractionalFee); 16 | 17 | event LogTreasuryPremiumTransferred(address from, address riskpoolWalletAddress, uint256 amount); 18 | event LogTreasuryPayoutTransferred(address riskpoolWalletAddress, address to, uint256 amount); 19 | event LogTreasuryCapitalTransferred(address from, address riskpoolWalletAddress, uint256 amount); 20 | event LogTreasuryFeesTransferred(address from, address instanceWalletAddress, uint256 amount); 21 | event LogTreasuryWithdrawalTransferred(address riskpoolWalletAddress, address to, uint256 amount); 22 | 23 | event LogTreasuryPremiumProcessed(bytes32 processId, uint256 amount); 24 | event LogTreasuryPayoutProcessed(uint256 riskpoolId, address to, uint256 amount); 25 | event LogTreasuryCapitalProcessed(uint256 riskpoolId, uint256 bundleId, uint256 amount); 26 | event LogTreasuryWithdrawalProcessed(uint256 riskpoolId, uint256 bundleId, uint256 amount); 27 | 28 | struct FeeSpecification { 29 | uint256 componentId; 30 | uint256 fixedFee; 31 | uint256 fractionalFee; 32 | bytes feeCalculationData; 33 | uint256 createdAt; 34 | uint256 updatedAt; 35 | } 36 | 37 | function setProductToken(uint256 productId, address erc20Address) external; 38 | 39 | function setInstanceWallet(address instanceWalletAddress) external; 40 | function setRiskpoolWallet(uint256 riskpoolId, address riskpoolWalletAddress) external; 41 | 42 | function createFeeSpecification( 43 | uint256 componentId, 44 | uint256 fixedFee, 45 | uint256 fractionalFee, 46 | bytes calldata feeCalculationData 47 | ) 48 | external view returns(FeeSpecification memory feeSpec); 49 | 50 | function setPremiumFees(FeeSpecification calldata feeSpec) external; 51 | function setCapitalFees(FeeSpecification calldata feeSpec) external; 52 | 53 | function processPremium(bytes32 processId) external 54 | returns( 55 | bool success, 56 | uint256 feeAmount, 57 | uint256 netPremiumAmount 58 | ); 59 | 60 | function processPremium(bytes32 processId, uint256 amount) external 61 | returns( 62 | bool success, 63 | uint256 feeAmount, 64 | uint256 netPremiumAmount 65 | ); 66 | 67 | function processPayout(bytes32 processId, uint256 payoutId) external 68 | returns( 69 | uint256 feeAmount, 70 | uint256 netPayoutAmount 71 | ); 72 | 73 | function processCapital(uint256 bundleId, uint256 capitalAmount) external 74 | returns( 75 | uint256 feeAmount, 76 | uint256 netCapitalAmount 77 | ); 78 | 79 | function processWithdrawal(uint256 bundleId, uint256 amount) external 80 | returns( 81 | uint256 feeAmount, 82 | uint256 netAmount 83 | ); 84 | 85 | function getComponentToken(uint256 componentId) external view returns(IERC20 token); 86 | function getFeeSpecification(uint256 componentId) external view returns(FeeSpecification memory feeSpecification); 87 | 88 | function getFractionFullUnit() external view returns(uint256); 89 | function getInstanceWallet() external view returns(address instanceWalletAddress); 90 | function getRiskpoolWallet(uint256 riskpoolId) external view returns(address riskpoolWalletAddress); 91 | 92 | } 93 | -------------------------------------------------------------------------------- /contracts/services/IComponentOwnerService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "../components/IComponent.sol"; 5 | 6 | interface IComponentOwnerService { 7 | 8 | function propose(IComponent component) external; 9 | 10 | function stake(uint256 id) external; 11 | function withdraw(uint256 id) external; 12 | 13 | function pause(uint256 id) external; 14 | function unpause(uint256 id) external; 15 | 16 | function archive(uint256 id) external; 17 | } 18 | -------------------------------------------------------------------------------- /contracts/services/IInstanceOperatorService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "../modules/ITreasury.sol"; 5 | 6 | interface IInstanceOperatorService { 7 | 8 | // registry 9 | function prepareRelease(bytes32 newRelease) external; 10 | function register(bytes32 contractName, address contractAddress) external; 11 | function deregister(bytes32 contractName) external; 12 | function registerInRelease(bytes32 release, bytes32 contractName, address contractAddress) external; 13 | function deregisterInRelease(bytes32 release, bytes32 contractName) external; 14 | 15 | // access 16 | function createRole(bytes32 role) external; 17 | function invalidateRole(bytes32 role) external; 18 | function grantRole(bytes32 role, address principal) external; 19 | function revokeRole(bytes32 role, address principal) external; 20 | 21 | // component 22 | function approve(uint256 id) external; 23 | function decline(uint256 id) external; 24 | function suspend(uint256 id) external; 25 | function resume(uint256 id) external; 26 | function archive(uint256 id) external; 27 | 28 | // service staking 29 | function setDefaultStaking(uint16 componentType, bytes calldata data) external; 30 | function adjustStakingRequirements(uint256 id, bytes calldata data) external; 31 | 32 | // treasury 33 | function suspendTreasury() external; 34 | function resumeTreasury() external; 35 | 36 | function setInstanceWallet(address walletAddress) external; 37 | function setRiskpoolWallet(uint256 riskpoolId, address walletAddress) external; 38 | function setProductToken(uint256 productId, address erc20Address) external; 39 | 40 | function setPremiumFees(ITreasury.FeeSpecification calldata feeSpec) external; 41 | function setCapitalFees(ITreasury.FeeSpecification calldata feeSpec) external; 42 | 43 | function createFeeSpecification( 44 | uint256 componentId, 45 | uint256 fixedFee, 46 | uint256 fractionalFee, 47 | bytes calldata feeCalculationData 48 | ) external view returns(ITreasury.FeeSpecification memory); 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /contracts/services/IInstanceService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "../components/IComponent.sol"; 5 | import "../modules/IBundle.sol"; 6 | import "../modules/IPolicy.sol"; 7 | import "../modules/IPool.sol"; 8 | import "../tokens/IBundleToken.sol"; 9 | import "./IComponentOwnerService.sol"; 10 | import "./IInstanceOperatorService.sol"; 11 | import "./IOracleService.sol"; 12 | import "./IProductService.sol"; 13 | import "./IRiskpoolService.sol"; 14 | 15 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 16 | import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; 17 | 18 | interface IInstanceService { 19 | 20 | // instance 21 | function getChainId() external view returns(uint256 chainId); 22 | function getChainName() external view returns(string memory chainName); 23 | function getInstanceId() external view returns(bytes32 instanceId); 24 | function getInstanceOperator() external view returns(address instanceOperator); 25 | 26 | // registry 27 | function getComponentOwnerService() external view returns(IComponentOwnerService service); 28 | function getInstanceOperatorService() external view returns(IInstanceOperatorService service); 29 | function getOracleService() external view returns(IOracleService service); 30 | function getProductService() external view returns(IProductService service); 31 | function getRiskpoolService() external view returns(IRiskpoolService service); 32 | function contracts() external view returns (uint256 numberOfContracts); 33 | function contractName(uint256 idx) external view returns (bytes32 name); 34 | 35 | // access 36 | function getDefaultAdminRole() external view returns(bytes32 role); 37 | function getProductOwnerRole() external view returns(bytes32 role); 38 | function getOracleProviderRole() external view returns(bytes32 role); 39 | function getRiskpoolKeeperRole() external view returns(bytes32 role); 40 | function hasRole(bytes32 role, address principal) external view returns (bool roleIsAssigned); 41 | 42 | // component 43 | function products() external view returns(uint256 numberOfProducts); 44 | function oracles() external view returns(uint256 numberOfOracles); 45 | function riskpools() external view returns(uint256 numberOfRiskpools); 46 | 47 | function getComponentId(address componentAddress) external view returns(uint256 componentId); 48 | function getComponent(uint256 componentId) external view returns(IComponent component); 49 | function getComponentType(uint256 componentId) external view returns(IComponent.ComponentType componentType); 50 | function getComponentState(uint256 componentId) external view returns(IComponent.ComponentState componentState); 51 | 52 | // service staking 53 | function getStakingRequirements(uint256 componentId) external view returns(bytes memory data); 54 | function getStakedAssets(uint256 componentId) external view returns(bytes memory data); 55 | 56 | // riskpool 57 | function getRiskpool(uint256 riskpoolId) external view returns(IPool.Pool memory riskPool); 58 | function getFullCollateralizationLevel() external view returns (uint256); 59 | function getCapital(uint256 riskpoolId) external view returns(uint256 capitalAmount); 60 | function getTotalValueLocked(uint256 riskpoolId) external view returns(uint256 totalValueLockedAmount); 61 | function getCapacity(uint256 riskpoolId) external view returns(uint256 capacityAmount); 62 | function getBalance(uint256 riskpoolId) external view returns(uint256 balanceAmount); 63 | 64 | function activeBundles(uint256 riskpoolId) external view returns(uint256 numberOfActiveBundles); 65 | function getActiveBundleId(uint256 riskpoolId, uint256 bundleIdx) external view returns(uint256 bundleId); 66 | function getMaximumNumberOfActiveBundles(uint256 riskpoolId) external view returns(uint256 maximumNumberOfActiveBundles); 67 | 68 | // bundles 69 | function getBundleToken() external view returns(IBundleToken token); 70 | function bundles() external view returns(uint256 numberOfBundles); 71 | function getBundle(uint256 bundleId) external view returns(IBundle.Bundle memory bundle); 72 | function unburntBundles(uint256 riskpoolId) external view returns(uint256 numberOfUnburntBundles); 73 | 74 | // policy 75 | function processIds() external view returns(uint256 numberOfProcessIds); 76 | function getMetadata(bytes32 processId) external view returns(IPolicy.Metadata memory metadata); 77 | function getApplication(bytes32 processId) external view returns(IPolicy.Application memory application); 78 | function getPolicy(bytes32 processId) external view returns(IPolicy.Policy memory policy); 79 | function claims(bytes32 processId) external view returns(uint256 numberOfClaims); 80 | function payouts(bytes32 processId) external view returns(uint256 numberOfPayouts); 81 | 82 | function getClaim(bytes32 processId, uint256 claimId) external view returns (IPolicy.Claim memory claim); 83 | function getPayout(bytes32 processId, uint256 payoutId) external view returns (IPolicy.Payout memory payout); 84 | 85 | // treasury 86 | function getTreasuryAddress() external view returns(address treasuryAddress); 87 | 88 | function getInstanceWallet() external view returns(address walletAddress); 89 | function getRiskpoolWallet(uint256 riskpoolId) external view returns(address walletAddress); 90 | 91 | function getComponentToken(uint256 componentId) external view returns(IERC20 token); 92 | function getFeeFractionFullUnit() external view returns(uint256 fullUnit); 93 | 94 | } 95 | -------------------------------------------------------------------------------- /contracts/services/IOracleService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IOracleService { 5 | 6 | function respond(uint256 requestId, bytes calldata data) external; 7 | } 8 | -------------------------------------------------------------------------------- /contracts/services/IProductService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IProductService { 5 | 6 | function newApplication( 7 | address owner, 8 | uint256 premiumAmount, 9 | uint256 sumInsuredAmount, 10 | bytes calldata metaData, 11 | bytes calldata applicationData 12 | ) external returns(bytes32 processId); 13 | 14 | function collectPremium(bytes32 processId, uint256 amount) external 15 | returns( 16 | bool success, 17 | uint256 feeAmount, 18 | uint256 netPremiumAmount 19 | ); 20 | 21 | function adjustPremiumSumInsured( 22 | bytes32 processId, 23 | uint256 expectedPremiumAmount, 24 | uint256 sumInsuredAmount 25 | ) external; 26 | 27 | function revoke(bytes32 processId) external; 28 | function underwrite(bytes32 processId) external returns(bool success); 29 | function decline(bytes32 processId) external; 30 | function expire(bytes32 processId) external; 31 | function close(bytes32 processId) external; 32 | 33 | function newClaim( 34 | bytes32 processId, 35 | uint256 claimAmount, 36 | bytes calldata data 37 | ) external returns(uint256 claimId); 38 | 39 | function confirmClaim( 40 | bytes32 processId, 41 | uint256 claimId, 42 | uint256 confirmedAmount 43 | ) external; 44 | 45 | function declineClaim(bytes32 processId, uint256 claimId) external; 46 | function closeClaim(bytes32 processId, uint256 claimId) external; 47 | 48 | function newPayout( 49 | bytes32 processId, 50 | uint256 claimId, 51 | uint256 amount, 52 | bytes calldata data 53 | ) external returns(uint256 payoutId); 54 | 55 | function processPayout(bytes32 processId, uint256 payoutId) external 56 | returns( 57 | uint256 feeAmount, 58 | uint256 netPayoutAmount 59 | ); 60 | 61 | function request( 62 | bytes32 processId, 63 | bytes calldata data, 64 | string calldata callbackMethodName, 65 | address callbackContractAddress, 66 | uint256 responsibleOracleId 67 | ) external returns(uint256 requestId); 68 | 69 | function cancelRequest(uint256 requestId) external; 70 | } 71 | -------------------------------------------------------------------------------- /contracts/services/IRiskpoolService.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface IRiskpoolService { 5 | 6 | function registerRiskpool( 7 | address wallet, 8 | address erc20Token, 9 | uint256 collateralization, 10 | uint256 sumOfSumInsuredCap 11 | ) external; 12 | 13 | function createBundle(address owner_, bytes calldata filter_, uint256 amount_) external returns(uint256 bundleId); 14 | function fundBundle(uint256 bundleId, uint256 amount) external returns(uint256 netAmount); 15 | function defundBundle(uint256 bundleId, uint256 amount) external returns(uint256 netAmount); 16 | 17 | function lockBundle(uint256 bundleId) external; 18 | function unlockBundle(uint256 bundleId) external; 19 | function closeBundle(uint256 bundleId) external; 20 | function burnBundle(uint256 bundleId) external; 21 | 22 | function collateralizePolicy(uint256 bundleId, bytes32 processId, uint256 collateralAmount) external; 23 | function processPremium(uint256 bundleId, bytes32 processId, uint256 amount) external; 24 | function processPayout(uint256 bundleId, bytes32 processId, uint256 amount) external; 25 | function releasePolicy(uint256 bundleId, bytes32 processId) external returns(uint256 collateralAmount); 26 | 27 | function setMaximumNumberOfActiveBundles(uint256 riskpoolId, uint256 maxNumberOfActiveBundles) external; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /contracts/shared/ICoreProxy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | interface ICoreProxy { 5 | 6 | event LogCoreContractUpgraded ( 7 | address oldImplementation, 8 | address newImplemntation 9 | ); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /contracts/tokens/IBundleToken.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | pragma solidity 0.8.2; 3 | 4 | import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; 5 | 6 | interface IBundleToken is 7 | IERC721 8 | { 9 | event LogBundleTokenMinted(uint256 bundleId, uint256 tokenId, address tokenOwner); 10 | event LogBundleTokenBurned(uint256 bundleId, uint256 tokenId); 11 | 12 | function burned(uint tokenId) external view returns(bool isBurned); 13 | function exists(uint256 tokenId) external view returns(bool doesExist); 14 | function getBundleId(uint256 tokenId) external view returns(uint256 bundleId); 15 | function totalSupply() external view returns(uint256 tokenCount); 16 | } 17 | -------------------------------------------------------------------------------- /docs/ayii_product_new_application.md: -------------------------------------------------------------------------------- 1 | # AYII Product new applicatoon 2 | 3 | ```mermaid 4 | sequenceDiagram 5 | participant P as AyiiProduct 6 | participant PS as ProductService 7 | participant PDF as PolicyDefaultFlow 8 | participant PC as PolicyController 9 | participant POOLC as PoolController 10 | participant RP as Riskpool 11 | participant RS as RiskpoolService 12 | participant BC as BundleController 13 | P->>PS: newApplication() 14 | PS->>PDF: delegate newApplication() 15 | PDF->>+PC: createPolicyFlow() 16 | PC->>-PDF: processId 17 | PDF->>+PC: createApplication() 18 | PC->>-PDF: _ 19 | PDF->>PS: processId 20 | PS->>P: processId 21 | P->>PS: underwrite() 22 | PS->>PDF: delegate underwrite() 23 | PDF->>POOLC: underwrite() 24 | POOLC->>RP: collateralizePolicy() 25 | activate RP 26 | Note right of RP: _lockCollateral() 27 | RP->>RS: collateralizePolicy() 28 | RS->>+BC: collateralizePolicy() 29 | BC->>-RS: _ 30 | RS->>RP: _ 31 | RP->>POOLC: success 32 | deactivate RP 33 | POOLC->>PDF: success 34 | PDF->>PS: success 35 | PS->>P: success 36 | ``` 37 | -------------------------------------------------------------------------------- /docs/ayii_product_trigger_oracle.md: -------------------------------------------------------------------------------- 1 | # AYII Product trigger oracle 2 | 3 | ```mermaid 4 | sequenceDiagram 5 | participant P as AyiiProduct 6 | participant PS as ProductService 7 | participant PDF as PolicyDefaultFlow 8 | participant QM as QueryModule 9 | participant OS as OracleService 10 | participant AO as AyiiOracle 11 | participant CT as ChainlinkToken 12 | participant OP as ChainlinkOperator 13 | participant CN as ChainlinkNode 14 | participant PA as Pula API 15 | P->>PS: request() 16 | PS->>PDF: delegate request() 17 | PDF->>QM: request() 18 | QM->>AO: request() 19 | AO->>AO: buildChainlinkRequest() 20 | AO->>CT: transferAndCall() 21 | CT->>OP: operatorRequest() 22 | Note right of OP: emits OracleRequest 23 | CN->>+CN: awaits OracleRequest 24 | Note right of CN: executes Chainlink Job 25 | CN->>+PA: Any API call 26 | PA->>-CN: API response 27 | CN->>AO: fulfill() 28 | AO->>OS: respond() 29 | OS->>QM: respond() 30 | QM->>P: oracleCallback() 31 | P->>P: calculatePayoutPercentage() 32 | ``` 33 | -------------------------------------------------------------------------------- /docs/component_states.md: -------------------------------------------------------------------------------- 1 | # Component states 2 | 3 | ## Diagram 4 | 5 | ```mermaid 6 | stateDiagram-v2 7 | [*] --> Proposed: (CO) 8 | Proposed --> Declined: (IO) 9 | Proposed --> Active: (IO) 10 | Active --> Paused: Pause \n(CO) 11 | Paused --> Active: Unpause \n(CO) 12 | Active --> Suspended: Suspend \n(IO) 13 | Suspended --> Active: Resume \n(IO) 14 | Suspended --> Archived: (IO) 15 | Paused --> Archived: (CO, IO) 16 | Declined --> [*] 17 | Archived --> [*] 18 | ``` 19 | 20 | - CO: ComponentOwner 21 | - IO: InstanceOperator 22 | -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = "contracts" 3 | out = "build_foundry" 4 | libs = ["lib"] 5 | test = "tests_foundry" 6 | 7 | # See more config options https://github.com/foundry-rs/foundry/tree/master/config 8 | 9 | remappings = [ 10 | "@openzeppelin/=lib/openzeppelin-contracts/", 11 | "@forgestd/=lib/forge-std/src/", 12 | ] 13 | 14 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@etherisc/gif-interface", 3 | "version": "2.0.0-rc.1", 4 | "lockfileVersion": 2, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "@etherisc/gif-interface", 9 | "version": "2.0.0-rc.1", 10 | "license": "Apache-2.0", 11 | "dependencies": { 12 | "@openzeppelin/contracts": "4.7.3" 13 | } 14 | }, 15 | "node_modules/@openzeppelin/contracts": { 16 | "version": "4.7.3", 17 | "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.7.3.tgz", 18 | "integrity": "sha512-dGRS0agJzu8ybo44pCIf3xBaPQN/65AIXNgK8+4gzKd5kbvlqyxryUYVLJv7fK98Seyd2hDZzVEHSWAh0Bt1Yw==" 19 | } 20 | }, 21 | "dependencies": { 22 | "@openzeppelin/contracts": { 23 | "version": "4.7.3", 24 | "resolved": "https://registry.npmjs.org/@openzeppelin/contracts/-/contracts-4.7.3.tgz", 25 | "integrity": "sha512-dGRS0agJzu8ybo44pCIf3xBaPQN/65AIXNgK8+4gzKd5kbvlqyxryUYVLJv7fK98Seyd2hDZzVEHSWAh0Bt1Yw==" 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@etherisc/gif-interface", 3 | "version": "2.0.0-rc.1", 4 | "description": "This repository holds the necessary interfaces and base contracts to interact with an existing GIF instance. The repository is not intended to be used on its own.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/etherisc/gif-interface.git" 8 | }, 9 | "files": [ 10 | "contracts/**/*sol", 11 | "build/**/*" 12 | ], 13 | "keywords": [ 14 | "etherisc", 15 | "dip", 16 | "gif", 17 | "insurance", 18 | "blockchain", 19 | "ethereum", 20 | "solidity" 21 | ], 22 | "license": "Apache-2.0", 23 | "homepage": "https://www.etherisc.com", 24 | "bugs": { 25 | "url": "https://github.com/etherisc/gif-interface/issues" 26 | }, 27 | "dependencies": { 28 | "@openzeppelin/contracts": "4.7.3" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests_foundry/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/etherisc/gif-interface/0e58b1f03234915e44d65000756b5fc231da44d3/tests_foundry/.keep --------------------------------------------------------------------------------