# Table of Contents
- [Generic Insurance Framework - Etherisc Docs](#generic-insurance-framework-etherisc-docs)
- [GIF Contracts - Etherisc Docs](#gif-contracts-etherisc-docs)
- [Core Contracts - Etherisc Docs](#core-contracts-etherisc-docs)
- [Flows - Etherisc Docs](#flows-etherisc-docs)
- [Tokens - Etherisc Docs](#tokens-etherisc-docs)
- [Shared - Etherisc Docs](#shared-etherisc-docs)
- [Components - Etherisc Docs](#components-etherisc-docs)
- [Global Registry - Etherisc Docs](#global-registry-etherisc-docs)
- [Overview - Etherisc Docs](#overview-etherisc-docs)
- [Sandbox - Etherisc Docs](#sandbox-etherisc-docs)
- [GIF Monitor - Etherisc Docs](#gif-monitor-etherisc-docs)
- [Roles - Etherisc Docs](#roles-etherisc-docs)
- [Instances - Etherisc Docs](#instances-etherisc-docs)
- [Data Model - Etherisc Docs](#data-model-etherisc-docs)
- [Services - Etherisc Docs](#services-etherisc-docs)
- [Governance Model - Etherisc Docs](#governance-model-etherisc-docs)
- [Services - Etherisc Docs](#services-etherisc-docs)
- [Modules - Etherisc Docs](#modules-etherisc-docs)
- [Test - Etherisc Docs](#test-etherisc-docs)
- [Error Codes - Etherisc Docs](#error-codes-etherisc-docs)
- [Token Model - Etherisc Docs](#token-model-etherisc-docs)
- [Learn - Etherisc Docs](#learn-etherisc-docs)
- [Q & A - Etherisc Docs](#q-a-etherisc-docs)
- [Basics about the GIF framework - Etherisc Docs](#basics-about-the-gif-framework-etherisc-docs)
- [Developing smart contracts - Etherisc Docs](#developing-smart-contracts-etherisc-docs)
- [Staking as a fundamental building block for insurance - Etherisc Docs](#staking-as-a-fundamental-building-block-for-insurance-etherisc-docs)
- [DIP Token - Etherisc Docs](#dip-token-etherisc-docs)
- [Deploying and interacting with smart contracts - Etherisc Docs](#deploying-and-interacting-with-smart-contracts-etherisc-docs)
- [Depeg protection tutorial - Etherisc Docs](#depeg-protection-tutorial-etherisc-docs)
- [Preparing for mainnet - Etherisc Docs](#preparing-for-mainnet-etherisc-docs)
- [The Etherisc DIP staking web app - Etherisc Docs](#the-etherisc-dip-staking-web-app-etherisc-docs)
- [Documentation - Etherisc Docs](#documentation-etherisc-docs)
- [Etherisc Docs](#etherisc-docs)
- [tl;dr - Etherisc Docs](#tl-dr-etherisc-docs)
- [Etherisc - Terms of Service - Etherisc Docs](#etherisc-terms-of-service-etherisc-docs)
- [The GIF sandbox - Etherisc Docs](#the-gif-sandbox-etherisc-docs)
- [Privacy Policy for the websites and mobile apps of Etherisc GmbH - Etherisc Docs](#privacy-policy-for-the-websites-and-mobile-apps-of-etherisc-gmbh-etherisc-docs)
- [FAQ Etherisc DIP staking - Etherisc Docs](#faq-etherisc-dip-staking-etherisc-docs)
- [Base - Etherisc Docs](#base-etherisc-docs)
- [GIF Next - Etherisc Docs](#gif-next-etherisc-docs)
- [Accounting - Etherisc Docs](#accounting-etherisc-docs)
- [Acknowledgements
- Etherisc Docs](#acknowledgements-br-etherisc-docs)
- [Remerciements
- Etherisc Docs](#remerciements-br-etherisc-docs)
- [Unpermissioned example components - Etherisc Docs](#unpermissioned-example-components-etherisc-docs)
- [Distribution - Etherisc Docs](#distribution-etherisc-docs)
- [Fire insurance example components - Etherisc Docs](#fire-insurance-example-components-etherisc-docs)
- [Authorization - Etherisc Docs](#authorization-etherisc-docs)
- [Instance - Etherisc Docs](#instance-etherisc-docs)
- [Module - Etherisc Docs](#module-etherisc-docs)
- [Setup of the development environment - Etherisc Docs](#setup-of-the-development-environment-etherisc-docs)
- [Fire insurance example - Etherisc Docs](#fire-insurance-example-etherisc-docs)
- [How to write documentation - Etherisc Docs](#how-to-write-documentation-etherisc-docs)
- [Oracle - Etherisc Docs](#oracle-etherisc-docs)
- [Upgradeability - Etherisc Docs](#upgradeability-etherisc-docs)
- [Setup of the development environment - Etherisc Docs](#setup-of-the-development-environment-etherisc-docs)
- [Fire insurance registration - Etherisc Docs](#fire-insurance-registration-etherisc-docs)
- [Fire insurance implementation - Etherisc Docs](#fire-insurance-implementation-etherisc-docs)
- [Compile, deploy and interact - Etherisc Docs](#compile-deploy-and-interact-etherisc-docs)
- [Shared - Etherisc Docs](#shared-etherisc-docs)
- [GIF Sandbox - Etherisc Docs](#gif-sandbox-etherisc-docs)
- [Types - Etherisc Docs](#types-etherisc-docs)
- [Pool - Etherisc Docs](#pool-etherisc-docs)
- [Product - Etherisc Docs](#product-etherisc-docs)
- [Registry - Etherisc Docs](#registry-etherisc-docs)
- [Staking - Etherisc Docs](#staking-etherisc-docs)
- [Architecture - Etherisc Docs](#architecture-etherisc-docs)
---
# Generic Insurance Framework - Etherisc Docs
Generic Insurance Framework
===========================
Comprehensive guides for every aspect of the Generic Insurance Framework.
[Overview Introduction in the structure, concepts and architecture of the GIF.](overview)
[Instances Instances are deployments of the smart contracts which can run products, oracles and risk pools.](instances)
[Sandbox The sandbox allows you to get a working playground up and running in a few minutes.](sandbox)
[Global registry Certified instances are registered in a global registry. This creates trust and accountability for all stakeholders in the ecosystem.](#registry.adoc)
[Data Model The extensible and generic data model ensures consistency and auditability.](data-model)
[Roles Roles allow a fine-grained access control and permission system which secures the system and guarantees accountability.](roles)
[Components Components are the basic building blocks which enable composability and reusability.](components)
[Services Services provide generic functionalities for the lifecycle and operation of insurance products.](services)
[Token Model The token model provides the economic backbone of the ecosystem.](token-model)
[Governance The Etherisc Governance Model (EGM) defines the rules of the larger ecosystem and ensures the alignment of interest of all stakeholders.](governance-model)
[GIF Monitor The GIF Monitor serves as the central information hub to display in-depth data of all GIF instances, their products, oracles and riskpools.](gif-monitor)
[Overview →](/gif/overview)
---
# GIF Contracts - Etherisc Docs
GIF Contracts
=============
**Secure and audited smart contracts to develop decentralized insurance applications.**
* GIF Contracts is a library of smart contracts for decentralized insurance applications.
[](#overview)
Overview
----------------------
### [](#install)
Installation
$ npm install @etherisc/gif-contracts
Etherisc GIF Contracts features a [stable API](#releases-stability.adoc#api-stability)
, which means your contracts won’t break unexpectedly when upgrading to a newer minor version.
### [](#usage)
Usage
Once installed, you can use the contracts in the library by importing them:
// contracts/MyProduct.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@etherisc/gif-interface/contracts/components/Product.sol";
contract MyProduct is Product {
bytes32 public constant POLICY_FLOW = "PolicyDefaultFlow";
constructor(
bytes32 productName,
address token,
address registry,
uint256 riskpoolId,
)
Product(productName, token, POLICY_FLOW, riskpoolId, registry)
{
}
}
| | |
| --- | --- |
| | If you’re new to smart contract development, head to … to learn about creating a new project and compiling your contracts. |
To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don’t need to worry about it needlessly increasing gas costs.
[](#error_codes)
Error Codes
----------------------------
Each error has a 7-letter identifier of the form `XXX-###`. The first three letters indicate the component where the error occurred, and the last three letters indicate the error number within that component. A list of the error codes with explanations / conditions is available in the [Errors](errorCodes)
section.
[](#next-steps)
Learn More
--------------------------
The guides in the sidebar will teach about different concepts, and how to use the related contracts that GIF Contracts provides:
[Flows →](/contracts/2.x/api/flows)
---
# Core Contracts - Etherisc Docs
Core Contracts
==============
The core contracts are a collection of open source smart contracts that implement essential insurance product and policy lifecycle functions. This enables the modeling of a wide range of insurance types.
The core contracts provide the generic functions for all sub-steps in the lifecycle of an insurance policy and thus enable an automated workflow.
Core smart contracts are deployed and operated by an instance operator - a DAO or other legal entity. The instance operator publishes entry points to its instance of the GIF and registers actors.
For a concise overview of the basic concepts see here:
[Tutorial: Understanding the basic concepts of the GIF Framework.](../learn/basics-gif)
[](#organization)
Organization
------------------------------
The core contracts are organized in folders in the `gif-contracts` repo:
/contracts
├── /flows
├── /modules
├── /services
├── /shared
└── /tokens
[](#contracts)
Contracts
------------------------
### [](#flows)
Flows
Flows encapsulate the business logic which controls the life cycle of an insurance product. Currently we offer a very generic default flow (`PolicyDefaultFlow`) which typically suits most products with a fixed policy period. Special flows could be created for revolving policies, or policies without a fixed end date.
A policy flow guarantees the overall consistency of all data objects during the lifecycle of a process and maintains all state transistions.
#### [](#policydefaultflow_sol)
PolicyDefaultFlow.sol
The default policy flow implements a standard policy lifecycle with application, underwriting, decline, expire, revoke functionality.
### [](#modules)
Modules
Modules encapsulate the functionality which operates on a certain data object. Each module guarantees the internal consistency and validity of its data objects. Modules are not accessible from the outside. They are only accessed via service contracts.
| | |
| --- | --- |
| | All contracts whose name ends in `...Controller.sol` will be renamed in `...Module.sol` in the next release. |
#### [](#accesscontroller_sol)
AccessController.sol
t.b.d.
#### [](#bundlecontroller_sol)
BundleController.sol
t.b.d.
#### [](#componentcontroller_sol)
ComponentController.sol
t.b.d.
#### [](#licensecontroller_sol)
LicenseController.sol
t.b.d.
#### [](#policycontroller_sol)
PolicyController.sol
t.b.d.
#### [](#poolcontroller_sol)
PoolController.sol
t.b.d.
#### [](#querymodule_sol)
QueryModule.sol
t.b.d.
#### [](#registrycontroller_sol)
RegistryController.sol
t.b.d.
#### [](#treasurymodule_sol)
TreasuryModule.sol
t.b.d.
### [](#services)
Services
Services provide defined access points by which the data objects can be manipulated in a controlled way.
#### [](#componentownerservice_sol)
ComponentOwnerService.sol
t.b.d.
#### [](#instanceoperatorservice_sol)
InstanceOperatorService.sol
t.b.d.
#### [](#instanceservice_sol)
InstanceService.sol
t.b.d.
#### [](#oracleservice_sol)
OracleService.sol
t.b.d.
#### [](#productservice_sol)
ProductService.sol
t.b.d.
#### [](#riskpoolservice_sol)
RiskpoolService.sol
t.b.d.
### [](#tokens)
Tokens
Tokens are used to represent ownership of investments in risk pools. The use of tokens allows the permissionless transfer of ownership.
#### [](#bundletoken_sol)
BundleToken.sol
t.b.d.
#### [](#riskpooltoken_sol)
RiskpoolToken.sol
t.b.d.
### [](#shared)
Shared
The following contracts provide some helper functionality or act as base classes, from which other contracts are derived.
#### [](#corecontroller_sol)
CoreController.sol
t.b.d.
#### [](#coreproxy_sol)
CoreProxy.sol
t.b.d.
#### [](#transferhelper_sol)
TransferHelper.sol
t.b.d.
#### [](#withregistry_sol)
WithRegistry.sol
t.b.d.
[← Overview](/gif/overview)
[Instances →](/gif/instances)
---
# Flows - Etherisc Docs
Flows
=====
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/flows](https://docs.etherisc.com/contracts/api/flows) |
[](#contracts)
Contracts
------------------------
### [](#PolicyDefaultFlow)
`PolicyDefaultFlow`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/flows/PolicyDefaultFlow.sol)
import "@etherisc/gif-contracts/contracts/flows/PolicyDefaultFlow.sol";
Modifiers
* [`onlyActivePolicy(processId)`](#PolicyDefaultFlow-onlyActivePolicy-bytes32-)
* [`onlyExpiredPolicy(processId)`](#PolicyDefaultFlow-onlyExpiredPolicy-bytes32-)
* [`notClosedPolicy(processId)`](#PolicyDefaultFlow-notClosedPolicy-bytes32-)
* [`onlyResponsibleProduct(processId)`](#PolicyDefaultFlow-onlyResponsibleProduct-bytes32-)
* [`onlyMatchingProduct(requestId)`](#PolicyDefaultFlow-onlyMatchingProduct-uint256-)
Functions
* [`constructor(_registry)`](#PolicyDefaultFlow-constructor-address-)
* [`newApplication(owner, premiumAmount, sumInsuredAmount, metaData, applicationData)`](#PolicyDefaultFlow-newApplication-address-uint256-uint256-bytes-bytes-)
* [`revoke(processId)`](#PolicyDefaultFlow-revoke-bytes32-)
* [`underwrite(processId)`](#PolicyDefaultFlow-underwrite-bytes32-)
* [`collectPremium(processId, amount)`](#PolicyDefaultFlow-collectPremium-bytes32-uint256-)
* [`adjustPremiumSumInsured(processId, expectedPremiumAmount, sumInsuredAmount)`](#PolicyDefaultFlow-adjustPremiumSumInsured-bytes32-uint256-uint256-)
* [`decline(processId)`](#PolicyDefaultFlow-decline-bytes32-)
* [`expire(processId)`](#PolicyDefaultFlow-expire-bytes32-)
* [`close(processId)`](#PolicyDefaultFlow-close-bytes32-)
* [`newClaim(processId, claimAmount, data)`](#PolicyDefaultFlow-newClaim-bytes32-uint256-bytes-)
* [`confirmClaim(processId, claimId, confirmedAmount)`](#PolicyDefaultFlow-confirmClaim-bytes32-uint256-uint256-)
* [`declineClaim(processId, claimId)`](#PolicyDefaultFlow-declineClaim-bytes32-uint256-)
* [`closeClaim(processId, claimId)`](#PolicyDefaultFlow-closeClaim-bytes32-uint256-)
* [`newPayout(processId, claimId, amount, data)`](#PolicyDefaultFlow-newPayout-bytes32-uint256-uint256-bytes-)
* [`processPayout(processId, payoutId)`](#PolicyDefaultFlow-processPayout-bytes32-uint256-)
* [`request(processId, _input, _callbackMethodName, _callbackContractAddress, _responsibleOracleId)`](#PolicyDefaultFlow-request-bytes32-bytes-string-address-uint256-)
* [`cancelRequest(requestId)`](#PolicyDefaultFlow-cancelRequest-uint256-)
* [`getApplicationData(processId)`](#PolicyDefaultFlow-getApplicationData-bytes32-)
* [`getClaimData(processId, claimId)`](#PolicyDefaultFlow-getClaimData-bytes32-uint256-)
* [`getPayoutData(processId, payoutId)`](#PolicyDefaultFlow-getPayoutData-bytes32-uint256-)
* [`getComponentContract()`](#PolicyDefaultFlow-getComponentContract--)
* [`getPoolContract()`](#PolicyDefaultFlow-getPoolContract--)
* [`getPolicyContract()`](#PolicyDefaultFlow-getPolicyContract--)
* [`getQueryContract()`](#PolicyDefaultFlow-getQueryContract--)
* [`getTreasuryContract()`](#PolicyDefaultFlow-getTreasuryContract--)
WithRegistry
* [`getContractFromRegistry(_contractName)`](shared#WithRegistry-getContractFromRegistry-bytes32-)
* [`getContractInReleaseFromRegistry(_release, _contractName)`](shared#WithRegistry-getContractInReleaseFromRegistry-bytes32-bytes32-)
* [`getReleaseFromRegistry()`](shared#WithRegistry-getReleaseFromRegistry--)
#### [](#PolicyDefaultFlow-onlyActivePolicy-bytes32-)
`onlyActivePolicy(bytes32 processId)` modifier
#### [](#PolicyDefaultFlow-onlyExpiredPolicy-bytes32-)
`onlyExpiredPolicy(bytes32 processId)` modifier
#### [](#PolicyDefaultFlow-notClosedPolicy-bytes32-)
`notClosedPolicy(bytes32 processId)` modifier
#### [](#PolicyDefaultFlow-onlyResponsibleProduct-bytes32-)
`onlyResponsibleProduct(bytes32 processId)` modifier
#### [](#PolicyDefaultFlow-onlyMatchingProduct-uint256-)
`onlyMatchingProduct(uint256 requestId)` modifier
#### [](#PolicyDefaultFlow-constructor-address-)
`constructor(address _registry)` public
Constructor function that initializes the contract with a given registry address.
#### [](#PolicyDefaultFlow-newApplication-address-uint256-uint256-bytes-bytes-)
`newApplication(address owner, uint256 premiumAmount, uint256 sumInsuredAmount, bytes metaData, bytes applicationData) → bytes32 processId` external
Creates a new insurance application and returns the process ID.
#### [](#PolicyDefaultFlow-revoke-bytes32-)
`revoke(bytes32 processId)` external
Revokes an application for a specific processId.
#### [](#PolicyDefaultFlow-underwrite-bytes32-)
`underwrite(bytes32 processId) → bool success` external
Attempts to get the collateral to secure the policy.
#### [](#PolicyDefaultFlow-collectPremium-bytes32-uint256-)
`collectPremium(bytes32 processId, uint256 amount) → bool success, uint256 feeAmount, uint256 netPremiumAmount` public
Collects the premium for a given policy and updates the book keeping of the policy and the risk pool.
#### [](#PolicyDefaultFlow-adjustPremiumSumInsured-bytes32-uint256-uint256-)
`adjustPremiumSumInsured(bytes32 processId, uint256 expectedPremiumAmount, uint256 sumInsuredAmount)` external
Adjusts the premium and sum insured amounts of a policy.
#### [](#PolicyDefaultFlow-decline-bytes32-)
`decline(bytes32 processId)` external
Allows the responsible product to decline an application for a policy.
#### [](#PolicyDefaultFlow-expire-bytes32-)
`expire(bytes32 processId)` external
Expire the policy identified by the given process ID.
#### [](#PolicyDefaultFlow-close-bytes32-)
`close(bytes32 processId)` external
Closes a policy and releases the corresponding funds from the pool.
#### [](#PolicyDefaultFlow-newClaim-bytes32-uint256-bytes-)
`newClaim(bytes32 processId, uint256 claimAmount, bytes data) → uint256 claimId` external
Creates a new claim for a given process ID, claim amount and data.
#### [](#PolicyDefaultFlow-confirmClaim-bytes32-uint256-uint256-)
`confirmClaim(bytes32 processId, uint256 claimId, uint256 confirmedAmount)` external
Confirms a claim for a specific process and claim ID, updating the confirmed amount.
#### [](#PolicyDefaultFlow-declineClaim-bytes32-uint256-)
`declineClaim(bytes32 processId, uint256 claimId)` external
Allows the responsible product to decline a claim.
#### [](#PolicyDefaultFlow-closeClaim-bytes32-uint256-)
`closeClaim(bytes32 processId, uint256 claimId)` external
Closes a claim for a specific process and claim ID.
#### [](#PolicyDefaultFlow-newPayout-bytes32-uint256-uint256-bytes-)
`newPayout(bytes32 processId, uint256 claimId, uint256 amount, bytes data) → uint256 payoutId` external
Creates a new payout for a specific claim.
#### [](#PolicyDefaultFlow-processPayout-bytes32-uint256-)
`processPayout(bytes32 processId, uint256 payoutId) → bool success, uint256 feeAmount, uint256 netPayoutAmount` external
Processes a payout for a specific process and payout ID.
#### [](#PolicyDefaultFlow-request-bytes32-bytes-string-address-uint256-)
`request(bytes32 processId, bytes _input, string _callbackMethodName, address _callbackContractAddress, uint256 _responsibleOracleId) → uint256 _requestId` external
Sends a request to the query contract to initiate a new process.
#### [](#PolicyDefaultFlow-cancelRequest-uint256-)
`cancelRequest(uint256 requestId)` external
Cancels a request with the given requestId.
#### [](#PolicyDefaultFlow-getApplicationData-bytes32-)
`getApplicationData(bytes32 processId) → bytes` external
Returns the application data associated with the given process ID.
#### [](#PolicyDefaultFlow-getClaimData-bytes32-uint256-)
`getClaimData(bytes32 processId, uint256 claimId) → bytes` external
Returns the claim data of a specific claim for a given process ID.
#### [](#PolicyDefaultFlow-getPayoutData-bytes32-uint256-)
`getPayoutData(bytes32 processId, uint256 payoutId) → bytes` external
Returns the payout data for a given process and payout ID.
#### [](#PolicyDefaultFlow-getComponentContract--)
`getComponentContract() → contract ComponentController` internal
Returns the ComponentController contract instance.
#### [](#PolicyDefaultFlow-getPoolContract--)
`getPoolContract() → contract PoolController` internal
Returns the PoolController contract instance from the registry.
#### [](#PolicyDefaultFlow-getPolicyContract--)
`getPolicyContract() → contract PolicyController` internal
Returns the PolicyController contract instance from the registry.
#### [](#PolicyDefaultFlow-getQueryContract--)
`getQueryContract() → contract QueryModule` internal
Returns the QueryModule contract instance from the registry.
#### [](#PolicyDefaultFlow-getTreasuryContract--)
`getTreasuryContract() → contract TreasuryModule` internal
Retrieves the TreasuryModule contract instance.
[← Overview](/contracts/2.x/)
[Modules →](/contracts/2.x/api/modules)
---
# Tokens - Etherisc Docs
Tokens
======
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/tokens](https://docs.etherisc.com/contracts/api/tokens) |
[](#contracts)
Contracts
------------------------
### [](#BundleToken)
`BundleToken`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/tokens/BundleToken.sol)
import "@etherisc/gif-contracts/contracts/tokens/BundleToken.sol";
Modifiers
* [`onlyBundleModule()`](#BundleToken-onlyBundleModule--)
Functions
* [`constructor()`](#BundleToken-constructor--)
* [`setBundleModule(bundleModule)`](#BundleToken-setBundleModule-address-)
* [`mint(bundleId, to)`](#BundleToken-mint-uint256-address-)
* [`burn(tokenId)`](#BundleToken-burn-uint256-)
* [`burned(tokenId)`](#BundleToken-burned-uint256-)
* [`getBundleId(tokenId)`](#BundleToken-getBundleId-uint256-)
* [`getBundleModuleAddress()`](#BundleToken-getBundleModuleAddress--)
* [`exists(tokenId)`](#BundleToken-exists-uint256-)
* [`totalSupply()`](#BundleToken-totalSupply--)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
ERC721
* [`supportsInterface(interfaceId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-supportsInterface-bytes4-)
* [`balanceOf(owner)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-balanceOf-address-)
* [`ownerOf(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-ownerOf-uint256-)
* [`name()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-name--)
* [`symbol()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-symbol--)
* [`tokenURI(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-tokenURI-uint256-)
* [`_baseURI()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_baseURI--)
* [`approve(to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-approve-address-uint256-)
* [`getApproved(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-getApproved-uint256-)
* [`setApprovalForAll(operator, approved)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-setApprovalForAll-address-bool-)
* [`isApprovedForAll(owner, operator)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-isApprovedForAll-address-address-)
* [`transferFrom(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-transferFrom-address-address-uint256-)
* [`safeTransferFrom(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-safeTransferFrom-address-address-uint256-)
* [`safeTransferFrom(from, to, tokenId, data)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-safeTransferFrom-address-address-uint256-bytes-)
* [`_safeTransfer(from, to, tokenId, data)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_safeTransfer-address-address-uint256-bytes-)
* [`_exists(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_exists-uint256-)
* [`_isApprovedOrOwner(spender, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_isApprovedOrOwner-address-uint256-)
* [`_safeMint(to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_safeMint-address-uint256-)
* [`_safeMint(to, tokenId, data)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_safeMint-address-uint256-bytes-)
* [`_mint(to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_mint-address-uint256-)
* [`_burn(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_burn-uint256-)
* [`_transfer(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_transfer-address-address-uint256-)
* [`_approve(to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_approve-address-uint256-)
* [`_setApprovalForAll(owner, operator, approved)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_setApprovalForAll-address-address-bool-)
* [`_requireMinted(tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_requireMinted-uint256-)
* [`_beforeTokenTransfer(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_beforeTokenTransfer-address-address-uint256-)
* [`_afterTokenTransfer(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#ERC721-_afterTokenTransfer-address-address-uint256-)
Events
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
IBundleToken
* [`LogBundleTokenMinted(bundleId, tokenId, tokenOwner)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/tokens/IBundleToken.sol)
* [`LogBundleTokenBurned(bundleId, tokenId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/tokens/IBundleToken.sol)
IERC721
* [`Transfer(from, to, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#IERC721-Transfer-address-address-uint256-)
* [`Approval(owner, approved, tokenId)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#IERC721-Approval-address-address-uint256-)
* [`ApprovalForAll(owner, operator, approved)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC721#IERC721-ApprovalForAll-address-address-bool-)
#### [](#BundleToken-onlyBundleModule--)
`onlyBundleModule()` modifier
#### [](#BundleToken-constructor--)
`constructor()` public
Constructor function for the ERC721 token contract. It sets the name and symbol of the token and initializes the Ownable contract.
#### [](#BundleToken-setBundleModule-address-)
`setBundleModule(address bundleModule)` external
Sets the bundle module address.
#### [](#BundleToken-mint-uint256-address-)
`mint(uint256 bundleId, address to) → uint256 tokenId` external
Mints a new bundle token and assigns ownership to the specified address.
#### [](#BundleToken-burn-uint256-)
`burn(uint256 tokenId)` external
Burns a bundle token.
#### [](#BundleToken-burned-uint256-)
`burned(uint256 tokenId) → bool isBurned` external
Checks if a token has been burned.
#### [](#BundleToken-getBundleId-uint256-)
`getBundleId(uint256 tokenId) → uint256` external
Returns the bundle ID associated with a given token ID.
#### [](#BundleToken-getBundleModuleAddress--)
`getBundleModuleAddress() → address` external
Returns the address of the bundle module.
#### [](#BundleToken-exists-uint256-)
`exists(uint256 tokenId) → bool` external
Checks if a given token ID exists.
#### [](#BundleToken-totalSupply--)
`totalSupply() → uint256 tokenCount` external
Returns the total number of tokens in circulation.
### [](#RiskpoolToken)
`RiskpoolToken`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/tokens/RiskpoolToken.sol)
import "@etherisc/gif-contracts/contracts/tokens/RiskpoolToken.sol";
Functions
* [`constructor()`](#RiskpoolToken-constructor--)
ERC20
* [`name()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-name--)
* [`symbol()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-symbol--)
* [`decimals()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decimals--)
* [`totalSupply()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-totalSupply--)
* [`balanceOf(account)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-balanceOf-address-)
* [`transfer(to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-transfer-address-uint256-)
* [`allowance(owner, spender)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-allowance-address-address-)
* [`approve(spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-approve-address-uint256-)
* [`transferFrom(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-transferFrom-address-address-uint256-)
* [`increaseAllowance(spender, addedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-increaseAllowance-address-uint256-)
* [`decreaseAllowance(spender, subtractedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decreaseAllowance-address-uint256-)
* [`_transfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_transfer-address-address-uint256-)
* [`_mint(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_mint-address-uint256-)
* [`_burn(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_burn-address-uint256-)
* [`_approve(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_approve-address-address-uint256-)
* [`_spendAllowance(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_spendAllowance-address-address-uint256-)
* [`_beforeTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_beforeTokenTransfer-address-address-uint256-)
* [`_afterTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_afterTokenTransfer-address-address-uint256-)
Events
IERC20
* [`Transfer(from, to, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Transfer-address-address-uint256-)
* [`Approval(owner, spender, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Approval-address-address-uint256-)
#### [](#RiskpoolToken-constructor--)
`constructor()` public
Constructor function that sets the name and symbol of the ERC20 token.
[← Test](/contracts/2.x/api/test)
---
# Shared - Etherisc Docs
Shared
======
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/shared](https://docs.etherisc.com/contracts/api/shared) |
[](#contracts)
Contracts
------------------------
### [](#CoreController)
`CoreController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/shared/CoreController.sol)
import "@etherisc/gif-contracts/contracts/shared/CoreController.sol";
Modifiers
* [`onlyInstanceOperator()`](#CoreController-onlyInstanceOperator--)
* [`onlyPolicyFlow(module)`](#CoreController-onlyPolicyFlow-bytes32-)
Functions
* [`constructor()`](#CoreController-constructor--)
* [`initialize(registry)`](#CoreController-initialize-address-)
* [`_getName()`](#CoreController-_getName--)
* [`_afterInitialize()`](#CoreController-_afterInitialize--)
* [`_getContractAddress(contractName)`](#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#CoreController-onlyInstanceOperator--)
`onlyInstanceOperator()` modifier
#### [](#CoreController-onlyPolicyFlow-bytes32-)
`onlyPolicyFlow(bytes32 module)` modifier
#### [](#CoreController-constructor--)
`constructor()` public
Constructor function that disables initializers.
#### [](#CoreController-initialize-address-)
`initialize(address registry)` public
Initializes the contract with the provided registry address.
#### [](#CoreController-_getName--)
`_getName() → bytes32` internal
Returns the name of the contract.
#### [](#CoreController-_afterInitialize--)
`_afterInitialize()` internal
This function is called after the contract is initialized and can be used to perform additional setup.
#### [](#CoreController-_getContractAddress-bytes32-)
`_getContractAddress(bytes32 contractName) → address contractAddress` internal
Returns the address of a registered contract by its name.
### [](#CoreProxy)
`CoreProxy`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/shared/CoreProxy.sol)
import "@etherisc/gif-contracts/contracts/shared/CoreProxy.sol";
Modifiers
* [`onlyAdmin()`](#CoreProxy-onlyAdmin--)
Functions
* [`constructor(_controller, encoded_initializer)`](#CoreProxy-constructor-address-bytes-)
* [`implementation()`](#CoreProxy-implementation--)
* [`upgradeToAndCall(newImplementation, data)`](#CoreProxy-upgradeToAndCall-address-bytes-)
ERC1967Proxy
* [`_implementation()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Proxy-_implementation--)
ERC1967Upgrade
* [`_getImplementation()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_getImplementation--)
* [`_upgradeTo(newImplementation)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_upgradeTo-address-)
* [`_upgradeToAndCall(newImplementation, data, forceCall)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_upgradeToAndCall-address-bytes-bool-)
* [`_upgradeToAndCallUUPS(newImplementation, data, forceCall)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_upgradeToAndCallUUPS-address-bytes-bool-)
* [`_getAdmin()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_getAdmin--)
* [`_changeAdmin(newAdmin)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_changeAdmin-address-)
* [`_getBeacon()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_getBeacon--)
* [`_upgradeBeaconToAndCall(newBeacon, data, forceCall)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-_upgradeBeaconToAndCall-address-bytes-bool-)
Proxy
* [`_delegate(implementation)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Proxy-_delegate-address-)
* [`_fallback()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Proxy-_fallback--)
* [`fallback()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Proxy-fallback--)
* [`receive()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Proxy-receive--)
* [`_beforeFallback()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Proxy-_beforeFallback--)
Events
ERC1967Upgrade
* [`Upgraded(implementation)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-Upgraded-address-)
* [`AdminChanged(previousAdmin, newAdmin)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-AdminChanged-address-address-)
* [`BeaconUpgraded(beacon)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#ERC1967Upgrade-BeaconUpgraded-address-)
ICoreProxy
* [`LogCoreContractUpgraded(oldImplementation, newImplemntation)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/shared/ICoreProxy.sol)
#### [](#CoreProxy-onlyAdmin--)
`onlyAdmin()` modifier
#### [](#CoreProxy-constructor-address-bytes-)
`constructor(address _controller, bytes encoded_initializer)` public
Constructor function that creates a new instance of the contract.
#### [](#CoreProxy-implementation--)
`implementation() → address` external
Returns the address of the current implementation contract.
#### [](#CoreProxy-upgradeToAndCall-address-bytes-)
`upgradeToAndCall(address newImplementation, bytes data)` external
Upgrades the contract to a new implementation and forwards a function call to it.
### [](#TransferHelper)
`TransferHelper`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/shared/TransferHelper.sol)
import "@etherisc/gif-contracts/contracts/shared/TransferHelper.sol";
Functions
* [`unifiedTransferFrom(token, from, to, value)`](#TransferHelper-unifiedTransferFrom-contract-IERC20-address-address-uint256-)
Events
* [`LogTransferHelperInputValidation1Failed(tokenIsContract, from, to)`](#TransferHelper-LogTransferHelperInputValidation1Failed-bool-address-address-)
* [`LogTransferHelperInputValidation2Failed(balance, allowance)`](#TransferHelper-LogTransferHelperInputValidation2Failed-uint256-uint256-)
* [`LogTransferHelperCallFailed(callSuccess, returnDataLength, returnData)`](#TransferHelper-LogTransferHelperCallFailed-bool-uint256-bytes-)
#### [](#TransferHelper-unifiedTransferFrom-contract-IERC20-address-address-uint256-)
`unifiedTransferFrom(contract IERC20 token, address from, address to, uint256 value) → bool success` internal
Executes a transferFrom function call on an ERC20 token contract, after performing input validation.
#### [](#TransferHelper-LogTransferHelperInputValidation1Failed-bool-address-address-)
`LogTransferHelperInputValidation1Failed(bool tokenIsContract, address from, address to)` event
#### [](#TransferHelper-LogTransferHelperInputValidation2Failed-uint256-uint256-)
`LogTransferHelperInputValidation2Failed(uint256 balance, uint256 allowance)` event
#### [](#TransferHelper-LogTransferHelperCallFailed-bool-uint256-bytes-)
`LogTransferHelperCallFailed(bool callSuccess, uint256 returnDataLength, bytes returnData)` event
### [](#WithRegistry)
`WithRegistry`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/shared/WithRegistry.sol)
import "@etherisc/gif-contracts/contracts/shared/WithRegistry.sol";
Modifiers
* [`onlyInstanceOperator()`](#WithRegistry-onlyInstanceOperator--)
* [`onlyOracleService()`](#WithRegistry-onlyOracleService--)
* [`onlyOracleOwner()`](#WithRegistry-onlyOracleOwner--)
* [`onlyProductOwner()`](#WithRegistry-onlyProductOwner--)
Functions
* [`constructor(_registry)`](#WithRegistry-constructor-address-)
* [`getContractFromRegistry(_contractName)`](#WithRegistry-getContractFromRegistry-bytes32-)
* [`getContractInReleaseFromRegistry(_release, _contractName)`](#WithRegistry-getContractInReleaseFromRegistry-bytes32-bytes32-)
* [`getReleaseFromRegistry()`](#WithRegistry-getReleaseFromRegistry--)
#### [](#WithRegistry-onlyInstanceOperator--)
`onlyInstanceOperator()` modifier
#### [](#WithRegistry-onlyOracleService--)
`onlyOracleService()` modifier
#### [](#WithRegistry-onlyOracleOwner--)
`onlyOracleOwner()` modifier
#### [](#WithRegistry-onlyProductOwner--)
`onlyProductOwner()` modifier
#### [](#WithRegistry-constructor-address-)
`constructor(address _registry)` public
Constructor function that sets the address of the registry contract.
#### [](#WithRegistry-getContractFromRegistry-bytes32-)
`getContractFromRegistry(bytes32 _contractName) → address _addr` public
Returns the address of a contract registered in the registry by its name.
#### [](#WithRegistry-getContractInReleaseFromRegistry-bytes32-bytes32-)
`getContractInReleaseFromRegistry(bytes32 _release, bytes32 _contractName) → address _addr` internal
Returns the address of a contract with a given name in a specific release of the registry.
#### [](#WithRegistry-getReleaseFromRegistry--)
`getReleaseFromRegistry() → bytes32 _release` internal
Returns the current release identifier from the registry.
[← Services](/contracts/2.x/api/services)
[Test →](/contracts/2.x/api/test)
---
# Components - Etherisc Docs
Components
==========

[](#concept_of_components)
Concept of components
------------------------------------------------
Each GIF instance manages different components. A component is a specific smart contract with a certain core functionality. The components can represent different core objects.
The core objects are:
* Products
* Oracles
* Risk pools
All components and thus the objects they contain can assume identical states and have the same life cycle but can differ significantly in terms of lifespan.
[](#component_roles)
Component roles
------------------------------------
Two roles can determine the life cycle of a component.
### [](#component_owner)
Component owner
A Component owner can be an oracle owner, a product owner, or a risk pool keeper, depending on which core object he manages.
### [](#instance_operator)
Instance operator
The instance operator runs one or more GIF instances.
[](#lifecycle)
Lifecycle
------------------------

A component in the GIF is always in one of the following states:
* Created
* Proposed
* Declined
* Active
* Paused
* Suspended
* Archived
The transition between these states and roles is described in the above diagram. The lifecycle of a component starts with its development and deployment on the blockchain.
The component owner can implement their requirements in the smart contract or use generic GIF components.
In the next step, the component is registered, approved, and activated by the instance operator in the GIF instance. The instance operator can also decline a component.
In the event of approval, the instance operator continues to check the technical and procedural details. The instance operator can also outsource the verification to an independent audit.
_Another condition is that the component owner must contribute a certain amount of DIP token to be allowed to operate in the GIF instance._
If the component is active, it can be used until it is set to either suspended or paused. The difference between suspended and paused is that only the instance operator can suspend a component or resume it from suspended to active. The component owner can set a component to paused, and the component owner and the instance operator can unpause the component.
If the component is inactivated (pause, suspended) and not reactivated (resume, unpause), it is not deleted but archived.
For each component type (products, oracles, risk pools), we provide sample implementations that you can use as a starting point for your implementation.
[](#products)
Products
----------------------
A product is a specific smart contract that implements the functionality of this product. The product owner can implement its specific requirements, or he can use the generic functionality of the GIF.
After the product is technically developed and deployed to the blockchain, it must be registered in the GIF instance. This action is typically integrated with the deployment process.
The GIF instance offers the following functions to the product owner for this:
* ‘registerProduct’
After registering a product, it needs to be approved by the instance operator. The instance operator will check the details, such as that there is no malicious code in the product contract.
A possible and likely requirement is that the product owner stakes a certain amount of DIP token in a particular contract before actively selling products and earning money on the platform.
Approval is made by the instance operator using the function
* ‘approveProduct’
After approval of the product, the product is active and can start selling policies.
Should a change in terms imply a re-deployment of the product, the old product needs to be deactivated. For this, the GIF instance offers two functions:
* ‘pauseProduct’
* ‘unpauseProduct’
[](#oracles)
Oracles
--------------------
Oracles are vital to the GIF, as they link the blockchain-based smart contracts and the index/parameter information necessary to operate real-world insurance products.
Products can utilize product-specific oracles, but they can also use generic oracles, which can, in turn, be implemented by many different parties.
An oracle owner can propose oracles he would like to offer (in the case of the oracle owner) or use (in the case of the product owner). The instance operator checks the suggested oracles and activates them after successfully checking. The instance operator can deactivate or remove the oracle if necessary.
The following functions are available for oracles:
* proposeOracle (oracle owner)
* activateOracle (instance operator)
* deactivateOracle (instance operator)
* removeOracle (instance operator)
[](#risk_pools)
Risk Pools
--------------------------
The risk pools manage the individual risk bundles. The risk pool keeper can decide how many bundles may be present in the risk pool and how high the maximum volume of tokens may be. The risk pool keeper receives the risk pool NFT, which secures his ownership.
[← Roles](/gif/roles)
[Services →](/gif/services)
---
# Global Registry - Etherisc Docs
Global Registry
===============
The main objective of the global GIF registry is to provide a reliable information source to promote transparency, accountability and efficiency at the global level.

The global registry is a decentralized database in the form of a smart contract that serves as a comprehensive directory for certified GIF instances. It acts as a trusted source of information and provides a global registry that can be read by all interested worldwide. You can find the global registry on the Ethereum mainnet.
The GIF instances are multi-chain capable, so each chain has a chain net registry (for example, Polygon). When an instance operator installs a DIP instance on a chain, it registers itself on the chain net registry. The global registry managers check the instance for malware and fraud. After the check, the global registry manager adds the instance to the global registry on the Ethereum mainnet.
This procedure ensures that the instance is updated with the latest technology. The audited entity is trustworthy, which is advantageous to all parties involved and provides planning security.
Investors and risk pool keepers can invest their tokens and stablecoins in a secure environment.
Oracle owners and product owners are assured of an executable, secure and highly available framework. This provides planning security.
The customers have the security that the purchased policies will be paid out in the event of a loss.
[← Sandbox](/gif/sandbox)
[Data Model →](/gif/data-model)
---
# Overview - Etherisc Docs
Overview
========
For a concise overview of the basic concepts see here:
[Tutorial: Understanding the basic concepts of the GIF Framework.](../learn/basics-gif)
[](#architecture)
Architecture
------------------------------
[](_images/architecture.jpg)
[](#concepts)
Concepts
----------------------
### [](#components)
Components
A component is a specific smart contract with a particular core functionality.
A component can represent three different core objects:
* Products
* Oracle
* Risk pools
For each core object, we provide sample implementations that you can use as a baseline for your implementation.
The transition between these states and roles is described in the following diagram.

All components and thus the objects they contain can assume identical states and have the same life cycle but differ significantly in their lifetime.
States of a component:
* Created
* Proposed
* Declined
* Active
* Paused
* Suspended
* Archived
If the component is active, it can be used until it is set to either suspended or paused. The difference between suspended and paused is that only the instance operator can suspend a component or resume it from suspended to active. The component owner can set a component to paused, and the component owner and the instance operator can unpause the component.
If the component is inactivated (pause, suspended) and not reactivated (resume, unpause), it is not deleted but archived.
#### [](#lifecycle)
Lifecycle
The lifecycle of a component starts with its development and deployment in the blockchain.
You can implement your component requirements in the smart contract or use generic GIF components.
After that, the component is registered, approved, and activated by the instance operator in the GIF instance. Then the instance operator checks the technical and procedural details. The instance operator can also outsource the verification to an independent audit.
### [](#modules)
Modules
A module represents a group of smart contracts, each containing at least one storage and controller contract.
A storage contract acts as a database for the core objects. A controller contract includes an implementation that helps to manage core objects in a storage contract. In its turn, a storage contract delegates methods and makes calls to a controller contract, which modifies the state of a storage contract.
We provide you with four generic modules that map the standard processes of insurances or protections:
* policy module (manages applications, policies, claims, payouts, and metadata objects)
* registry module (registers sets of the core contracts used in a policy flow lifecycle in release groups)
* license module (manages products)
* query module (manages queries made to oracles and delivers responses from them)
### [](#services)
Services
We provide you with six services:
* InstanceOperatorService
* InstanceService
* OracleService
* ProductService
* RiskPoolService
* ComponentOwnerService
[](#coding_standards)
Coding Standards
--------------------------------------
### [](#error_handling)
Error handling
Each error message is assigned a unique number so that when an error message is received, we immediately know where the error occurred and can react quickly.
### [](#upgradability)
Upgradability
Once a smart contract is stored on the blockchain, it can no longer be changed.
The implementation (smart contract) upgradeability in Solidity is achieved by working with two corresponding smart contracts, the implementation and the proxy.
Each deployed smart contract has an address. The proxy has two main functions. The proxy has the information on which address/implementation it should access and the state of the implementation. So it manages all the data but doesn’t know what to do with it. The implementation processes the data and sends the result to the proxy.
If you now update an implementation, the updated implementation has a new address. This address is then communicated to the proxy.
[← Contents](/gif/)
[Core Contracts →](/gif/core-contracts)
---
# Sandbox - Etherisc Docs
Sandbox
=======
 [](https://opensource.org/licenses/Apache-2.0)
[](https://discord.gg/Qb6ZjgE8)
[](#fire_insurance_demo)
Fire Insurance Demo
--------------------------------------------
This repository holds the smart contracts for a demo fire insurance.
### [](#setup_requirements)
Setup Requirements
1. A running Docker installation
2. Developing with VS Code
3. Working with dev containers
Installing Docker on Windows is sometimes a struggle. Recommended Approach: Follow the installation instructions for [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
. Installing Docker on Linux or Mac should be straight forward.
### [](#interaction_via_command_line)
Interaction via Command Line
#### [](#running_unit_tests)
Running Unit Tests
brownie test -n 8
#### [](#deploy_and_verify_with_ganache)
Deploy and Verify with Ganache
brownie console
In the console use the following steps.
from scripts.deploy_fire import help
help()
The help command then shows an example session.
from scripts.deploy_fire import all_in_1, verify_deploy, create_bundle, create_policy, help
(customer, customer2, product, oracle, riskpool, riskpoolWallet, investor, usdc, instance, instanceService, instanceOperator, bundleId, processId, d) = all_in_1(deploy_all=True)
verify_deploy(d, usdc, product)
#### [](#deploy_to_differnt_network_with_existing_instance)
Deploy to differnt Network with existing Instance
As an example use the Ganache chain that runs in the background of this devcontainer setup.
brownie console --network=ganache
With an existing instance set parameter `deploy_all=False`. In this case the file `gif_instance_address.txt` needs to exist and contain the addresses of the instance registry. The file should be automatically created during the devconainer setup procedure of this repository.
from scripts.deploy_fire import all_in_1, verify_deploy, create_bundle, create_policy, help
(customer, customer2, product, oracle, riskpool, riskpoolWallet, investor, usdc, instance, instanceService, instanceOperator, bundleId, processId, d) = all_in_1(deploy_all=False)
verify_deploy(d, usdc, product)
[← Instances](/gif/instances)
[Global Registry →](/gif/global-registry)
---
# GIF Monitor - Etherisc Docs
GIF Monitor
===========
[](#overview)
Overview
----------------------
The GIF monitor now provides a structured overview of all generic building blocks available in the GIF framework for creating and operating an insurance product. It is subdivided into ‘Home,’ ‘Core,’ ‘Oracles,’ ‘Products’ and ‘Policies’ menu items. Drop-down menus take you to submenus and further down until to individual data fields and business transactions.
[](#how_it_works)
How it works
------------------------------
The GIF monitor provides all information transparently and in real-time online. The information is provided from the blockchain and GIF framework. Clicking on ‘Home,’ ‘Products,’ and Policies’ takes you to the relevant sections where you can view more information.
Under the menu items ‘Oracles,’ ‘Products,’ and ‘Policies’ are drop-down menus where you can access submenus and further on to the details.
If you click on ‘Core/GIF Instances,’ the GIF Monitor provides an Overview of deployed GIF Instances on the blockchains.
Under the ‘Oracles’ tab, the GIF monitor can view all available oracle types and oracles.
The ‘Products’ tab contains all products already available on the platform.
Under ‘Policies,’ you get access to all applications, policies, claims and payouts.
We integrated a search function in all areas where a search makes sense. You can return the overall view of the submenu from the search result by deleting the search term and searching again with no search term.
In the lower part of all areas, you can find the question, ‘What do you see here?’ Here we have a short description of all the information available in the area.

[](#menu_items)
Menu Items
--------------------------
The URL [https://gif-monitor.etherisc.com/](https://gif-monitor.etherisc.com/)
takes you to the ‘Home’ area of the GIF monitor. In the menu bar, you can choose from the menu items.
### [](#core)
Core
The ‘Core’ area is by far the most extensive. It displays the available GIF Instances, the GIF core contracts per instance and the events of these core contracts. The core area shows the complete core contracts that each user can use.
#### [](#gif_instances)
GIF Instances
Here you find the blockchains the instances use, such as xDai or Ethereum. GIF is multichain capable. You can compare an instance with a marketplace where product and oracle owners can register. The bigger the marketplace, the more attractive it becomes for all participants. It makes more sense to connect to an existing instance as a product owner or oracle owner than to run your own instance.
By clicking on an instance, you will get detailed information like the instance ID, name, name of the blockchain, chain ID and status (active or not). Each instance is identified by its registry address. You can compare this with the residents’ registration office.
#### [](#core_contracts)
Core Contracts
This section contains all 14 GIF core contracts. Each core contract provides essential functionality to a GIF instance.
You can click on the contract name for all GIF core contracts to get to the contract details. Here you will see on which instance you are, the instance ID, the address on the blockchain (and a link to the blockchain explorer blockscout.com), the name of the core contract, and the detailed contract functionality described by its contract application binary (ABI) interface.
For more information regarding the ABI check the Contract ABI specification Solidity interface. Further, the IPFS link details can be found in the chapter ‘Where do we store our source code?’ and the release status. You will return to the main menu by pressing the ‘OK’ button.
##### [](#in_each_gif_instance_the_following_core_contracts_are_available)
In each GIF instance, the following core contracts are available:
* Instance Operator Service
* Registry
* RegistryController
* License
* LicenseController
* Policy
* PolicyController
* Query
* QueryController
* ProductService
* OracleOwnerService
* OracleService
* PolicyFlowDefault
* Sandbox These core contracts can be divided into storage contracts, service contracts and PolicyFlow contracts.
#### [](#storage_contracts)
Storage contracts
Storage contracts store general and personal data. They also provide essential accessor functions. Storage contracts use the delegator pattern, meaning the on-chain contract data is separated from the contract functionality. This provides a way to upgrade the contract functionality without touching the contract data.
##### [](#in_each_gif_instance_the_following_storage_contracts_are_available)
In each GIF instance, the following storage contracts are available:
* Registry Contract
* Licence contract
* Query Contract
* Policy Contract
#### [](#service_contracts)
Service contracts
Service contracts provide functionalities that access and operate on data held in storage contracts.
##### [](#in_each_gif_instance_the_following_service_contracts_are_available)
In each GIF instance, the following service contracts are available:
* InstanceOperatorService
* ProductService
* OracleService
* OracleOwnerService
#### [](#policyflow_contracts)
PolicyFlow contracts
PolicyFlow contracts contain the business functionality of a classic insurance policy. Depending on the product, PolicyFlow contracts vary.
For example, one product may offer a renewal option and other products do not offer such an option and the contracts end automatically.
Currently, we support the PolicyFlowDefault workflow, which covers a very wide range of products.
* PolicyFlowDefault The blockchains the instances use, such as xDai or Ethereum. You can compare an instance with a marketplace where product and oracle owners can register. The bigger the marketplace, the more attractive it becomes for all participants. It makes more sense to connect to an existing instance as a product owner or oracle owner than to run your own instance.
#### [](#core_events)
Core Events
Here the contract events of the GIF core contracts are displayed. Smart contracts create contract events during code execution and are permanently stored on the chain. Events are primarily used to document significant changes in the data of smart contracts, for example, the change of status. Check the Solidity documentation for a more detailed description of events.
##### [](#events_used_in_the_gif_core_contracts)
Events used in the GIF core contracts
| | |
| --- | --- |
| License LogNewProduct | A new product is created |
| License LogProductSetApproved | A new product has been approved |
| License LogProductSetPaused | A product has been paused = temporarily deactivated |
| Policy LogApplicationStateChanged | An application has changed state, e.g. from ‘approved’ to ‘underwritten’ |
| Policy LogNewApplication | A new application has been registered |
| Policy LogNewPolicy | A new policy has been created |
| Query LogOracleActivated | An oracle has been activated |
| Query LogOracleAssignedToOracleType | An oracle has been assigned to an oracle type |
| Query LogOracleProposed | A new oracle has been proposed |
| Query LogOracleProposedToOracleType | An oracle has been proposed to an oracle type |
| Query LogOracleResponded | An oracle has responded to a request |
| Query LogOracleTypeActivated | An oracle type has been activated |
| Query LogOracleTypeProposed | a new oracle type has been proposed |
| Registry LogContractRegistered | A core contract has been registered in the registry |
### [](#oracles)
Oracles
The ‘Oracle’ area of the GIF monitor displays available oracles.
#### [](#oracles_2)
Oracles
You will find all oracles available on the platform in the ‘Oracles dialogue.’ Here you can view all input and callback formats as a product owner. In addition, the appropriate oracle can be requested from the Oracle owners.
By clicking on an oracle, the ID, the description, the oracle contract, the oracle owner and the active oracle types are displayed in the details.
### [](#products)
Products
In the ‘Products area,’ all the framework’s products are listed. By clicking on a product, the details are displayed. These are the name, the product ID, the owner, the address, which policy flow is used, the release and the status.
### [](#policies)
Policies
In the ‘Policies’ area, you can find information on every phase of the life cycle of a policy. It starts with information about the product, metadata, application, policy, claim and payout. Depending on the policy’s life cycle, more or fewer information blocks are displayed.

You can find information on which product the insured person has taken out containing the name, the product ID, the status, the release status, which PolicyFlow contract, the address of the owner and the policy address. The addresses are stored with links to blockscout.com.

For each request and policy, a business process is triggered that collects data needed for all phases of a policy. From the customer’s application to underwriting, claims processing and payout. The data that is required for all phases of a policy is called metadata.
You get an overview of the policy. When created and updated, the BP key (created by the owner. GIF only checks that the BPKey is unique) has a policy, an application, and how many claims and payouts.

The first step in concluding a policy is the customer’s application. The client wants the insurance company to underwrite a risk against a premium payment. The application contains all the information for the underwriter. The underwriter checks the application, accepts it, or declines it. Possible application states are ‘Applied,’ ‘Revoked,’ ‘Underwritten,’ and ‘Declined.’ In this block, you find information when created, when updated, the state and the data (hashed data that can only be used by the person who created the data set).

If the underwriter accepts an application, it converts into a policy. The policies are either active or expired. If the policy is expired, no claims can be made.

The insured event has occurred and the policyholder assures the claims to him. The claim has thus been created. Possible claim states are ‘Applied,’ ‘Confirmed,’ ‘Declined’ and ‘Payout.’

In the traditional insurance world, an insurance company employee or a complete specialist department decides whether the guaranteed sum is paid out. In the blockchain world, a smart contract decides and triggers the payout. One of two possible payout states is displayed: ‘Expected’ and ‘PaidOut.’
### [](#where_do_we_store_our_source_code)
Where do we store our source code?
The source code of the core contracts is stored using the Interplanetary File System Protocol (IPFS), a decentralized file-sharing platform. The IPFS provides a protocol and naming network for storing and sharing data. The content does the address of the content. So independent of where data is stored, it always has the same address. You can find the IPFS link in the details of each core contract.
[← Governance](/gif/governance-model)
---
# Roles - Etherisc Docs
Roles
=====

[](#instance_operator)
Instance Operator
----------------------------------------
Designs and runs one or more GIF frameworks, which is a collection of open-source smart contracts. Any complete deployment of this framework is called a ‘GIF instance.’
There will always be at least one complete instance of the GIF, which is operated by the Etherisc project, but in principle, anybody can deploy a new GIF instance.
The key responsibilities of the instance operator are the administration of products and oracles (as introduced above) and a few other basic actions.
Any GIF instance is multi-client capable, which means that any number of product owners and oracle providers can be operated and administered on one GIF instance. Due to the different legal regulations for insurance worldwide, different GIF instances and several instance operators are required.
[](#product_owner)
Product Owner
--------------------------------
The product owner designs and operates one or more products. This would be an insurance company or an MGA (managing general agent) in the traditional insurance industry. Due to the multi-client capability, a product owner can use all oracles located on the respective platform by the oracle owners.
[](#oracle_owner)
Oracle Owner
------------------------------
The oracle owner provides oracles that interface between the blockchain smart contracts and external data sources.
For example, in the case of flight delay insurance, the oracle informs the smart contract whether the flight landed in time, how much it was delayed, or if the airline ultimately canceled it.
For weather index insurance, on the other hand, an oracle could provide historical and real-time weather data like rainfall and wind speed.
[](#risk_pool_keeper)
Risk Pool Keeper
--------------------------------------
A risk pool keeper manages one or more risk pools. A risk pool is a smart contract that assigns (‘pools’) several risks, represented by policy objects, to risk capital.
Risk pools can collect collateral that risk investors invest in. They allocate DIP tokens and stablecoins in the risk pool and receive a reward for binding their assets. Losses are paid from the risk pool. Investors can top up their risk pool investments and withdraw their funds.
DIP tokens are used to link access to risk pools to investors who have also invested in the platform represented by this GIF instance.
[](#insured)
Insured
--------------------
The Insured is the policyholder who wants to pass his risk to the risk pools. He is a customer of the insurance company.
[](#investor)
Investor
----------------------
Investors are interested in participating in risk pools to balance/diversify their risk portfolios. Investors provide collateral for risk pools in exchange for interest payments.
[← Data Model](/gif/data-model)
[Components →](/gif/components)
---
# Instances - Etherisc Docs
Instances
=========
[](#what_is_a_gif_instance)
What is a GIF Instance?
---------------------------------------------------
A GIF (Generic Insurance Framework) instance is an autonomous, fully functional framework running on a blockchain. An instance operator operates the instance. This can be a natural person, a multisig or a DAO.
You can compare the GIF instance to a marketplace where players offer different products. The larger the marketplace is, the more attractive it becomes. Because of the large offer, more customers come to the market.
So it can be a good idea to join an existing instance as a product owner.
### [](#technical_role_concept)
Technical role concept
GIF has implemented a role model. Each role can implement specific processes.
#### [](#instance_operator)
Instance operator
The instance operator operates the platform, i.e., the framework. The instance operator administers the product owners and the oracle providers. GIF is multi-client capable, meaning that any number of product owners and oracle providers can be operated and administered on one platform. Due to different legal regulations, several instance operators are required.
#### [](#risk_pool_keeper)
Risk pool keeper
A risk pool keeper manages one or more risk pools. A risk pool is a smart contract that “pools” several risks, represented by policy objects, to risk capital. Risk pools collect collateral that investors invest in.
#### [](#oracle_owner)
Oracle owner
The Oracle-owner provides oracles. Oracles provide the interface between blockchain smart contracts and the external internet with data. For example, in the case of flight delay insurance, an oracle informs the smart contract whether the flight took off on time, how much it was delayed, or was canceled entirely.
#### [](#product_owner)
Product owner
The product owner designs and operates one or more products. In the classic sense, this would be an insurance company.
[](#what_is_gif)
What is GIF?
-----------------------------
The Generic Insurance Framework consists at its core of a system of smart contracts that implement essential functions of the lifecycle of an insurance policy. GIF thus enables the modeling of a wide variety of insurance types.
It is a basic implementation that can be used to create blockchain-based applications, in this case, insurance.
To be able to design insurance products quickly and easily, processing steps that run the same in all products have been identified and already implemented. Thus, only specifications such as pricing etc., need to be adapted.
GIF provides these generic functions for all sub-steps in the lifecycle of an insurance policy and thus enables an automated workflow that controls the sequence of processing steps.
### [](#generic_lifecycle_functions_in_gif)
Generic lifecycle functions in GIF
* \_register (each product has to be registered to get access to the GIF functionality)
* \_newApplication (to generate and save a new application from a customer)
* \_underwrite (to sign an application and create a new policy)
* \_decline (to reject an application)
* \_newClaim (to generate and store a new claim in case of a claim)
* \_confirmClaim (to confirm a claim and create a payout)
* \_declineClaim (to reject a claim)
* \_payout (to confirm and initiate a payout)
* \_request (to request data or actions from Oracle)
* \_createRole (to create roles for actors)
* \_addRoleToAccount (to assign roles to actors)
[](#instances_operated_by_the_etherisc_project)
Instances operated by the Etherisc Project
------------------------------------------------------------------------------------------

The GIF instances are multi-chain ready for every blockchain that consists of two layers (consensus and execution layer). GIF instances only use the execution layer so we are independent of the consensus layer and therefore independent of the blockchain.
Currently, 4 GIF instances are productive:
* Ethereum Mainnet: Depeg USDC Protection, USDT and DIP token staking
* Avalanche: Lemonade Crypto Climate Coalition
* Gnosis chain (xDai): Etherisc Flight Delay, Acre Africa
* Polygon: Etherisc Train Delay / CSI Project
Testnet-Deployments:
* Mumbai: Etherisc Train Delay, VCM (Verity Care Management)
* Görli: Depeg USDC Protection, USDT and DIP token staking
* Gnosis chain (xDai) testnet: Etherisc flight delay
* Fuji / Avalanche testnet: Lemonade Crypto Climate Coalition
* Alfajores Celo: Acre Africa soil moisture
Please contact us if you want to use any of our GIF instances on Gnosis (xDai), Polygon, Avalanche or Binance Smart Chain. We are curious about your plans and are happy to assist and support you.
[← Core Contracts](/gif/core-contracts)
[Sandbox →](/gif/sandbox)
---
# Data Model - Etherisc Docs
Data Model
==========
[](#overview)
Overview
----------------------
Here you get an overview of the individual data models. The individual sections represent the complete process of creating a policy up to the termination, either by a claim and the payout or the end without a claim in chronological order.
Here the complete process:
* the customer inquires (application) about an insurance policy. By taking out the insurance policy, one wants to protect themself against a specific risk.
* the insurance company examines the customer’s application.
* the application is accepted or rejected.
* in case of rejection, the customer is informed and no further activities occur.
* in case of acceptance, the contract comes to the “underwriter.” The acceptance of the application is called “underwriting.”
* the insurance company commits itself to the “underwriting” to take over the customer’s risk and transfer it to itself. It further undertakes to cover the loss if the insured event occurs.
* the customer, for his part, undertakes to pay the premium.
* both declarations of obligation are documented in a contract. This contract is called the insurance policy.
* if a claim occurs, the customer reports it to the insurance company.
* the claim is checked by the insurance company and accepted or rejected.
* in case of acceptance, the agreed insurance sum is paid out (payout).
[](#metadata)
Metadata
----------------------
Metadata or metainformation refers to structured data containing information about other resources. Metadata thus describes the actual data in a way. Metainformation becomes necessary when there are more significant amounts of data to manage.

* the address of the owner of the smart contract
* the product ID
* state of the policy flow module
* data
* the date of creation
When a new policy is created, metadata is entered first, i.e., before the application, it is determined who is the policy’s owner (owner), to which product the policy belongs (productID) and a process ID is generated.
The process in Metadata, Application and Policy is linked to unique unique process ID, so you can tell exactly which steps have been completed.
[](#applications)
Applications
------------------------------

The application then specifies the insurance sum (sumInsuredAmount) and what amount of premium (premiumAmount) must be paid. Additional information is also entered to determine the insurance premium depending on the insurance type (data).
When the application is 'underwritten,' the insurance sum is reserved in the risk pool and the policy is generated.
States of the application:
* applied
* revoked
* underwritten
* declined
[](#policies)
Policies
----------------------

The policy will then log how much premium you have already paid (premiumPaidAmount) and the total premium (premiumExpectedAmount). Here you will also find the outstanding claims (openClaimsCount) and the claims already paid out (claimsCount). The policy can be closed when no more open claims exist or the policy has expired.
Further information is the maximum amount of the payout (payoutMaxAmount) and how much has already been paid out (payoutAmount).
States of the policy:
* active
* expired
* closed
[](#claims)
Claims
------------------

In the claim smart contracts, you can look up how much the policy owner has claimed (claimAmount) and how much has been paid out (paidAmount). If the two amounts match or the claim is declined, the claim can be closed.
Claims can only be created if the policy has the ‘active status.’
States of the claim:
* applied
* confirmed
* declined
* closed
[](#payouts)
Payouts
--------------------

Each planned payout has a certain amount. With each payout, the claim amount increases. Only when the planned payouts have been paid out the claimed amount decreases and the paid amount increases. When the claim amount is equal to the paid amount, the claim can be closed.
States of the payout:
* expected
* paid out
[](#oracle_request)
Oracle Request
----------------------------------
Here is defined which oracle is requested and the time intervals the request takes place.
With our depeg app, Chainlink already provides us with the USDC rates on-chain.
[](#bundles)
Bundles
--------------------

Everybody who wants to provide risk capital creates his risk bundle by staking USDT stablecoins in the [Etherisc Depeg Protection web app](https://depeg.etherisc.com/stake)
. In your risk bundle, you can set parameters like lifetime, minimum or maximum staked amount.
Each risk bundle has its own NFT (ERC721).
You can find detailed information in the [Depeg Protection Tutorial](https://docs.etherisc.com/learn/depeg-purchase)
and the [Depeg Protection FAQ’s](https://docs.etherisc.com/learn/depeg-faq)
.
States of the bundle:
* active
* locked
* closed
* burned
[](#risk_pools)
Risk Pools
--------------------------

The risk pool bundles and manages the individual risk bundles. The risk pool provider defines the general conditions, such as the maximum total sum insured or the collateralization level.
The risk pool has a unique ID and wallet in which the assets are managed. The risk pool can also issue its own risk pool token (ERC20), which can then be traded. The risk pool keeper can define how much must be deposited for collateral damage (collateralizatoinlevel1) and the maximum amount to which policies can be issued (sumOfSumInsuredCap).
The risk pool shows the aggregate sum insured of all existing policies (sumOfSumInsuredAtRisk), the balance (capital), the capital locked up in policies that have been completed but have yet to expire (lockedCapital), the total amount of funds (balance), when the risk pool was created (createdAt) and the date of the last update (updatedAt).
[← Global Registry](/gif/global-registry)
[Roles →](/gif/roles)
---
# Services - Etherisc Docs
Services
========
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/services](https://docs.etherisc.com/contracts/api/services) |
[](#contracts)
Contracts
------------------------
### [](#ComponentOwnerService)
`ComponentOwnerService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/ComponentOwnerService.sol)
import "@etherisc/gif-contracts/contracts/services/ComponentOwnerService.sol";
Modifiers
* [`onlyOwnerWithRoleFromComponent(component)`](#ComponentOwnerService-onlyOwnerWithRoleFromComponent-contract-IComponent-)
* [`onlyOwnerWithRole(id)`](#ComponentOwnerService-onlyOwnerWithRole-uint256-)
Functions
* [`_afterInitialize()`](#ComponentOwnerService-_afterInitialize--)
* [`propose(component)`](#ComponentOwnerService-propose-contract-IComponent-)
* [`stake(id)`](#ComponentOwnerService-stake-uint256-)
* [`withdraw(id)`](#ComponentOwnerService-withdraw-uint256-)
* [`pause(id)`](#ComponentOwnerService-pause-uint256-)
* [`unpause(id)`](#ComponentOwnerService-unpause-uint256-)
* [`archive(id)`](#ComponentOwnerService-archive-uint256-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#ComponentOwnerService-onlyOwnerWithRoleFromComponent-contract-IComponent-)
`onlyOwnerWithRoleFromComponent(contract IComponent component)` modifier
#### [](#ComponentOwnerService-onlyOwnerWithRole-uint256-)
`onlyOwnerWithRole(uint256 id)` modifier
#### [](#ComponentOwnerService-_afterInitialize--)
`_afterInitialize()` internal
This function is called after the contract is initialized and can only be called once. It sets the component controller contract address.
#### [](#ComponentOwnerService-propose-contract-IComponent-)
`propose(contract IComponent component)` external
Propose a new component to be added to the system.
#### [](#ComponentOwnerService-stake-uint256-)
`stake(uint256 id)` external
Stake function allows the owner to stake a specific id.
#### [](#ComponentOwnerService-withdraw-uint256-)
`withdraw(uint256 id)` external
Allows the owner to withdraw a specific asset by its ID.
#### [](#ComponentOwnerService-pause-uint256-)
`pause(uint256 id)` external
Pauses a specific component with the given ID.
#### [](#ComponentOwnerService-unpause-uint256-)
`unpause(uint256 id)` external
Unpauses a component with the specified ID.
#### [](#ComponentOwnerService-archive-uint256-)
`archive(uint256 id)` external
Archives a component with the given ID from the component owner’s inventory.
### [](#InstanceOperatorService)
`InstanceOperatorService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/InstanceOperatorService.sol)
import "@etherisc/gif-contracts/contracts/services/InstanceOperatorService.sol";
Modifiers
* [`onlyInstanceOperatorAddress()`](#InstanceOperatorService-onlyInstanceOperatorAddress--)
Functions
* [`_afterInitialize()`](#InstanceOperatorService-_afterInitialize--)
* [`prepareRelease(_newRelease)`](#InstanceOperatorService-prepareRelease-bytes32-)
* [`register(_contractName, _contractAddress)`](#InstanceOperatorService-register-bytes32-address-)
* [`deregister(_contractName)`](#InstanceOperatorService-deregister-bytes32-)
* [`registerInRelease(_release, _contractName, _contractAddress)`](#InstanceOperatorService-registerInRelease-bytes32-bytes32-address-)
* [`deregisterInRelease(_release, _contractName)`](#InstanceOperatorService-deregisterInRelease-bytes32-bytes32-)
* [`createRole(_role)`](#InstanceOperatorService-createRole-bytes32-)
* [`invalidateRole(_role)`](#InstanceOperatorService-invalidateRole-bytes32-)
* [`grantRole(role, principal)`](#InstanceOperatorService-grantRole-bytes32-address-)
* [`revokeRole(role, principal)`](#InstanceOperatorService-revokeRole-bytes32-address-)
* [`approve(id)`](#InstanceOperatorService-approve-uint256-)
* [`decline(id)`](#InstanceOperatorService-decline-uint256-)
* [`suspend(id)`](#InstanceOperatorService-suspend-uint256-)
* [`resume(id)`](#InstanceOperatorService-resume-uint256-)
* [`archive(id)`](#InstanceOperatorService-archive-uint256-)
* [`setDefaultStaking(componentType, data)`](#InstanceOperatorService-setDefaultStaking-uint16-bytes-)
* [`adjustStakingRequirements(id, data)`](#InstanceOperatorService-adjustStakingRequirements-uint256-bytes-)
* [`suspendTreasury()`](#InstanceOperatorService-suspendTreasury--)
* [`resumeTreasury()`](#InstanceOperatorService-resumeTreasury--)
* [`setInstanceWallet(walletAddress)`](#InstanceOperatorService-setInstanceWallet-address-)
* [`setRiskpoolWallet(riskpoolId, riskpoolWalletAddress)`](#InstanceOperatorService-setRiskpoolWallet-uint256-address-)
* [`setProductToken(productId, erc20Address)`](#InstanceOperatorService-setProductToken-uint256-address-)
* [`createFeeSpecification(componentId, fixedFee, fractionalFee, feeCalculationData)`](#InstanceOperatorService-createFeeSpecification-uint256-uint256-uint256-bytes-)
* [`setPremiumFees(feeSpec)`](#InstanceOperatorService-setPremiumFees-struct-ITreasury-FeeSpecification-)
* [`setCapitalFees(feeSpec)`](#InstanceOperatorService-setCapitalFees-struct-ITreasury-FeeSpecification-)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#InstanceOperatorService-onlyInstanceOperatorAddress--)
`onlyInstanceOperatorAddress()` modifier
#### [](#InstanceOperatorService-_afterInitialize--)
`_afterInitialize()` internal
Performs the necessary setup after contract initialization. - Sets the component, pool, and treasury contracts. - Transfers ownership to the message sender. - Links the bundle module to the bundle token. - Sets the default admin role.
#### [](#InstanceOperatorService-prepareRelease-bytes32-)
`prepareRelease(bytes32 _newRelease)` external
Prepares a new release by calling the prepareRelease function from the Registry contract.
#### [](#InstanceOperatorService-register-bytes32-address-)
`register(bytes32 _contractName, address _contractAddress)` external
Registers a contract in the registry.
#### [](#InstanceOperatorService-deregister-bytes32-)
`deregister(bytes32 _contractName)` external
Deregisters a contract from the registry.
#### [](#InstanceOperatorService-registerInRelease-bytes32-bytes32-address-)
`registerInRelease(bytes32 _release, bytes32 _contractName, address _contractAddress)` external
Registers a contract in a specific release.
#### [](#InstanceOperatorService-deregisterInRelease-bytes32-bytes32-)
`deregisterInRelease(bytes32 _release, bytes32 _contractName)` external
Deregisters a contract from a specific release in the registry.
#### [](#InstanceOperatorService-createRole-bytes32-)
`createRole(bytes32 _role)` external
Adds a new role to the access control contract.
#### [](#InstanceOperatorService-invalidateRole-bytes32-)
`invalidateRole(bytes32 _role)` external
Invalidates a role.
#### [](#InstanceOperatorService-grantRole-bytes32-address-)
`grantRole(bytes32 role, address principal)` external
Grants a role to a principal.
#### [](#InstanceOperatorService-revokeRole-bytes32-address-)
`revokeRole(bytes32 role, address principal)` external
Revokes a role from a principal.
#### [](#InstanceOperatorService-approve-uint256-)
`approve(uint256 id)` external
Approves a component with the given ID and sets its corresponding riskpool ID in the pool contract.
#### [](#InstanceOperatorService-decline-uint256-)
`decline(uint256 id)` external
Declines a component with the specified ID.
#### [](#InstanceOperatorService-suspend-uint256-)
`suspend(uint256 id)` external
Suspends the component with the given ID.
#### [](#InstanceOperatorService-resume-uint256-)
`resume(uint256 id)` external
Resumes the execution of a paused component instance.
#### [](#InstanceOperatorService-archive-uint256-)
`archive(uint256 id)` external
Archives a component with the given ID from the instance operator’s address.
#### [](#InstanceOperatorService-setDefaultStaking-uint16-bytes-)
`setDefaultStaking(uint16 componentType, bytes data)` external
Sets the default staking for a specific component type.
#### [](#InstanceOperatorService-adjustStakingRequirements-uint256-bytes-)
`adjustStakingRequirements(uint256 id, bytes data)` external
Adjusts the staking requirements for a specific instance operator by providing the operator ID and the new staking requirements.
#### [](#InstanceOperatorService-suspendTreasury--)
`suspendTreasury()` external
Suspends the treasury functionality.
#### [](#InstanceOperatorService-resumeTreasury--)
`resumeTreasury()` external
Resumes the treasury contract.
#### [](#InstanceOperatorService-setInstanceWallet-address-)
`setInstanceWallet(address walletAddress)` external
Sets the wallet address of the instance operator.
#### [](#InstanceOperatorService-setRiskpoolWallet-uint256-address-)
`setRiskpoolWallet(uint256 riskpoolId, address riskpoolWalletAddress)` external
Sets the wallet address for a specific risk pool.
#### [](#InstanceOperatorService-setProductToken-uint256-address-)
`setProductToken(uint256 productId, address erc20Address)` external
Sets the ERC20 token address for a given product ID.
#### [](#InstanceOperatorService-createFeeSpecification-uint256-uint256-uint256-bytes-)
`createFeeSpecification(uint256 componentId, uint256 fixedFee, uint256 fractionalFee, bytes feeCalculationData) → struct ITreasury.FeeSpecification` external
Returns a FeeSpecification object created with the given parameters.
#### [](#InstanceOperatorService-setPremiumFees-struct-ITreasury-FeeSpecification-)
`setPremiumFees(struct ITreasury.FeeSpecification feeSpec)` external
Sets the premium fees for the treasury.
#### [](#InstanceOperatorService-setCapitalFees-struct-ITreasury-FeeSpecification-)
`setCapitalFees(struct ITreasury.FeeSpecification feeSpec)` external
Sets the fee specification for capital fees in the treasury contract.
### [](#InstanceService)
`InstanceService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/InstanceService.sol)
import "@etherisc/gif-contracts/contracts/services/InstanceService.sol";
Functions
* [`_afterInitialize()`](#InstanceService-_afterInitialize--)
* [`_setChainNames()`](#InstanceService-_setChainNames--)
* [`getChainId()`](#InstanceService-getChainId--)
* [`getChainName()`](#InstanceService-getChainName--)
* [`getInstanceId()`](#InstanceService-getInstanceId--)
* [`getInstanceOperator()`](#InstanceService-getInstanceOperator--)
* [`getComponentOwnerService()`](#InstanceService-getComponentOwnerService--)
* [`getInstanceOperatorService()`](#InstanceService-getInstanceOperatorService--)
* [`getOracleService()`](#InstanceService-getOracleService--)
* [`getProductService()`](#InstanceService-getProductService--)
* [`getRiskpoolService()`](#InstanceService-getRiskpoolService--)
* [`getRegistry()`](#InstanceService-getRegistry--)
* [`contracts()`](#InstanceService-contracts--)
* [`contractName(idx)`](#InstanceService-contractName-uint256-)
* [`getDefaultAdminRole()`](#InstanceService-getDefaultAdminRole--)
* [`getProductOwnerRole()`](#InstanceService-getProductOwnerRole--)
* [`getOracleProviderRole()`](#InstanceService-getOracleProviderRole--)
* [`getRiskpoolKeeperRole()`](#InstanceService-getRiskpoolKeeperRole--)
* [`hasRole(role, principal)`](#InstanceService-hasRole-bytes32-address-)
* [`products()`](#InstanceService-products--)
* [`oracles()`](#InstanceService-oracles--)
* [`riskpools()`](#InstanceService-riskpools--)
* [`getComponentId(componentAddress)`](#InstanceService-getComponentId-address-)
* [`getComponentType(componentId)`](#InstanceService-getComponentType-uint256-)
* [`getComponentState(componentId)`](#InstanceService-getComponentState-uint256-)
* [`getComponent(id)`](#InstanceService-getComponent-uint256-)
* [`getOracleId(idx)`](#InstanceService-getOracleId-uint256-)
* [`getRiskpoolId(idx)`](#InstanceService-getRiskpoolId-uint256-)
* [`getProductId(idx)`](#InstanceService-getProductId-uint256-)
* [`getStakingRequirements(id)`](#InstanceService-getStakingRequirements-uint256-)
* [`getStakedAssets(id)`](#InstanceService-getStakedAssets-uint256-)
* [`processIds()`](#InstanceService-processIds--)
* [`getMetadata(bpKey)`](#InstanceService-getMetadata-bytes32-)
* [`getApplication(processId)`](#InstanceService-getApplication-bytes32-)
* [`getPolicy(processId)`](#InstanceService-getPolicy-bytes32-)
* [`claims(processId)`](#InstanceService-claims-bytes32-)
* [`payouts(processId)`](#InstanceService-payouts-bytes32-)
* [`getClaim(processId, claimId)`](#InstanceService-getClaim-bytes32-uint256-)
* [`getPayout(processId, payoutId)`](#InstanceService-getPayout-bytes32-uint256-)
* [`getRiskpool(riskpoolId)`](#InstanceService-getRiskpool-uint256-)
* [`getFullCollateralizationLevel()`](#InstanceService-getFullCollateralizationLevel--)
* [`getCapital(riskpoolId)`](#InstanceService-getCapital-uint256-)
* [`getTotalValueLocked(riskpoolId)`](#InstanceService-getTotalValueLocked-uint256-)
* [`getCapacity(riskpoolId)`](#InstanceService-getCapacity-uint256-)
* [`getBalance(riskpoolId)`](#InstanceService-getBalance-uint256-)
* [`activeBundles(riskpoolId)`](#InstanceService-activeBundles-uint256-)
* [`getActiveBundleId(riskpoolId, bundleIdx)`](#InstanceService-getActiveBundleId-uint256-uint256-)
* [`getMaximumNumberOfActiveBundles(riskpoolId)`](#InstanceService-getMaximumNumberOfActiveBundles-uint256-)
* [`getBundleToken()`](#InstanceService-getBundleToken--)
* [`getBundle(bundleId)`](#InstanceService-getBundle-uint256-)
* [`bundles()`](#InstanceService-bundles--)
* [`unburntBundles(riskpoolId)`](#InstanceService-unburntBundles-uint256-)
* [`getTreasuryAddress()`](#InstanceService-getTreasuryAddress--)
* [`getInstanceWallet()`](#InstanceService-getInstanceWallet--)
* [`getRiskpoolWallet(riskpoolId)`](#InstanceService-getRiskpoolWallet-uint256-)
* [`getComponentToken(componentId)`](#InstanceService-getComponentToken-uint256-)
* [`getFeeFractionFullUnit()`](#InstanceService-getFeeFractionFullUnit--)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#InstanceService-_afterInitialize--)
`_afterInitialize()` internal
Internal function that is called after initialization is complete. It sets the bundle, component, policy, pool, and treasury controllers by retrieving their contract addresses. It also sets the chain names.
#### [](#InstanceService-_setChainNames--)
`_setChainNames()` internal
Sets the names for several blockchain networks by assigning them to their respective chain IDs.
Sets the names for the Ethereum Mainnet/ETH, Goerli/ETH, Ganache, Gnosis/xDai, Sokol/SPOA, Polygon Mainnet/MATIC, Mumbai/MATIC, Avalanche C-Chain/AVAX and Avalanche Fuji Testnet/AVAX blockchain networks by assigning them to their respective chain IDs.
#### [](#InstanceService-getChainId--)
`getChainId() → uint256 chainId` public
Returns the chain ID of the current blockchain.
#### [](#InstanceService-getChainName--)
`getChainName() → string chainName` public
Returns the name of the chain based on its ID.
#### [](#InstanceService-getInstanceId--)
`getInstanceId() → bytes32 instanceId` public
Returns the instance ID of the contract, which is a hash of the chain ID and the registry address.
#### [](#InstanceService-getInstanceOperator--)
`getInstanceOperator() → address` external
Returns the address of the current instance operator.
#### [](#InstanceService-getComponentOwnerService--)
`getComponentOwnerService() → contract IComponentOwnerService service` external
Returns the address of the Component Owner Service contract.
#### [](#InstanceService-getInstanceOperatorService--)
`getInstanceOperatorService() → contract IInstanceOperatorService service` external
Returns the instance operator service contract address.
#### [](#InstanceService-getOracleService--)
`getOracleService() → contract IOracleService service` external
Returns the Oracle Service contract instance.
#### [](#InstanceService-getProductService--)
`getProductService() → contract IProductService service` external
Returns the address of the Product Service contract.
#### [](#InstanceService-getRiskpoolService--)
`getRiskpoolService() → contract IRiskpoolService service` external
Returns the IRiskpoolService contract instance.
#### [](#InstanceService-getRegistry--)
`getRegistry() → contract IRegistry service` external
Returns the current instance of the IRegistry contract.
#### [](#InstanceService-contracts--)
`contracts() → uint256 numberOfContracts` external
Returns the number of contracts registered in the registry.
#### [](#InstanceService-contractName-uint256-)
`contractName(uint256 idx) → bytes32 name` external
Returns the name of the contract at the specified index in the registry.
#### [](#InstanceService-getDefaultAdminRole--)
`getDefaultAdminRole() → bytes32` external
Returns the default admin role for the AccessControl contract.
#### [](#InstanceService-getProductOwnerRole--)
`getProductOwnerRole() → bytes32` external
Returns the role identifier of the product owner role.
#### [](#InstanceService-getOracleProviderRole--)
`getOracleProviderRole() → bytes32` external
Returns the role identifier for the oracle provider role.
#### [](#InstanceService-getRiskpoolKeeperRole--)
`getRiskpoolKeeperRole() → bytes32` external
Returns the role identifier for the Riskpool Keeper role.
#### [](#InstanceService-hasRole-bytes32-address-)
`hasRole(bytes32 role, address principal) → bool` external
Checks if an address has a specific role.
#### [](#InstanceService-products--)
`products() → uint256` external
Returns the number of products in the component contract.
#### [](#InstanceService-oracles--)
`oracles() → uint256` external
Returns the number of oracles registered in the component.
#### [](#InstanceService-riskpools--)
`riskpools() → uint256` external
Returns the number of risk pools in the component.
#### [](#InstanceService-getComponentId-address-)
`getComponentId(address componentAddress) → uint256 componentId` external
Returns the component ID of a given component address.
#### [](#InstanceService-getComponentType-uint256-)
`getComponentType(uint256 componentId) → enum IComponent.ComponentType componentType` external
Returns the type of a component given its ID.
#### [](#InstanceService-getComponentState-uint256-)
`getComponentState(uint256 componentId) → enum IComponent.ComponentState componentState` external
Returns the current state of a specific component.
#### [](#InstanceService-getComponent-uint256-)
`getComponent(uint256 id) → contract IComponent` external
Returns the component with the specified ID.
#### [](#InstanceService-getOracleId-uint256-)
`getOracleId(uint256 idx) → uint256 oracleId` public
Returns the oracle ID at the specified index.
#### [](#InstanceService-getRiskpoolId-uint256-)
`getRiskpoolId(uint256 idx) → uint256 riskpoolId` public
Returns the riskpool ID for the given index.
#### [](#InstanceService-getProductId-uint256-)
`getProductId(uint256 idx) → uint256 productId` public
Returns the product ID of the component at the given index.
#### [](#InstanceService-getStakingRequirements-uint256-)
`getStakingRequirements(uint256 id) → bytes data` external
Returns the staking requirements for a specific ID.
#### [](#InstanceService-getStakedAssets-uint256-)
`getStakedAssets(uint256 id) → bytes data` external
Returns the staked assets for a given ID.
#### [](#InstanceService-processIds--)
`processIds() → uint256 numberOfProcessIds` external
Returns the number of process IDs in the policy contract.
#### [](#InstanceService-getMetadata-bytes32-)
`getMetadata(bytes32 bpKey) → struct IPolicy.Metadata metadata` external
Returns the metadata associated with a given business process key.
#### [](#InstanceService-getApplication-bytes32-)
`getApplication(bytes32 processId) → struct IPolicy.Application application` external
Returns the application data associated with the given process ID.
#### [](#InstanceService-getPolicy-bytes32-)
`getPolicy(bytes32 processId) → struct IPolicy.Policy policy` external
Returns the policy associated with the given process ID.
#### [](#InstanceService-claims-bytes32-)
`claims(bytes32 processId) → uint256 numberOfClaims` external
Returns the number of claims associated with a given process ID.
#### [](#InstanceService-payouts-bytes32-)
`payouts(bytes32 processId) → uint256 numberOfPayouts` external
Returns the number of payouts for a given processId.
#### [](#InstanceService-getClaim-bytes32-uint256-)
`getClaim(bytes32 processId, uint256 claimId) → struct IPolicy.Claim claim` external
Returns the claim with the given claimId for the specified processId.
#### [](#InstanceService-getPayout-bytes32-uint256-)
`getPayout(bytes32 processId, uint256 payoutId) → struct IPolicy.Payout payout` external
Returns the information of a specific payout.
#### [](#InstanceService-getRiskpool-uint256-)
`getRiskpool(uint256 riskpoolId) → struct IPool.Pool riskPool` external
Returns the risk pool with the given ID.
#### [](#InstanceService-getFullCollateralizationLevel--)
`getFullCollateralizationLevel() → uint256` external
Returns the full collateralization level of the pool.
#### [](#InstanceService-getCapital-uint256-)
`getCapital(uint256 riskpoolId) → uint256 capitalAmount` external
Returns the capital amount of a given risk pool.
#### [](#InstanceService-getTotalValueLocked-uint256-)
`getTotalValueLocked(uint256 riskpoolId) → uint256 totalValueLockedAmount` external
Returns the total value locked in a specific risk pool.
#### [](#InstanceService-getCapacity-uint256-)
`getCapacity(uint256 riskpoolId) → uint256 capacityAmount` external
Returns the available capacity of a risk pool.
#### [](#InstanceService-getBalance-uint256-)
`getBalance(uint256 riskpoolId) → uint256 balanceAmount` external
Returns the balance amount of a specific risk pool.
#### [](#InstanceService-activeBundles-uint256-)
`activeBundles(uint256 riskpoolId) → uint256 numberOfActiveBundles` external
Returns the number of active bundles for a given risk pool.
#### [](#InstanceService-getActiveBundleId-uint256-uint256-)
`getActiveBundleId(uint256 riskpoolId, uint256 bundleIdx) → uint256 bundleId` external
Returns the active bundle ID for a given risk pool and bundle index.
#### [](#InstanceService-getMaximumNumberOfActiveBundles-uint256-)
`getMaximumNumberOfActiveBundles(uint256 riskpoolId) → uint256 maximumNumberOfActiveBundles` external
Returns the maximum number of active bundles for a given risk pool ID.
#### [](#InstanceService-getBundleToken--)
`getBundleToken() → contract IBundleToken token` external
Returns the bundle token contract address.
#### [](#InstanceService-getBundle-uint256-)
`getBundle(uint256 bundleId) → struct IBundle.Bundle bundle` external
Returns the bundle with the given ID.
#### [](#InstanceService-bundles--)
`bundles() → uint256` external
Returns the number of bundles in the `_bundle` contract.
#### [](#InstanceService-unburntBundles-uint256-)
`unburntBundles(uint256 riskpoolId) → uint256 numberOfUnburntBundles` external
Returns the number of unburnt bundles for a given risk pool ID.
#### [](#InstanceService-getTreasuryAddress--)
`getTreasuryAddress() → address` external
Returns the address of the treasury contract.
#### [](#InstanceService-getInstanceWallet--)
`getInstanceWallet() → address` external
Returns the address of the instance wallet associated with the treasury.
#### [](#InstanceService-getRiskpoolWallet-uint256-)
`getRiskpoolWallet(uint256 riskpoolId) → address` external
Returns the wallet address of the specified riskpool.
#### [](#InstanceService-getComponentToken-uint256-)
`getComponentToken(uint256 componentId) → contract IERC20` external
Returns the IERC20 token associated with the given component ID.
#### [](#InstanceService-getFeeFractionFullUnit--)
`getFeeFractionFullUnit() → uint256` external
Returns the fraction of the treasury fee expressed in full units.
### [](#OracleService)
`OracleService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/OracleService.sol)
import "@etherisc/gif-contracts/contracts/services/OracleService.sol";
Functions
* [`_afterInitialize()`](#OracleService-_afterInitialize--)
* [`respond(_requestId, _data)`](#OracleService-respond-uint256-bytes-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#OracleService-_afterInitialize--)
`_afterInitialize()` internal
Sets the `_query` variable to an instance of the `IQuery` contract.
#### [](#OracleService-respond-uint256-bytes-)
`respond(uint256 _requestId, bytes _data)` external
Allows a registered oracle to respond to a data request.
### [](#ProductService)
`ProductService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/ProductService.sol)
import "@etherisc/gif-contracts/contracts/services/ProductService.sol";
Functions
* [`constructor(_registry)`](#ProductService-constructor-address-)
* [`fallback()`](#ProductService-fallback--)
* [`_delegate(implementation)`](#ProductService-_delegate-address-)
* [`_license()`](#ProductService-_license--)
WithRegistry
* [`getContractFromRegistry(_contractName)`](shared#WithRegistry-getContractFromRegistry-bytes32-)
* [`getContractInReleaseFromRegistry(_release, _contractName)`](shared#WithRegistry-getContractInReleaseFromRegistry-bytes32-bytes32-)
* [`getReleaseFromRegistry()`](shared#WithRegistry-getReleaseFromRegistry--)
#### [](#ProductService-constructor-address-)
`constructor(address _registry)` public
Constructor function that initializes the contract with a registry address.
#### [](#ProductService-fallback--)
`fallback()` external
Fallback function that ensures the caller is a registered product and authorized to execute the delegated policy flow.
#### [](#ProductService-_delegate-address-)
`_delegate(address implementation)` internal
Delegates the current call to `implementation`.
#### [](#ProductService-_license--)
`_license() → contract ILicense` internal
Returns the instance of the License contract.
### [](#RiskpoolService)
`RiskpoolService`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/services/RiskpoolService.sol)
import "@etherisc/gif-contracts/contracts/services/RiskpoolService.sol";
Modifiers
* [`onlyProposedRiskpool()`](#RiskpoolService-onlyProposedRiskpool--)
* [`onlyActiveRiskpool()`](#RiskpoolService-onlyActiveRiskpool--)
* [`onlyOwningRiskpool(bundleId, mustBeActive)`](#RiskpoolService-onlyOwningRiskpool-uint256-bool-)
* [`onlyOwningRiskpoolId(riskpoolId, mustBeActive)`](#RiskpoolService-onlyOwningRiskpoolId-uint256-bool-)
Functions
* [`_afterInitialize()`](#RiskpoolService-_afterInitialize--)
* [`registerRiskpool(wallet, erc20Token, collateralizationLevel, sumOfSumInsuredCap)`](#RiskpoolService-registerRiskpool-address-address-uint256-uint256-)
* [`createBundle(owner, filter, initialCapital)`](#RiskpoolService-createBundle-address-bytes-uint256-)
* [`fundBundle(bundleId, amount)`](#RiskpoolService-fundBundle-uint256-uint256-)
* [`defundBundle(bundleId, amount)`](#RiskpoolService-defundBundle-uint256-uint256-)
* [`lockBundle(bundleId)`](#RiskpoolService-lockBundle-uint256-)
* [`unlockBundle(bundleId)`](#RiskpoolService-unlockBundle-uint256-)
* [`closeBundle(bundleId)`](#RiskpoolService-closeBundle-uint256-)
* [`burnBundle(bundleId)`](#RiskpoolService-burnBundle-uint256-)
* [`collateralizePolicy(bundleId, processId, collateralAmount)`](#RiskpoolService-collateralizePolicy-uint256-bytes32-uint256-)
* [`processPremium(bundleId, processId, amount)`](#RiskpoolService-processPremium-uint256-bytes32-uint256-)
* [`processPayout(bundleId, processId, amount)`](#RiskpoolService-processPayout-uint256-bytes32-uint256-)
* [`releasePolicy(bundleId, processId)`](#RiskpoolService-releasePolicy-uint256-bytes32-)
* [`setMaximumNumberOfActiveBundles(riskpoolId, maxNumberOfActiveBundles)`](#RiskpoolService-setMaximumNumberOfActiveBundles-uint256-uint256-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#RiskpoolService-onlyProposedRiskpool--)
`onlyProposedRiskpool()` modifier
#### [](#RiskpoolService-onlyActiveRiskpool--)
`onlyActiveRiskpool()` modifier
#### [](#RiskpoolService-onlyOwningRiskpool-uint256-bool-)
`onlyOwningRiskpool(uint256 bundleId, bool mustBeActive)` modifier
#### [](#RiskpoolService-onlyOwningRiskpoolId-uint256-bool-)
`onlyOwningRiskpoolId(uint256 riskpoolId, bool mustBeActive)` modifier
#### [](#RiskpoolService-_afterInitialize--)
`_afterInitialize()` internal
Sets the addresses of the BundleController, ComponentController, PoolController, and TreasuryModule contracts.
#### [](#RiskpoolService-registerRiskpool-address-address-uint256-uint256-)
`registerRiskpool(address wallet, address erc20Token, uint256 collateralizationLevel, uint256 sumOfSumInsuredCap)` external
Registers a new risk pool with the given parameters.
#### [](#RiskpoolService-createBundle-address-bytes-uint256-)
`createBundle(address owner, bytes filter, uint256 initialCapital) → uint256 bundleId` external
Creates a new bundle with the given parameters and adds it to the active set of the riskpool.
#### [](#RiskpoolService-fundBundle-uint256-uint256-)
`fundBundle(uint256 bundleId, uint256 amount) → uint256 netAmount` external
This function allows a user to fund a bundle with a specified amount.
#### [](#RiskpoolService-defundBundle-uint256-uint256-)
`defundBundle(uint256 bundleId, uint256 amount) → uint256 netAmount` external
Defunds a bundle by withdrawing a specified amount of tokens from it.
#### [](#RiskpoolService-lockBundle-uint256-)
`lockBundle(uint256 bundleId)` external
Locks a bundle, preventing it from being traded or redeemed.
#### [](#RiskpoolService-unlockBundle-uint256-)
`unlockBundle(uint256 bundleId)` external
Unlocks a bundle for trading by adding its ID to the active set of a risk pool and unlocking the bundle.
#### [](#RiskpoolService-closeBundle-uint256-)
`closeBundle(uint256 bundleId)` external
Closes a bundle and removes it from the active set of the owning riskpool.
#### [](#RiskpoolService-burnBundle-uint256-)
`burnBundle(uint256 bundleId)` external
Burns a closed bundle, withdrawing its remaining balance and defunding it from the riskpool and the pool.
#### [](#RiskpoolService-collateralizePolicy-uint256-bytes32-uint256-)
`collateralizePolicy(uint256 bundleId, bytes32 processId, uint256 collateralAmount)` external
Collateralizes a policy by locking a specified amount of collateral for a given bundle and process ID.
#### [](#RiskpoolService-processPremium-uint256-bytes32-uint256-)
`processPremium(uint256 bundleId, bytes32 processId, uint256 amount)` external
Processes a premium payment for a specific bundle.
#### [](#RiskpoolService-processPayout-uint256-bytes32-uint256-)
`processPayout(uint256 bundleId, bytes32 processId, uint256 amount)` external
Processes a payout for a specific bundle.
#### [](#RiskpoolService-releasePolicy-uint256-bytes32-)
`releasePolicy(uint256 bundleId, bytes32 processId) → uint256 collateralAmount` external
Releases a policy for a given bundle and process ID.
#### [](#RiskpoolService-setMaximumNumberOfActiveBundles-uint256-uint256-)
`setMaximumNumberOfActiveBundles(uint256 riskpoolId, uint256 maxNumberOfActiveBundles)` external
Sets the maximum number of active bundles for a given riskpool.
[← Modules](/contracts/2.x/api/modules)
[Shared →](/contracts/2.x/api/shared)
---
# Governance Model - Etherisc Docs
Governance Model
================
[](#overview)
Overview
----------------------
The Etherisc Governance Model (EGM) aims to create an effective self-regulatory mechanism for the Etherisc ecosystem. Etherisc considers a baseline of rules and procedures as necessary to ensure that:
* The platform operates in a way that is consistent with the rules and recommendations of the Decentralized Insurance Platform (DIP) protocol.
* Platform participants conduct business in the interest of the good of the commons while safeguarding the interests of customers and investors.
* Market integrity is preserved, meaning no market abuse and all platform participants have equal access to accurate and transparent information.
Consistent with a decentralized infrastructure, the community should carry out regulation rather than a sole entity. Additionally, rules need to be enforceable to incentivize compliance. For rules to be enforceable, there must be an element of staking. Beyond a smooth-functioning ecosystem being an end, the EGM will strengthen confidence in the Etherisc decentralized insurance platform and support growth and massive adoption.
[](#core_values)
Core Values
----------------------------
Any system of rules requires a set of underlying principles and ‘values.’ Both the set and the meaning of these values is necessary, to a certain extent, fuzzy and cannot be fully captured by any formal definition.
Some people would, e.g., emphasize other values not listed here, or put them in different words. However, these rules have been proven helpful in other contexts that rely on decentralization and collaboration. They serve as general guidelines to derive more precisely defined rules and requirements.
### [](#respect)
Respect
Each platform user, actor and stakeholder should respect and value diversity. We promote inclusiveness and treat others with tact, courtesy and respect. We abstain from and actively discourage discrimination in all forms.
### [](#collaboration)
Collaboration
The DIP is based on solid and voluntary partnerships. The platform will always encourage partnerships and cooperation. Each participant should be able to benefit from evolving partnerships.
### [](#responsibility)
Responsibility
Each participant shall act entirely on their responsibility, while the platform will provide any means to support this. All participants acknowledge their joint responsibility for the operations and development of the platform as a whole.
### [](#trust)
Trust
The platform encourages trustful behavior and will provide a safe environment for all participants. Each participant is committed to compliant behavior. Transparency is an essential element in trust-building. Therefore, we encourage transparency as much as possible without violating the justified needs for the protection of each platform participant.
### [](#public_good_commons)
Public good / commons
The platform, as a whole, serves the public good. It is a [‘commons’](https://www.onthecommons.org/magazine/elinor-ostroms-8-principles-managing-commmons)
in the senses of Elinor Ostrom and operated by the community of all participants. Therefore, the governance rules for the platform are based on the eight rules for successful commons coined by E. Ostrom. We discuss how the ‘eight rules’ are implemented in the EGM and DIP protocol.
[](#structure)
Structure
------------------------

You will find the actors and participants described in the image above in the table below. The image is only a snapshot and more actors are added and others may be omitted.
| Name | Short description |
| --- | --- |
| Decentralized Insurance Foundation | Development and promotion of the DIP protocol, funding of the development of the Generic Insurance Framework (GIF) |
| Kleros | Decentralized arbitration service and token curated registry |
| DAOstack | Software stack for DAOs including a library of governance protocols and interfaces for creating and managing DAOs |
| Mainnet | Example blockchain |
| Gnosis chain | Example blockchain |
| Avalanche | Example blockchain |
| Polygon | Example blockchain |
**The four defining aspects of the EGM are as follows:**
* Platform participants as the topmost authority
* The Decentralized Insurance Foundation (DIF) as the non-profit, neutral link to the real-world institutions and legal systems
* Certification of GIF instances as a market signaling mechanism to incentivize high standard of work
* Dispute resolution via an independent arbitration board
The platform’s participants - be they insureds, product owners, or risk pool keepers - are the topmost authority of the platform. Their stake is represented by governance token (vDIP), minted against staking DIP token in a governance contract. Governance token (vDIP) are used for decision-making in all DAOs involved in the platform.
While addresses on blockchain protocols represent the platform participants, we need a link to the real world, connecting the on-chain infrastructure with legal entities in the real world.
In the real world, the topmost authority is the not-for-profit DIF, based in Zug, Switzerland, and regulated according to Swiss law.
The purpose of the DIF is defined in the notarial deed of the foundation and cannot be changed:
_“The Foundation’s purpose is promoting and developing new technologies and applications, especially in the fields of new open and decentralized software architectures mainly in the insurance field. A dominating but not exclusive focus is set on the promotion and development of the so-called DIP-protocol and the related technologies, as well as the promotion and support of applications using the DIP-protocol.”_
Therefore, the only purpose of the foundation is to serve the community of participants in building and using the DIP protocol. The DIF is committed to strict neutrality. Therefore, the DIF will never engage in disputes between participants. For dispute resolution, the DIP platform will use existing mechanisms like, e.g., the Kleros arbitration board. The foundation council formally represents the DIF.
The main task of the DIF in the context of the technical DIP protocol is the certification of GIF instances on the different blockchains. On each blockchain, there can be multiple GIF instances. The rules for certification will be published.
The rules should be such that, if possible, there is no ambiguity in interpretation and that people with basic technical understanding and common sense can decide whether a particular GIF instance meets the requirements.
Requirements include technical stability (like contract audits), soundness, and legal compliance. Certified GIF instances are registered in a token curated registry. The concrete rules for certification of GIF instances are currently worked in progress.
Certification has no consequences - it’s just signaling “this GIF instance has undergone thorough scrutiny and due diligence and implements the rules and recommendations of the DIP protocol.” Thus, a certification will act as a strong differentiator in the market, and non-certification will be a red flag for both customers and investors. Self-regulation works.
An instance operator operates one or more GIF instances. An instance operator can be represented by an EOA (externally owned address), a multisig, or a DAO. It is recommended that the instance operator is represented by a DAO, the members of which are the stakeholders of this GIF instance.
Each GIF instance may send a delegate to the advisory board of the DIF. The advisory board shall interact with the foundation council and represent the interests of the GIF instances and its stakeholders with the foundation council. The advisory board and its decision-making processes are implemented as a DAO.
Each GIF instance (or the DAO representing it) can implement governance rules on a more granular level, e.g., rules to decide which products may be listed on the instance and which not, as long as these rules follow our core values and the other rules of the platform.
Each GIF instance needs to implement rules that ensure that the instance can participate in the funding of the EGM and the DIP protocol.
Disputes are resolved via an arbitration board. Possible disputes include, e.g., registration of a GIF instance in the TCR or disputes concerning insurance claims that cannot be resolved via smart contract logic (e.g., oracle malfunction).
[](#funding)
Funding
--------------------
The funding is only to cover costs, to be self-sustaining and not profit-oriented. But the infrastructure to maintain the EGM and the development and maintenance of the DIP protocol (especially the GIF framework) requires funding. Each GIF instance will therefore be required to:
* Stake a defined amount of DIP token in a governance staking contract
* Pay a regular fee to cover the operational cost of the EGM
The required stakes and fees are calculated based on the economic volume transacted on the particular instance. We will inform you as soon as we have the details.
In the event of rule violations, sanctions of varying severity may be imposed:
* Financial penalties for misbehaving members
* Slashing of staked DIP token
* Exclusion of participants from a GIF instance
* Exclusion of a GIF instance from the token curated registry
Part of the fees paid will be burned to create a slight deflationary effect on the DIP token.
[](#monetary_policy)
Monetary Policy
------------------------------------
As a significant holder of DIP token (about 60% of the total supply of DIP token), the DIF is obligated to protect the interests of the DIP token holders. The treasury of the DIF is not counted in the circulating supply of DIP token.
The DIF may allocate grants or provide DIP token to incentivize developing and using the DIP protocol. These grants and incentives will increase the circulating supply and could therefore dilute the value of the DIP token. However, the DIF will always take care that grants and incentives are always related to the value created so that the DIP token does not experience unnecessary dilution.
[](#commons)
Commons
--------------------
Commons need to have clearly defined boundaries. In particular, who is entitled to access to what? Unless there’s a specified community of benefit, it becomes a free for all, and that’s not how commons work.
The “boundaries” are implemented by the token-curated registry for the GIF Instances and the registries for products, oracles and risk pools in the GIF instances themselves.
There is no one-size-fits-all approach to standard resource management. Local people and ecological needs dictate rules. The rules are always created at the lowest possible level. E.g., the top-level rules only govern GIF instances. More granular rules are implemented on lower levels and can vary for different GIF instances.
Participatory decision-making is vital. There are many ways to make it happen, but people will be more likely to follow the rules if they have a hand writing them. Participation is implemented by DAOs, which govern the GIF instances. Each GIF instance is a member of the advisory board of the DIF.
Commons must be monitored. Once rules have been set, communities need a way of checking that people are keeping them. Commons don’t run on goodwill but on accountability. The monitoring happens on two levels: The top level is given by the DIF, the token-curated registry of GIF instances and the arbitration board. On a lower level, the monitoring is given by the DAOs governing the individual GIF instances.
Sanctions for those who abuse the commons should be graduated. Ostrom observed that the best commons didn’t just ban people who broke the rules. That tended to create resentment. Instead, they had systems of warnings, fines, and informal reputational consequences in the community. There are different methods of sanctioning, each with a different severity level.
Conflict resolution should be easily accessible. When issues come up, resolving them should be informal, cheap and straightforward. That means anyone can take their problems for mediation, and nobody is shut out. Problems are solved rather than ignored because nobody wants to pay legal fees. This is implemented by the arbitration board, which offers dispute resolution on every level.
Commons need the right to organize. Your commons rules won’t count for anything if a higher local authority doesn’t recognize them as legitimate. This is implemented by the written rules which govern the DIF and which, in turn, govern the DAOs representing the different GIF Instances.
Commons work best when nested within more extensive networks. Some things can be managed locally, but some might need broader regional cooperation – for example, an irrigation network might depend on a river that others also draw on upstream. This is implemented by the hierarchical structure, the top of which is a legal foundation recognized by Swiss law.
[← Token Model](/gif/token-model)
[GIF Monitor →](/gif/gif-monitor)
---
# Services - Etherisc Docs
Services
========
[](#overview)
Overview
----------------------

The services supply the core contracts with data and ensure that only the authorized owners can supply the core contracts with data or query data.
[Here](https://github.com/etherisc/gif-contracts/tree/develop/contracts/modules)
in these modules, the core functionalities of the GIF are deposited from a technical view. Here you will find all functions. Access (access control), Bundles, Components, Licenses, Policies, (Risk) Pools, Queries (Oracles), Registries and the Treasuries (capital flow).

You will undoubtedly notice fewer services [here](https://github.com/etherisc/gif-contracts/tree/develop/contracts/services)
than in the modules and that the view has changed.
The services are tailored and aligned to the different roles. In the services are all information and functions that the role owner may use. Furthermore, the services also check whether the corresponding role wants to access the core contracts.
Either one has the role, in which case it continues, or one does not have access authorization, in which case it is rejected.
The idea behind this is that the users of the GIF never access the core contracts themselves but always go through the ‘intermediate layer’ services. The services do not work according to the logic of the core contracts but according to the permissions of the existing roles.
[](#instanceoperatorservice)
InstanceOperatorService
----------------------------------------------------
The instance operator has vast powers, so the InstanceOperatorService.sol is extensive.
### [](#registry)
Registry

Here you, as an instance operator, can manage releases and contracts. He can create and activate a new release (prepareRelease). You can create new contracts (register) or remove them (deregister). Then you can register (registerInRelease) and deregister (deregisterInRelease) the contracts in the corresponding release.
### [](#access)
Access

Here you can administrate access management. You can create (createRole) or remove (invalidateRole) a participant (role). Once the role is created, you should check the component the new participant wants to deploy. If all this fits, you can grant the new participant (grantRole) or revoke the legitimation (revokeRole).
### [](#component)
Component

A component can be a product, risk pool or oracle. The component owner can request the implementation of his component. You, as an instance operator, can approve (approve), decline (decline), suspend (suspend), resume (resume) or archive (archive) the component.
### [](#service_staking)
Service staking

This functionality is still under development. We will inform you when we have a version here. You can then check if the component meets the requirements and then activate the component.
### [](#treasury)
Treasury

This is about money or tokens. If you get hacked, you can turn off the entire treasury (suspendTreasury) and re-enable it after fixing the cause (resumeTreasury).
You can include the wallet of the instance (setInstanceWallet), include the wallet of a risk pool (setRiskpoolWallet) and define the tokens that are accepted in a product (setProductToken).
As an instance operator, you can also set your premiums (setPremiumFees) and those of the investor (setCapitalFees).

As an instance operator, you can also define how the fees are divided on the component level (createFeeSpecification). What you get, what the component owner gets and any other fees, for example, to an oracle.
[](#instanceservice)
InstanceService
------------------------------------
The instance service is not tuned to a specific role but to the complete instance. But you won’t find a function that can change a state. All functions are queries to the instance. The service defines what information can be retrieved from an instance. Here there are also no permissions for who can query what. Everyone can retrieve all data. This is how open source works.
This is the convenient service to get, for example, as a product owner, information such as

* how many claims (getClaim) has my product
* how many payouts (getPayout) have I paid
to be displayed.
[](#oracleservice)
OracleService
--------------------------------
The oracle service is relatively manageable. It is merely a matter of retrieving information outside the blockchain and utilizing it on the blockchain.
[](#productservice)
ProductService
----------------------------------

In product service, the complete life cycle of a policy is mapped from registering the product (newApplication)to collecting the premiums (collectPremium) and checking if the premium is paid in full (adjustPremiumInsured).

In this section, you can see the functions of the individual life cycles of a policy, from revocation (revoke) to acceptance of the policy (underwrite) or its rejection (decline) to expiration (expire) and termination (close).

In the event of a payout, a claim must first be received (newClaim). The claim can be accepted (confirmClaim) or rejected (declineClaim). In both cases, the claim is closed afterwards (closeClaim).

In the case of acceptance, the payment is made (newPayout). In the event of a payout, partial amounts can be paid out once or several times up to the agreed sum insured (processPayout).

Oracles provide the data required for a claim and payout. As the product owner, you define which oracle is to be used and how often the required data is requested (request). You can cancel the data supply if you don’t need it anymore (cancelRequest).
[](#riskpoolservice)
RiskPoolService
------------------------------------

In the risk pool service, the complete functional scope of a risk pool is mapped. First, the risk pool must be registered (registerRiskpool) on the instance. After that, you can create new risk bundles (createBundle) and stake or (fundBundle) unstake (defundBundle) tokens.

As a risk bundle owner, you can lock (lockBundle) and unlock (unlockBundle) your risk bundle. If you want to end your risk bundle, you can close it (closeBundle). When the last policy is paid out or expired, you can burn (burnBundle) the ERC721 token minted when you opened your bundle.

The following describes the functions related to a risk bundle and risk bundle owner, analogous to our Etherisc Depeg protection web app. You can write risk pool and risk pool keeper wherever risk bundle and risk bundle owner are written. This differs from product to product.
When a policy is taken out, it must be collateralized (collaterizePolicy) from the risk bundle. The premium flows into the risk bundle (processPremium) and if a claim is made, the amount is paid out (processPayout) of the risk bundle.
When a policy is closed, the logged funds are rereleased. As a risk bundle owner, you can decide whether the funds remain in the risk bundle and are used for new policies or taken out of the risk pool as profit (releasePolicy).
As a risk pool keeper, you can also define the maximum number of active risk bundles in your risk pool (setMaximumNumberOfActiveBundles).
[](#componentownerservice)
ComponentOwnerService
------------------------------------------------

A component owner can be an oracle owner, a product owner, or a risk pool keeper, depending on the core object it manages.
A component owner can propose (propose) his component. The instance operator registers, approve and activates the component.
Here the possibility of staking for the component owner is already built in (stake, withdraw). These are currently only placeholders. The evaluation of the process still needs to be finished.
As a component owner, you can pause (pause) your product if you don’t want to run it anymore. You can reactivate (unpause) or archive (archive) the product when all liabilities and terms of the sold products have expired. An archived product cannot be reactivated.
As a risk pool keeper, you can also define the maximum number of active risk bundles in your risk pool.
[← Components](/gif/components)
[Token Model →](/gif/token-model)
---
# Modules - Etherisc Docs
Modules
=======
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/modules](https://docs.etherisc.com/contracts/api/modules) |
[](#contracts)
Contracts
------------------------
### [](#AccessController)
`AccessController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/AccessController.sol)
import "@etherisc/gif-contracts/contracts/modules/AccessController.sol";
The provided smart contract is called "AccessController" and is written in Solidity. It implements the "IAccess" interface and inherits from the "CoreController" contract and the "AccessControlEnumerable" contract. The contract provides functionalities for access control and role management.
Roles:
The contract defines three role identifiers as bytes32 constants: 1. PRODUCT\_OWNER\_ROLE: Represents the role of a product owner. 2. ORACLE\_PROVIDER\_ROLE: Represents the role of an oracle provider. 3. RISKPOOL\_KEEPER\_ROLE: Represents the role of a risk pool keeper.
State Variables:
* `validRole`: A mapping that stores the validity of each role. It maps a role identifier (bytes32) to a boolean value indicating whether the role is valid.
* `_defaultAdminSet`: A boolean flag indicating whether the default admin role has been set.
Modifiers:
* `onlyInstanceOperator`: A modifier that restricts access to functions to only instance operators.
Overall, the contract provides a flexible access control mechanism by defining roles and allowing the assignment, revocation, and validation of roles by instance operators. It also sets a default admin role and manages the validity of roles through the `validRole` mapping.
Functions
* [`_afterInitialize()`](#AccessController-_afterInitialize--)
* [`_getName()`](#AccessController-_getName--)
* [`setDefaultAdminRole(defaultAdmin)`](#AccessController-setDefaultAdminRole-address-)
* [`grantRole(role, principal)`](#AccessController-grantRole-bytes32-address-)
* [`revokeRole(role, principal)`](#AccessController-revokeRole-bytes32-address-)
* [`renounceRole(role, principal)`](#AccessController-renounceRole-bytes32-address-)
* [`addRole(role)`](#AccessController-addRole-bytes32-)
* [`invalidateRole(role)`](#AccessController-invalidateRole-bytes32-)
* [`hasRole(role, principal)`](#AccessController-hasRole-bytes32-address-)
* [`getDefaultAdminRole()`](#AccessController-getDefaultAdminRole--)
* [`getProductOwnerRole()`](#AccessController-getProductOwnerRole--)
* [`getOracleProviderRole()`](#AccessController-getOracleProviderRole--)
* [`getRiskpoolKeeperRole()`](#AccessController-getRiskpoolKeeperRole--)
AccessControlEnumerable
* [`supportsInterface(interfaceId)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControlEnumerable-supportsInterface-bytes4-)
* [`getRoleMember(role, index)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControlEnumerable-getRoleMember-bytes32-uint256-)
* [`getRoleMemberCount(role)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControlEnumerable-getRoleMemberCount-bytes32-)
* [`_grantRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControlEnumerable-_grantRole-bytes32-address-)
* [`_revokeRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControlEnumerable-_revokeRole-bytes32-address-)
AccessControl
* [`hasRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-hasRole-bytes32-address-)
* [`_checkRole(role)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-_checkRole-bytes32-)
* [`_checkRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-_checkRole-bytes32-address-)
* [`getRoleAdmin(role)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-getRoleAdmin-bytes32-)
* [`grantRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-grantRole-bytes32-address-)
* [`revokeRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-revokeRole-bytes32-address-)
* [`renounceRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-renounceRole-bytes32-address-)
* [`_setupRole(role, account)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-_setupRole-bytes32-address-)
* [`_setRoleAdmin(role, adminRole)`](https://docs.openzeppelin.com/contracts/3.x/api/access#AccessControl-_setRoleAdmin-bytes32-bytes32-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
IAccessControl
* [`RoleAdminChanged(role, previousAdminRole, newAdminRole)`](https://docs.openzeppelin.com/contracts/3.x/api/access#IAccessControl-RoleAdminChanged-bytes32-bytes32-bytes32-)
* [`RoleGranted(role, account, sender)`](https://docs.openzeppelin.com/contracts/3.x/api/access#IAccessControl-RoleGranted-bytes32-address-address-)
* [`RoleRevoked(role, account, sender)`](https://docs.openzeppelin.com/contracts/3.x/api/access#IAccessControl-RoleRevoked-bytes32-address-address-)
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#AccessController-_afterInitialize--)
`_afterInitialize()` internal
This function is called after contract initialization and adds the product owner, oracle provider, and riskpool keeper roles.
#### [](#AccessController-_getName--)
`_getName() → bytes32` internal
Returns the name of the contract.
#### [](#AccessController-setDefaultAdminRole-address-)
`setDefaultAdminRole(address defaultAdmin)` external
Sets the default admin role for the Access Control List (ACL).
#### [](#AccessController-grantRole-bytes32-address-)
`grantRole(bytes32 role, address principal)` public
Grants a role to a principal.
#### [](#AccessController-revokeRole-bytes32-address-)
`revokeRole(bytes32 role, address principal)` public
Revokes the specified role from the specified principal.
#### [](#AccessController-renounceRole-bytes32-address-)
`renounceRole(bytes32 role, address principal)` public
Removes the specified `principal` from the `role` in the access control list (ACL) of the contract.
#### [](#AccessController-addRole-bytes32-)
`addRole(bytes32 role)` public
Adds a new role to the Access Control List.
#### [](#AccessController-invalidateRole-bytes32-)
`invalidateRole(bytes32 role)` public
Invalidates a role.
#### [](#AccessController-hasRole-bytes32-address-)
`hasRole(bytes32 role, address principal) → bool` public
Checks if a given principal has a specific role.
#### [](#AccessController-getDefaultAdminRole--)
`getDefaultAdminRole() → bytes32` public
Returns the default admin role.
#### [](#AccessController-getProductOwnerRole--)
`getProductOwnerRole() → bytes32` public
Returns the bytes32 value of the PRODUCT\_OWNER\_ROLE.
#### [](#AccessController-getOracleProviderRole--)
`getOracleProviderRole() → bytes32` public
Returns the bytes32 identifier of the Oracle Provider role.
#### [](#AccessController-getRiskpoolKeeperRole--)
`getRiskpoolKeeperRole() → bytes32` public
Returns the bytes32 value of the RISKPOOL\_KEEPER\_ROLE.
The "AccessController" smart contract is a Solidity implementation that provides access control and role management functionalities. It inherits from other contracts and implements the "IAccess" interface. It defines three role identifiers: PRODUCT\_OWNER\_ROLE, ORACLE\_PROVIDER\_ROLE, and RISKPOOL\_KEEPER\_ROLE. The contract has state variables to store role validity and a flag to indicate if the default admin role is set. It includes functions to grant, revoke, and renounce roles, as well as add and invalidate roles. t also has functions to check role membership and retrieve role identifiers. The contract ensures that only instance operators can access certain functions. Overall, it offers a flexible access control mechanism for managing roles and permissions.
### [](#BundleController)
`BundleController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/BundleController.sol)
import "@etherisc/gif-contracts/contracts/modules/BundleController.sol";
The smart contract is used to manage bundles, which are collections of policies.
* The contract imports other Solidity contracts such as `PolicyController.sol`, `CoreController.sol`, and `BundleToken.sol`.
* The contract implements the `IBundle` interface and extends the `CoreController` contract.
* It defines several mappings to store information about bundles, active policies, locked capital per policy, and the number of unburt bundles for each risk pool.
* There is a private variable `_bundleCount` to keep track of the number of bundles created.
* The contract includes modifiers to restrict access to certain functions, such as `onlyRiskpoolService` and `onlyFundableBundle`.
The contract includes various modifiers and event emitters to enforce access control and emit relevant events. Overall, the `BundleController` contract provides functionality to manage bundles and their associated policies, including creating, funding, locking, unlocking, closing, burning, collateralizing, and releasing policies within a bundle.
Modifiers
* [`onlyRiskpoolService()`](#BundleController-onlyRiskpoolService--)
* [`onlyFundableBundle(bundleId)`](#BundleController-onlyFundableBundle-uint256-)
Functions
* [`_afterInitialize()`](#BundleController-_afterInitialize--)
* [`create(owner_, riskpoolId_, filter_, amount_)`](#BundleController-create-address-uint256-bytes-uint256-)
* [`fund(bundleId, amount)`](#BundleController-fund-uint256-uint256-)
* [`defund(bundleId, amount)`](#BundleController-defund-uint256-uint256-)
* [`lock(bundleId)`](#BundleController-lock-uint256-)
* [`unlock(bundleId)`](#BundleController-unlock-uint256-)
* [`close(bundleId)`](#BundleController-close-uint256-)
* [`burn(bundleId)`](#BundleController-burn-uint256-)
* [`collateralizePolicy(bundleId, processId, amount)`](#BundleController-collateralizePolicy-uint256-bytes32-uint256-)
* [`processPremium(bundleId, processId, amount)`](#BundleController-processPremium-uint256-bytes32-uint256-)
* [`processPayout(bundleId, processId, amount)`](#BundleController-processPayout-uint256-bytes32-uint256-)
* [`releasePolicy(bundleId, processId)`](#BundleController-releasePolicy-uint256-bytes32-)
* [`getOwner(bundleId)`](#BundleController-getOwner-uint256-)
* [`getState(bundleId)`](#BundleController-getState-uint256-)
* [`getFilter(bundleId)`](#BundleController-getFilter-uint256-)
* [`getCapacity(bundleId)`](#BundleController-getCapacity-uint256-)
* [`getTotalValueLocked(bundleId)`](#BundleController-getTotalValueLocked-uint256-)
* [`getBalance(bundleId)`](#BundleController-getBalance-uint256-)
* [`getToken()`](#BundleController-getToken--)
* [`getBundle(bundleId)`](#BundleController-getBundle-uint256-)
* [`bundles()`](#BundleController-bundles--)
* [`unburntBundles(riskpoolId)`](#BundleController-unburntBundles-uint256-)
* [`_getPoolController()`](#BundleController-_getPoolController--)
* [`_changeState(bundleId, newState)`](#BundleController-_changeState-uint256-enum-IBundle-BundleState-)
* [`_setState(bundleId, newState)`](#BundleController-_setState-uint256-enum-IBundle-BundleState-)
* [`_checkStateTransition(oldState, newState)`](#BundleController-_checkStateTransition-enum-IBundle-BundleState-enum-IBundle-BundleState-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IBundle
* [`LogBundleCreated(bundleId, riskpoolId, owner, state, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundleStateChanged(bundleId, oldState, newState)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundleCapitalProvided(bundleId, sender, amount, capacity)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundleCapitalWithdrawn(bundleId, recipient, amount, capacity)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundlePolicyCollateralized(bundleId, processId, amount, capacity)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundlePayoutProcessed(bundleId, processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
* [`LogBundlePolicyReleased(bundleId, processId, amount, capacity)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IBundle.sol)
#### [](#BundleController-onlyRiskpoolService--)
`onlyRiskpoolService()` modifier
#### [](#BundleController-onlyFundableBundle-uint256-)
`onlyFundableBundle(uint256 bundleId)` modifier
#### [](#BundleController-_afterInitialize--)
`_afterInitialize()` internal
Performs internal operations after the contract initialization.
#### [](#BundleController-create-address-uint256-bytes-uint256-)
`create(address owner_, uint256 riskpoolId_, bytes filter_, uint256 amount_) → uint256 bundleId` external
Creates a new bundle and mints a corresponding NFT token. Only callable by the RiskpoolService contract.
#### [](#BundleController-fund-uint256-uint256-)
`fund(uint256 bundleId, uint256 amount)` external
Adds funds to a bundle’s capital and balance.
#### [](#BundleController-defund-uint256-uint256-)
`defund(uint256 bundleId, uint256 amount)` external
Allows the Riskpool service to withdraw `amount` from the `bundleId` Bundle.
#### [](#BundleController-lock-uint256-)
`lock(uint256 bundleId)` external
Locks a bundle of assets.
#### [](#BundleController-unlock-uint256-)
`unlock(uint256 bundleId)` external
Unlocks a bundle, changing its state to active.
#### [](#BundleController-close-uint256-)
`close(uint256 bundleId)` external
Closes a bundle of policies.
#### [](#BundleController-burn-uint256-)
`burn(uint256 bundleId)` external
Burns a bundle and changes its state to Burned.
#### [](#BundleController-collateralizePolicy-uint256-bytes32-uint256-)
`collateralizePolicy(uint256 bundleId, bytes32 processId, uint256 amount)` external
Collateralizes a policy by locking a specific amount of capital in the corresponding bundle.
#### [](#BundleController-processPremium-uint256-bytes32-uint256-)
`processPremium(uint256 bundleId, bytes32 processId, uint256 amount)` external
Process the premium payment for a given bundle and update its balance.
#### [](#BundleController-processPayout-uint256-bytes32-uint256-)
`processPayout(uint256 bundleId, bytes32 processId, uint256 amount)` external
Processes a payout for a policy from a bundle.
#### [](#BundleController-releasePolicy-uint256-bytes32-)
`releasePolicy(uint256 bundleId, bytes32 processId) → uint256 remainingCollateralAmount` external
Release a policy and update the bundle capital.
#### [](#BundleController-getOwner-uint256-)
`getOwner(uint256 bundleId) → address` public
Returns the address of the owner of the token associated with the given bundle ID.
#### [](#BundleController-getState-uint256-)
`getState(uint256 bundleId) → enum IBundle.BundleState` public
Returns the state of the bundle with the given ID.
#### [](#BundleController-getFilter-uint256-)
`getFilter(uint256 bundleId) → bytes` public
Returns the filter of a given bundle.
#### [](#BundleController-getCapacity-uint256-)
`getCapacity(uint256 bundleId) → uint256` public
Returns the available capacity of a bundle.
#### [](#BundleController-getTotalValueLocked-uint256-)
`getTotalValueLocked(uint256 bundleId) → uint256` public
Returns the total value locked in a particular bundle.
#### [](#BundleController-getBalance-uint256-)
`getBalance(uint256 bundleId) → uint256` public
Returns the balance of a specific bundle.
#### [](#BundleController-getToken--)
`getToken() → contract BundleToken` external
Returns the BundleToken contract instance.
#### [](#BundleController-getBundle-uint256-)
`getBundle(uint256 bundleId) → struct IBundle.Bundle` public
Returns the bundle with the specified bundle ID.
#### [](#BundleController-bundles--)
`bundles() → uint256` public
Returns the number of bundles created.
#### [](#BundleController-unburntBundles-uint256-)
`unburntBundles(uint256 riskpoolId) → uint256` external
Returns the number of unburnt bundles for a given riskpool ID.
#### [](#BundleController-_getPoolController--)
`_getPoolController() → contract PoolController _poolController` internal
Returns the pool controller contract instance.
#### [](#BundleController-_changeState-uint256-enum-IBundle-BundleState-)
`_changeState(uint256 bundleId, enum IBundle.BundleState newState)` internal
Changes the state of a bundle.
#### [](#BundleController-_setState-uint256-enum-IBundle-BundleState-)
`_setState(uint256 bundleId, enum IBundle.BundleState newState)` internal
Sets the state and updated timestamp of a given bundle.
#### [](#BundleController-_checkStateTransition-enum-IBundle-BundleState-enum-IBundle-BundleState-)
`_checkStateTransition(enum IBundle.BundleState oldState, enum IBundle.BundleState newState)` internal
Checks if a state transition is valid.
The "BundleController" smart contract is designed to manage bundles, which are collections of policies. It imports other Solidity contracts, implements the "IBundle" interface, and extends the "CoreController" contract. The contract includes mappings to store information about bundles, active policies, locked capital, and unburt bundles. It has functions to create bundles, fund and defund them, lock and unlock assets, close and burn bundles, and collateralize and release policies. The contract includes modifiers and event emitters for access control and important events. Overall, it provides comprehensive functionality for managing bundles and their associated policies.
### [](#ComponentController)
`ComponentController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/ComponentController.sol)
import "@etherisc/gif-contracts/contracts/modules/ComponentController.sol";
The smart contract provides functionality to manage and control components in a system. The contract defines several mappings and sets to store information about components, such as their addresses, IDs, states, and types. It also includes modifiers to restrict access to certain functions based on the caller’s role.
The contract also includes various modifiers (`onlyComponentOwnerService` and `onlyInstanceOperatorService`) to ensure that only authorized callers can access certain functions.
The contract imports several Solidity files from external dependencies and uses the `EnumerableSet` library from the OpenZeppelin library for set operations.
Modifiers
* [`onlyComponentOwnerService()`](#ComponentController-onlyComponentOwnerService--)
* [`onlyInstanceOperatorService()`](#ComponentController-onlyInstanceOperatorService--)
Functions
* [`propose(component)`](#ComponentController-propose-contract-IComponent-)
* [`_persistComponent(component)`](#ComponentController-_persistComponent-contract-IComponent-)
* [`exists(id)`](#ComponentController-exists-uint256-)
* [`approve(id)`](#ComponentController-approve-uint256-)
* [`decline(id)`](#ComponentController-decline-uint256-)
* [`suspend(id)`](#ComponentController-suspend-uint256-)
* [`resume(id)`](#ComponentController-resume-uint256-)
* [`pause(id)`](#ComponentController-pause-uint256-)
* [`unpause(id)`](#ComponentController-unpause-uint256-)
* [`archiveFromComponentOwner(id)`](#ComponentController-archiveFromComponentOwner-uint256-)
* [`archiveFromInstanceOperator(id)`](#ComponentController-archiveFromInstanceOperator-uint256-)
* [`getComponent(id)`](#ComponentController-getComponent-uint256-)
* [`getComponentId(componentAddress)`](#ComponentController-getComponentId-address-)
* [`getComponentType(id)`](#ComponentController-getComponentType-uint256-)
* [`getComponentState(id)`](#ComponentController-getComponentState-uint256-)
* [`getOracleId(idx)`](#ComponentController-getOracleId-uint256-)
* [`getRiskpoolId(idx)`](#ComponentController-getRiskpoolId-uint256-)
* [`getProductId(idx)`](#ComponentController-getProductId-uint256-)
* [`getRequiredRole(componentType)`](#ComponentController-getRequiredRole-enum-IComponent-ComponentType-)
* [`components()`](#ComponentController-components--)
* [`products()`](#ComponentController-products--)
* [`oracles()`](#ComponentController-oracles--)
* [`riskpools()`](#ComponentController-riskpools--)
* [`isProduct(id)`](#ComponentController-isProduct-uint256-)
* [`isOracle(id)`](#ComponentController-isOracle-uint256-)
* [`isRiskpool(id)`](#ComponentController-isRiskpool-uint256-)
* [`getPolicyFlow(productId)`](#ComponentController-getPolicyFlow-uint256-)
* [`_changeState(componentId, newState)`](#ComponentController-_changeState-uint256-enum-IComponent-ComponentState-)
* [`_checkStateTransition(oldState, newState)`](#ComponentController-_checkStateTransition-enum-IComponent-ComponentState-enum-IComponent-ComponentState-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_afterInitialize()`](shared#CoreController-_afterInitialize--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IComponentEvents
* [`LogComponentProposed(componentName, componentType, componentAddress, id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentApproved(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentDeclined(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentSuspended(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentResumed(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentPaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentUnpaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentArchived(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentStateChanged(id, stateOld, stateNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
#### [](#ComponentController-onlyComponentOwnerService--)
`onlyComponentOwnerService()` modifier
#### [](#ComponentController-onlyInstanceOperatorService--)
`onlyInstanceOperatorService()` modifier
#### [](#ComponentController-propose-contract-IComponent-)
`propose(contract IComponent component)` external
Proposes a new component to the system.
#### [](#ComponentController-_persistComponent-contract-IComponent-)
`_persistComponent(contract IComponent component) → uint256 id` internal
Persists a new component into the system.
#### [](#ComponentController-exists-uint256-)
`exists(uint256 id) → bool` public
Checks if a component with the given ID exists.
#### [](#ComponentController-approve-uint256-)
`approve(uint256 id)` external
Approves a component with the given id.
#### [](#ComponentController-decline-uint256-)
`decline(uint256 id)` external
Changes the state of a component with the given ID to "Declined" and emits a LogComponentDeclined event. Calls the declineCallback function of the component with the given ID.
#### [](#ComponentController-suspend-uint256-)
`suspend(uint256 id)` external
Suspends a component with the given ID.
#### [](#ComponentController-resume-uint256-)
`resume(uint256 id)` external
Resumes a component by changing its state to Active and emitting an event. It also calls the resumeCallback() function of the component to inform it about the resuming.
#### [](#ComponentController-pause-uint256-)
`pause(uint256 id)` external
Pauses the component with the given ID.
#### [](#ComponentController-unpause-uint256-)
`unpause(uint256 id)` external
Unpauses a component with the given id.
#### [](#ComponentController-archiveFromComponentOwner-uint256-)
`archiveFromComponentOwner(uint256 id)` external
Archives a component with the given ID, changing its state to "Archived" and emitting a LogComponentArchived event. Also calls the archiveCallback function of the component with the given ID, informing it about the archiving.
#### [](#ComponentController-archiveFromInstanceOperator-uint256-)
`archiveFromInstanceOperator(uint256 id)` external
Archives a component instance with the given ID.
#### [](#ComponentController-getComponent-uint256-)
`getComponent(uint256 id) → contract IComponent component` public
Returns the component with the given ID.
#### [](#ComponentController-getComponentId-address-)
`getComponentId(address componentAddress) → uint256 id` public
Returns the ID of a registered component given its address.
#### [](#ComponentController-getComponentType-uint256-)
`getComponentType(uint256 id) → enum IComponent.ComponentType componentType` public
Returns the component type of a given component ID.
#### [](#ComponentController-getComponentState-uint256-)
`getComponentState(uint256 id) → enum IComponent.ComponentState componentState` public
Returns the state of the component with the given ID.
#### [](#ComponentController-getOracleId-uint256-)
`getOracleId(uint256 idx) → uint256 oracleId` public
Returns the oracle ID at the given index.
#### [](#ComponentController-getRiskpoolId-uint256-)
`getRiskpoolId(uint256 idx) → uint256 riskpoolId` public
Returns the riskpool ID at the specified index.
#### [](#ComponentController-getProductId-uint256-)
`getProductId(uint256 idx) → uint256 productId` public
Returns the product ID at the given index in the \_products set.
#### [](#ComponentController-getRequiredRole-enum-IComponent-ComponentType-)
`getRequiredRole(enum IComponent.ComponentType componentType) → bytes32` external
Returns the required role for a given component type.
#### [](#ComponentController-components--)
`components() → uint256 count` public
Returns the number of components currently stored in the contract.
#### [](#ComponentController-products--)
`products() → uint256 count` public
Returns the number of products in the set '\_products'.
#### [](#ComponentController-oracles--)
`oracles() → uint256 count` public
Returns the number of oracles registered in the \_oracles set.
#### [](#ComponentController-riskpools--)
`riskpools() → uint256 count` public
Returns the number of risk pools in the EnumerableSet.
#### [](#ComponentController-isProduct-uint256-)
`isProduct(uint256 id) → bool` public
Check if a product exists in the set of products.
#### [](#ComponentController-isOracle-uint256-)
`isOracle(uint256 id) → bool` public
Checks if an oracle with a given ID exists.
#### [](#ComponentController-isRiskpool-uint256-)
`isRiskpool(uint256 id) → bool` public
Checks if a given ID is a riskpool.
#### [](#ComponentController-getPolicyFlow-uint256-)
`getPolicyFlow(uint256 productId) → address _policyFlow` public
Returns the address of the policy flow for a given product ID.
#### [](#ComponentController-_changeState-uint256-enum-IComponent-ComponentState-)
`_changeState(uint256 componentId, enum IComponent.ComponentState newState)` internal
Changes the state of a component.
#### [](#ComponentController-_checkStateTransition-enum-IComponent-ComponentState-enum-IComponent-ComponentState-)
`_checkStateTransition(enum IComponent.ComponentState oldState, enum IComponent.ComponentState newState)` internal
Checks if the state transition is valid. Throws an error if the newState is the same as the oldState. Throws an error if the transition from Created state is not to Proposed state. Throws an error if the transition from Proposed state is not to Active or Declined state. Throws an error if the transition from Declined state is attempted. Throws an error if the transition from Active state is not to Paused or Suspended state. Throws an error if the transition from Paused state is not to Active or Archived state. Throws an error if the transition from Suspended state is not to Active or Archived state. Throws an error if the initial state is not handled.
The "Component Controller" smart contract provides functionality to manage and control components within a system. It includes mappings and sets to store information about components, such as addresses, IDs, states, and types. The contract allows component owners to propose new components, and the contract owner can approve, decline, suspend, resume, pause, unpause, or archive components. Functions are available to retrieve component information, such as ID, type, state, and required role. The contract includes modifiers to restrict access to authorized callers, and it utilizes external dependencies and libraries for set operations. Overall, the contract enables efficient management and control of components in a system.
### [](#LicenseController)
`LicenseController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/LicenseController.sol)
import "@etherisc/gif-contracts/contracts/modules/LicenseController.sol";
The smart contract serves as a controller contract for managing licenses related to products in an insurance ecosystem. The contract implements the `ILicense` interface and extends the `CoreController` contract.
The contract imports two other contracts: `ComponentController.sol` and `CoreController.sol`, which are expected to be located in specific file paths. It also imports several interfaces from the "etherisc/gif-interface" library, including `IComponent.sol`, `IProduct.sol`, and `ILicense.sol`. The contract includes a private variable `_component` of type `ComponentController`, which is used to interact with the `ComponentController` contract.
Overall, the `LicenseController` contract serves as a controller for managing licenses and provides functions to check the authorization status and activity of products within an insurance ecosystem.
Functions
* [`_afterInitialize()`](#LicenseController-_afterInitialize--)
* [`getAuthorizationStatus(productAddress)`](#LicenseController-getAuthorizationStatus-address-)
* [`_isValidCall(productId)`](#LicenseController-_isValidCall-uint256-)
* [`_getProduct(id)`](#LicenseController-_getProduct-uint256-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
#### [](#LicenseController-_afterInitialize--)
`_afterInitialize()` internal
This function is called after the contract is initialized and sets the `_component` variable to the address of the `ComponentController` contract.
#### [](#LicenseController-getAuthorizationStatus-address-)
`getAuthorizationStatus(address productAddress) → uint256 productId, bool isAuthorized, address policyFlow` public
Returns the authorization status of a given product address.
#### [](#LicenseController-_isValidCall-uint256-)
`_isValidCall(uint256 productId) → bool` internal
Checks if a product is currently active.
#### [](#LicenseController-_getProduct-uint256-)
`_getProduct(uint256 id) → contract IProduct product` internal
Returns the product associated with the given ID.
The "LicenseController" smart contract serves as a controller for managing licenses in an insurance ecosystem. It implements the ILicense interface and extends the CoreController contract. The contract interacts with the ComponentController contract to retrieve information about products and their authorization status. Functions are available to check the authorization status of a product, validate if a product is active, and retrieve product information. The contract plays a crucial role in managing licenses within the insurance ecosystem.
### [](#PolicyController)
`PolicyController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/PolicyController.sol)
import "@etherisc/gif-contracts/contracts/modules/PolicyController.sol";
The smart contract implements functions for policy operations, including creation, update, cancellation, and retrieval. It also provides functions for claim creation, confirmation, decline, closure, and payout creation. Additionally, it includes functions to process payouts, retrieve metadata and application information, and get the number of claims and payouts associated with a policy. The contract inherits from the `IPolicy` interface and the `CoreController` contract.
State Variables:
* `metadata`: A mapping that stores metadata associated with policy flows.
* `applications`: A mapping that stores insurance applications associated with policy flows.
* `policies`: A mapping that stores policies associated with policy flows.
* `claims`: A nested mapping that stores claims associated with policies.
* `payouts`: A nested mapping that stores payouts associated with policies.
* `payoutCount`: A mapping that stores the count of payouts for each policy flow.
* `_assigendProcessIds`: A counter variable for assigning unique process IDs.
* `_component`: A reference to the `ComponentController` contract.
Overall, these functions provide functionality for creating, managing, and processing claims and payouts within the insurance policy contract.
Functions
* [`_afterInitialize()`](#PolicyController-_afterInitialize--)
* [`createPolicyFlow(owner, productId, data)`](#PolicyController-createPolicyFlow-address-uint256-bytes-)
* [`createApplication(processId, premiumAmount, sumInsuredAmount, data)`](#PolicyController-createApplication-bytes32-uint256-uint256-bytes-)
* [`collectPremium(processId, amount)`](#PolicyController-collectPremium-bytes32-uint256-)
* [`revokeApplication(processId)`](#PolicyController-revokeApplication-bytes32-)
* [`underwriteApplication(processId)`](#PolicyController-underwriteApplication-bytes32-)
* [`declineApplication(processId)`](#PolicyController-declineApplication-bytes32-)
* [`createPolicy(processId)`](#PolicyController-createPolicy-bytes32-)
* [`adjustPremiumSumInsured(processId, expectedPremiumAmount, sumInsuredAmount)`](#PolicyController-adjustPremiumSumInsured-bytes32-uint256-uint256-)
* [`expirePolicy(processId)`](#PolicyController-expirePolicy-bytes32-)
* [`closePolicy(processId)`](#PolicyController-closePolicy-bytes32-)
* [`createClaim(processId, claimAmount, data)`](#PolicyController-createClaim-bytes32-uint256-bytes-)
* [`confirmClaim(processId, claimId, confirmedAmount)`](#PolicyController-confirmClaim-bytes32-uint256-uint256-)
* [`declineClaim(processId, claimId)`](#PolicyController-declineClaim-bytes32-uint256-)
* [`closeClaim(processId, claimId)`](#PolicyController-closeClaim-bytes32-uint256-)
* [`createPayout(processId, claimId, payoutAmount, data)`](#PolicyController-createPayout-bytes32-uint256-uint256-bytes-)
* [`processPayout(processId, payoutId)`](#PolicyController-processPayout-bytes32-uint256-)
* [`getMetadata(processId)`](#PolicyController-getMetadata-bytes32-)
* [`getApplication(processId)`](#PolicyController-getApplication-bytes32-)
* [`getNumberOfClaims(processId)`](#PolicyController-getNumberOfClaims-bytes32-)
* [`getNumberOfPayouts(processId)`](#PolicyController-getNumberOfPayouts-bytes32-)
* [`getPolicy(processId)`](#PolicyController-getPolicy-bytes32-)
* [`getClaim(processId, claimId)`](#PolicyController-getClaim-bytes32-uint256-)
* [`getPayout(processId, payoutId)`](#PolicyController-getPayout-bytes32-uint256-)
* [`processIds()`](#PolicyController-processIds--)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IPolicy
* [`LogMetadataCreated(owner, processId, productId, state)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogMetadataStateChanged(processId, state)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationCreated(processId, premiumAmount, sumInsuredAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationRevoked(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationUnderwritten(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationDeclined(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPolicyCreated(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPolicyExpired(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPolicyClosed(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPremiumCollected(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationSumInsuredAdjusted(processId, sumInsuredAmountOld, sumInsuredAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogApplicationPremiumAdjusted(processId, premiumAmountOld, premiumAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPolicyPremiumAdjusted(processId, premiumExpectedAmountOld, premiumExpectedAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogClaimCreated(processId, claimId, claimAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogClaimConfirmed(processId, claimId, confirmedAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogClaimDeclined(processId, claimId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogClaimClosed(processId, claimId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPayoutCreated(processId, claimId, payoutId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
* [`LogPayoutProcessed(processId, payoutId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol)
#### [](#PolicyController-_afterInitialize--)
`_afterInitialize()` internal
Internal function that sets the \_component variable to the address of the ComponentController contract.
#### [](#PolicyController-createPolicyFlow-address-uint256-bytes-)
`createPolicyFlow(address owner, uint256 productId, bytes data) → bytes32 processId` external
Creates a new policy flow for a given owner and product.
#### [](#PolicyController-createApplication-bytes32-uint256-uint256-bytes-)
`createApplication(bytes32 processId, uint256 premiumAmount, uint256 sumInsuredAmount, bytes data)` external
Creates a new insurance application for a given process ID.
#### [](#PolicyController-collectPremium-bytes32-uint256-)
`collectPremium(bytes32 processId, uint256 amount)` external
Collects premium for a policy.
#### [](#PolicyController-revokeApplication-bytes32-)
`revokeApplication(bytes32 processId)` external
Revokes an application with the given process ID.
#### [](#PolicyController-underwriteApplication-bytes32-)
`underwriteApplication(bytes32 processId)` external
Changes the state of an application to underwritten.
#### [](#PolicyController-declineApplication-bytes32-)
`declineApplication(bytes32 processId)` external
Declines an application for a policy flow.
#### [](#PolicyController-createPolicy-bytes32-)
`createPolicy(bytes32 processId)` external
Creates a new policy for a given application process ID.
#### [](#PolicyController-adjustPremiumSumInsured-bytes32-uint256-uint256-)
`adjustPremiumSumInsured(bytes32 processId, uint256 expectedPremiumAmount, uint256 sumInsuredAmount)` external
This function adjusts the premium and sum insured amount of an insurance policy application.
#### [](#PolicyController-expirePolicy-bytes32-)
`expirePolicy(bytes32 processId)` external
This function expires a policy with the given process ID.
#### [](#PolicyController-closePolicy-bytes32-)
`closePolicy(bytes32 processId)` external
Closes a policy that has expired and has no open claims.
#### [](#PolicyController-createClaim-bytes32-uint256-bytes-)
`createClaim(bytes32 processId, uint256 claimAmount, bytes data) → uint256 claimId` external
Creates a new claim for a given policy.
#### [](#PolicyController-confirmClaim-bytes32-uint256-uint256-)
`confirmClaim(bytes32 processId, uint256 claimId, uint256 confirmedAmount)` external
Confirms a claim for a policy, updating the claim state to Confirmed and setting the confirmed amount.
#### [](#PolicyController-declineClaim-bytes32-uint256-)
`declineClaim(bytes32 processId, uint256 claimId)` external
This function allows the Policy contract to decline a claim.
#### [](#PolicyController-closeClaim-bytes32-uint256-)
`closeClaim(bytes32 processId, uint256 claimId)` external
Closes a claim for a given policy.
#### [](#PolicyController-createPayout-bytes32-uint256-uint256-bytes-)
`createPayout(bytes32 processId, uint256 claimId, uint256 payoutAmount, bytes data) → uint256 payoutId` external
Creates a new payout for a confirmed claim in a policy.
#### [](#PolicyController-processPayout-bytes32-uint256-)
`processPayout(bytes32 processId, uint256 payoutId)` external
Processes a payout for a policy and claim.
#### [](#PolicyController-getMetadata-bytes32-)
`getMetadata(bytes32 processId) → struct IPolicy.Metadata _metadata` public
Returns the metadata for the given process ID.
#### [](#PolicyController-getApplication-bytes32-)
`getApplication(bytes32 processId) → struct IPolicy.Application application` public
Returns the application associated with the provided process ID.
#### [](#PolicyController-getNumberOfClaims-bytes32-)
`getNumberOfClaims(bytes32 processId) → uint256 numberOfClaims` external
Returns the number of claims associated with a given process ID.
#### [](#PolicyController-getNumberOfPayouts-bytes32-)
`getNumberOfPayouts(bytes32 processId) → uint256 numberOfPayouts` external
Returns the number of payouts for a given process ID.
#### [](#PolicyController-getPolicy-bytes32-)
`getPolicy(bytes32 processId) → struct IPolicy.Policy policy` public
Returns the policy associated with the given process ID.
#### [](#PolicyController-getClaim-bytes32-uint256-)
`getClaim(bytes32 processId, uint256 claimId) → struct IPolicy.Claim claim` public
Returns the claim with the given ID for the specified process.
#### [](#PolicyController-getPayout-bytes32-uint256-)
`getPayout(bytes32 processId, uint256 payoutId) → struct IPolicy.Payout payout` public
Retrieves a specific payout from a process.
#### [](#PolicyController-processIds--)
`processIds() → uint256` external
Returns the number of process IDs that have been assigned.
The "PolicyController" smart contract implements functions for policy operations, such as creation, update, cancellation, and retrieval. It also handles claim creation, confirmation, decline, closure, and payout creation. The contract includes mappings to store policies, claims, payouts, and metadata associated with policy flows. It inherits from the IPolicy interface and the CoreController contract. The functions validate inputs, update states, and emit events to manage the lifecycle of policies, claims, and payouts. The contract provides comprehensive functionality for managing insurance policies and associated operations.
### [](#PoolController)
`PoolController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/PoolController.sol)
import "@etherisc/gif-contracts/contracts/modules/PoolController.sol";
The smart contract manages riskpools, their registration, funding, defunding, collateralization, and other related operations.
* The contract implements the IPool interface and extends the CoreController contract.
* It imports other contracts such as ComponentController, PolicyController, BundleController, and CoreController.
* It uses the EnumerableSet library from OpenZeppelin for managing sets of bundle IDs.
* The contract defines constants for full collateralization level, collateralization level cap, and default maximum number of active bundles.
* It maintains mappings to store riskpool information, riskpool IDs for products, maximum number of active bundles for riskpools, and active bundle IDs for riskpools.
* The contract has a private array to store riskpool IDs.
* It has references to other contracts: ComponentController, PolicyController, and BundleController.
* The contract defines modifiers for access control to specific functions.
Overall, the PoolController contract provides functionality to manage riskpools, register riskpools, collateralize policies, process premium payments, process payouts, and release collaterals. It acts as an intermediary between the PolicyController, ComponentController, and BundleController contracts to coordinate these operations.
Modifiers
* [`onlyInstanceOperatorService()`](#PoolController-onlyInstanceOperatorService--)
* [`onlyRiskpoolService()`](#PoolController-onlyRiskpoolService--)
* [`onlyActivePool(riskpoolId)`](#PoolController-onlyActivePool-uint256-)
* [`onlyActivePoolForProcess(processId)`](#PoolController-onlyActivePoolForProcess-bytes32-)
Functions
* [`_afterInitialize()`](#PoolController-_afterInitialize--)
* [`registerRiskpool(riskpoolId, wallet, erc20Token, collateralizationLevel, sumOfSumInsuredCap)`](#PoolController-registerRiskpool-uint256-address-address-uint256-uint256-)
* [`setRiskpoolForProduct(productId, riskpoolId)`](#PoolController-setRiskpoolForProduct-uint256-uint256-)
* [`fund(riskpoolId, amount)`](#PoolController-fund-uint256-uint256-)
* [`defund(riskpoolId, amount)`](#PoolController-defund-uint256-uint256-)
* [`underwrite(processId)`](#PoolController-underwrite-bytes32-)
* [`calculateCollateral(riskpoolId, sumInsuredAmount)`](#PoolController-calculateCollateral-uint256-uint256-)
* [`processPremium(processId, amount)`](#PoolController-processPremium-bytes32-uint256-)
* [`processPayout(processId, amount)`](#PoolController-processPayout-bytes32-uint256-)
* [`release(processId)`](#PoolController-release-bytes32-)
* [`setMaximumNumberOfActiveBundles(riskpoolId, maxNumberOfActiveBundles)`](#PoolController-setMaximumNumberOfActiveBundles-uint256-uint256-)
* [`getMaximumNumberOfActiveBundles(riskpoolId)`](#PoolController-getMaximumNumberOfActiveBundles-uint256-)
* [`riskpools()`](#PoolController-riskpools--)
* [`getRiskpool(riskpoolId)`](#PoolController-getRiskpool-uint256-)
* [`getRiskPoolForProduct(productId)`](#PoolController-getRiskPoolForProduct-uint256-)
* [`activeBundles(riskpoolId)`](#PoolController-activeBundles-uint256-)
* [`getActiveBundleId(riskpoolId, bundleIdx)`](#PoolController-getActiveBundleId-uint256-uint256-)
* [`addBundleIdToActiveSet(riskpoolId, bundleId)`](#PoolController-addBundleIdToActiveSet-uint256-uint256-)
* [`removeBundleIdFromActiveSet(riskpoolId, bundleId)`](#PoolController-removeBundleIdFromActiveSet-uint256-uint256-)
* [`getFullCollateralizationLevel()`](#PoolController-getFullCollateralizationLevel--)
* [`_getRiskpoolComponent(metadata)`](#PoolController-_getRiskpoolComponent-struct-IPolicy-Metadata-)
* [`_getRiskpoolForId(riskpoolId)`](#PoolController-_getRiskpoolForId-uint256-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IPool
* [`LogRiskpoolRegistered(riskpoolId, wallet, erc20Token, collateralizationLevel, sumOfSumInsuredCap)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPool.sol)
* [`LogRiskpoolRequiredCollateral(processId, sumInsured, collateral)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPool.sol)
* [`LogRiskpoolCollateralizationFailed(riskpoolId, processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPool.sol)
* [`LogRiskpoolCollateralizationSucceeded(riskpoolId, processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPool.sol)
* [`LogRiskpoolCollateralReleased(riskpoolId, processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPool.sol)
#### [](#PoolController-onlyInstanceOperatorService--)
`onlyInstanceOperatorService()` modifier
#### [](#PoolController-onlyRiskpoolService--)
`onlyRiskpoolService()` modifier
#### [](#PoolController-onlyActivePool-uint256-)
`onlyActivePool(uint256 riskpoolId)` modifier
#### [](#PoolController-onlyActivePoolForProcess-bytes32-)
`onlyActivePoolForProcess(bytes32 processId)` modifier
#### [](#PoolController-_afterInitialize--)
`_afterInitialize()` internal
This function is called after the contract is initialized and sets the addresses of the ComponentController, PolicyController, and BundleController contracts.
#### [](#PoolController-registerRiskpool-uint256-address-address-uint256-uint256-)
`registerRiskpool(uint256 riskpoolId, address wallet, address erc20Token, uint256 collateralizationLevel, uint256 sumOfSumInsuredCap)` external
Registers a new riskpool with the given parameters.
#### [](#PoolController-setRiskpoolForProduct-uint256-uint256-)
`setRiskpoolForProduct(uint256 productId, uint256 riskpoolId)` external
Sets the riskpool ID for a given product ID.
#### [](#PoolController-fund-uint256-uint256-)
`fund(uint256 riskpoolId, uint256 amount)` external
Adds funds to a specific riskpool.
#### [](#PoolController-defund-uint256-uint256-)
`defund(uint256 riskpoolId, uint256 amount)` external
Allows the Riskpool service to defund the specified Riskpool by the given amount.
#### [](#PoolController-underwrite-bytes32-)
`underwrite(bytes32 processId) → bool success` external
Underwrites a policy application by calculating the required collateral amount and asking the responsible riskpool to secure the application.
#### [](#PoolController-calculateCollateral-uint256-uint256-)
`calculateCollateral(uint256 riskpoolId, uint256 sumInsuredAmount) → uint256 collateralAmount` public
Calculates the required collateral amount for a given riskpool and sum insured amount.
#### [](#PoolController-processPremium-bytes32-uint256-)
`processPremium(bytes32 processId, uint256 amount)` external
Processes the premium payment for a policy.
#### [](#PoolController-processPayout-bytes32-uint256-)
`processPayout(bytes32 processId, uint256 amount)` external
Process a payout for a policy flow in the Pool.
#### [](#PoolController-release-bytes32-)
`release(bytes32 processId)` external
Releases a policy’s collateral from the riskpool.
#### [](#PoolController-setMaximumNumberOfActiveBundles-uint256-uint256-)
`setMaximumNumberOfActiveBundles(uint256 riskpoolId, uint256 maxNumberOfActiveBundles)` external
Sets the maximum number of active bundles for a given riskpool ID.
#### [](#PoolController-getMaximumNumberOfActiveBundles-uint256-)
`getMaximumNumberOfActiveBundles(uint256 riskpoolId) → uint256 maximumNumberOfActiveBundles` public
Returns the maximum number of active bundles for a given riskpool ID.
#### [](#PoolController-riskpools--)
`riskpools() → uint256 idx` external
Returns the number of risk pools created.
#### [](#PoolController-getRiskpool-uint256-)
`getRiskpool(uint256 riskpoolId) → struct IPool.Pool riskPool` public
Returns the risk pool data for a given risk pool ID.
#### [](#PoolController-getRiskPoolForProduct-uint256-)
`getRiskPoolForProduct(uint256 productId) → uint256 riskpoolId` external
Returns the risk pool ID associated with the given product ID.
#### [](#PoolController-activeBundles-uint256-)
`activeBundles(uint256 riskpoolId) → uint256 numberOfActiveBundles` external
Returns the number of active bundles for a given risk pool ID.
#### [](#PoolController-getActiveBundleId-uint256-uint256-)
`getActiveBundleId(uint256 riskpoolId, uint256 bundleIdx) → uint256 bundleId` external
Returns the active bundle ID at the specified index for the given risk pool ID.
#### [](#PoolController-addBundleIdToActiveSet-uint256-uint256-)
`addBundleIdToActiveSet(uint256 riskpoolId, uint256 bundleId)` external
Adds a bundle ID to the active set for a specific riskpool ID.
#### [](#PoolController-removeBundleIdFromActiveSet-uint256-uint256-)
`removeBundleIdFromActiveSet(uint256 riskpoolId, uint256 bundleId)` external
Removes a bundle ID from the active set for a given risk pool ID.
#### [](#PoolController-getFullCollateralizationLevel--)
`getFullCollateralizationLevel() → uint256` external
Returns the full collateralization level of the contract.
#### [](#PoolController-_getRiskpoolComponent-struct-IPolicy-Metadata-)
`_getRiskpoolComponent(struct IPolicy.Metadata metadata) → contract IRiskpool riskpool` internal
Returns the Riskpool contract instance associated with the given policy metadata.
#### [](#PoolController-_getRiskpoolForId-uint256-)
`_getRiskpoolForId(uint256 riskpoolId) → contract IRiskpool riskpool` internal
Returns the Riskpool contract instance for a given riskpoolId.
The "PoolController" smart contract manages riskpools and their operations, including registration, funding, defunding, collateralization, and more. It interacts with other contracts such as ComponentController, PolicyController, and BundleController. The contract maintains mappings to store riskpool information and handles functions for funding, defunding, underwriting, calculating collateral, processing premiums and payouts, and releasing collateral. It ensures access control through modifiers and emits events to track the success or failure of operations. The PoolController contract acts as a central component for coordinating riskpool-related operations within the ecosystem.
### [](#QueryModule)
`QueryModule`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/QueryModule.sol)
import "@etherisc/gif-contracts/contracts/modules/QueryModule.sol";
The smart contract implements the "IQuery" interface and extends the "CoreController" contract. The contract imports several external contracts from the "etherisc/gif-interface" repository, including "IComponent.sol", "IOracle.sol", "IQuery.sol", and "IInstanceService.sol". It also imports two local contracts, "ComponentController.sol" and "CoreController.sol".
The contract defines a private variable `_component` of type "ComponentController" and an array `_oracleRequests` of type "OracleRequest\[\]".
The contract includes two modifiers:
1. `onlyOracleService`: It requires that the caller must be the contract with the address specified by the "OracleService" contract address stored in the CoreController.
2. `onlyResponsibleOracle`: It checks if the oracle specified by the `responder` address is responsible for the given `requestId`.
The contract emits the following events:
1. `LogOracleRequested`: Indicates the creation of a new oracle request and includes the process ID, request ID, and responsible oracle ID.
2. `LogOracleResponded`: Indicates the response to an oracle request and includes the process ID, request ID, responder address, and success status.
3. `LogOracleCanceled`: Indicates the cancellation of an oracle request and includes the request ID.
Modifiers
* [`onlyOracleService()`](#QueryModule-onlyOracleService--)
* [`onlyResponsibleOracle(requestId, responder)`](#QueryModule-onlyResponsibleOracle-uint256-address-)
Functions
* [`_afterInitialize()`](#QueryModule-_afterInitialize--)
* [`request(processId, input, callbackMethodName, callbackContractAddress, responsibleOracleId)`](#QueryModule-request-bytes32-bytes-string-address-uint256-)
* [`respond(requestId, responder, data)`](#QueryModule-respond-uint256-address-bytes-)
* [`cancel(requestId)`](#QueryModule-cancel-uint256-)
* [`getProcessId(requestId)`](#QueryModule-getProcessId-uint256-)
* [`getOracleRequestCount()`](#QueryModule-getOracleRequestCount--)
* [`_getOracle(id)`](#QueryModule-_getOracle-uint256-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IQuery
* [`LogOracleRequested(processId, requestId, responsibleOracleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IQuery.sol)
* [`LogOracleResponded(processId, requestId, responder, success)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IQuery.sol)
* [`LogOracleCanceled(requestId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IQuery.sol)
#### [](#QueryModule-onlyOracleService--)
`onlyOracleService()` modifier
#### [](#QueryModule-onlyResponsibleOracle-uint256-address-)
`onlyResponsibleOracle(uint256 requestId, address responder)` modifier
#### [](#QueryModule-_afterInitialize--)
`_afterInitialize()` internal
Internal function that sets the `_component` variable to the `ComponentController` contract address.
#### [](#QueryModule-request-bytes32-bytes-string-address-uint256-)
`request(bytes32 processId, bytes input, string callbackMethodName, address callbackContractAddress, uint256 responsibleOracleId) → uint256 requestId` external
Creates a new oracle request for a given process with the specified input data and callback information.
#### [](#QueryModule-respond-uint256-address-bytes-)
`respond(uint256 requestId, address responder, bytes data)` external
Responds to an oracle request with the given requestId, responder address, and data.
#### [](#QueryModule-cancel-uint256-)
`cancel(uint256 requestId)` external
Cancels an oracle request.
#### [](#QueryModule-getProcessId-uint256-)
`getProcessId(uint256 requestId) → bytes32 processId` external
Returns the process ID associated with a given request ID.
#### [](#QueryModule-getOracleRequestCount--)
`getOracleRequestCount() → uint256 _count` public
Returns the number of oracle requests made.
#### [](#QueryModule-_getOracle-uint256-)
`_getOracle(uint256 id) → contract IOracle oracle` internal
Returns the Oracle component with the specified ID.
The "QueryModule" smart contract implements the IQuery interface and extends the CoreController contract. It interacts with external contracts such as IComponent.sol, IOracle.sol, IQuery.sol, and IInstanceService.sol. The contract allows the creation of oracle requests, enables oracles to respond to requests, cancels requests, and provides functions to retrieve information about requests and oracles. It ensures access control through modifiers and emits events to track the creation, response, and cancellation of oracle requests. The QueryModule contract acts as a module for managing oracle queries within the ecosystem.
### [](#RegistryController)
`RegistryController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/RegistryController.sol)
import "@etherisc/gif-contracts/contracts/modules/RegistryController.sol";
The smart contract implements the `IRegistry` interface and inherits from the `CoreController` contract. The contract provides functionality for registering, deregistering, and accessing contracts within different releases. It maintains mappings and sets to store contract names and addresses in different releases.
* `MAX_CONTRACTS`: A constant variable set to 100, representing the maximum number of contracts allowed in a release.
* `release`: A bytes32 variable representing the current release identifier.
* `startBlock`: An unsigned integer storing the block number at which the contract was deployed.
* `_contracts`: A nested mapping that stores contract addresses based on the release and contract name.
* `_contractsInRelease`: A mapping that keeps track of the number of contracts in each release.
* `_contractNames`: A private EnumerableSet that stores the names of contracts in a specific release.
The contract emits various events such as `LogContractRegistered` and `LogContractDeregistered` to notify when contracts are registered or deregistered.
Overall, the `RegistryController` contract provides a mechanism to manage and track contracts within different releases, allowing for controlled registration and deregistration of contracts.
Functions
* [`initializeRegistry(_initialRelease)`](#RegistryController-initializeRegistry-bytes32-)
* [`ensureSender(sender, _contractName)`](#RegistryController-ensureSender-address-bytes32-)
* [`getRelease()`](#RegistryController-getRelease--)
* [`getContract(_contractName)`](#RegistryController-getContract-bytes32-)
* [`register(_contractName, _contractAddress)`](#RegistryController-register-bytes32-address-)
* [`deregister(_contractName)`](#RegistryController-deregister-bytes32-)
* [`getContractInRelease(_release, _contractName)`](#RegistryController-getContractInRelease-bytes32-bytes32-)
* [`registerInRelease(_release, _contractName, _contractAddress)`](#RegistryController-registerInRelease-bytes32-bytes32-address-)
* [`deregisterInRelease(_release, _contractName)`](#RegistryController-deregisterInRelease-bytes32-bytes32-)
* [`prepareRelease(_newRelease)`](#RegistryController-prepareRelease-bytes32-)
* [`contracts()`](#RegistryController-contracts--)
* [`contractName(idx)`](#RegistryController-contractName-uint256-)
* [`_getContractInRelease(_release, _contractName)`](#RegistryController-_getContractInRelease-bytes32-bytes32-)
* [`_registerInRelease(_release, isNewRelease, _contractName, _contractAddress)`](#RegistryController-_registerInRelease-bytes32-bool-bytes32-address-)
* [`_deregisterInRelease(_release, _contractName)`](#RegistryController-_deregisterInRelease-bytes32-bytes32-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_afterInitialize()`](shared#CoreController-_afterInitialize--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IRegistry
* [`LogContractRegistered(release, contractName, contractAddress, isNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
* [`LogContractDeregistered(release, contractName)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
* [`LogReleasePrepared(release)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
#### [](#RegistryController-initializeRegistry-bytes32-)
`initializeRegistry(bytes32 _initialRelease)` public
Initializes the GIF registry with an initial release and sets the deployment block for reading logs.
#### [](#RegistryController-ensureSender-address-bytes32-)
`ensureSender(address sender, bytes32 _contractName) → bool _senderMatches` external
Verifies if the provided 'sender' address matches the address of the contract with the given '\_contractName' in the current release.
#### [](#RegistryController-getRelease--)
`getRelease() → bytes32 _release` external
Returns the current release identifier.
#### [](#RegistryController-getContract-bytes32-)
`getContract(bytes32 _contractName) → address _addr` public
Returns the address of a contract by its name.
#### [](#RegistryController-register-bytes32-address-)
`register(bytes32 _contractName, address _contractAddress)` external
Registers a contract with a given name and address.
#### [](#RegistryController-deregister-bytes32-)
`deregister(bytes32 _contractName)` external
Deregisters a contract from the current release.
#### [](#RegistryController-getContractInRelease-bytes32-bytes32-)
`getContractInRelease(bytes32 _release, bytes32 _contractName) → address _addr` external
Returns the address of a specific contract within a given release.
#### [](#RegistryController-registerInRelease-bytes32-bytes32-address-)
`registerInRelease(bytes32 _release, bytes32 _contractName, address _contractAddress)` external
Registers a contract in a specific release.
#### [](#RegistryController-deregisterInRelease-bytes32-bytes32-)
`deregisterInRelease(bytes32 _release, bytes32 _contractName)` external
Deregisters a contract name from a specific release.
#### [](#RegistryController-prepareRelease-bytes32-)
`prepareRelease(bytes32 _newRelease)` external
Prepares a new release by copying all contracts from the current release to the new one.
#### [](#RegistryController-contracts--)
`contracts() → uint256 _numberOfContracts` external
Returns the number of contracts in the current release.
#### [](#RegistryController-contractName-uint256-)
`contractName(uint256 idx) → bytes32 _contractName` external
Returns the name of the contract at the specified index in the contractNames set.
#### [](#RegistryController-_getContractInRelease-bytes32-bytes32-)
`_getContractInRelease(bytes32 _release, bytes32 _contractName) → address _addr` internal
Returns the address of a contract in a specific release.
#### [](#RegistryController-_registerInRelease-bytes32-bool-bytes32-address-)
`_registerInRelease(bytes32 _release, bool isNewRelease, bytes32 _contractName, address _contractAddress)` internal
Registers a contract in a release.
#### [](#RegistryController-_deregisterInRelease-bytes32-bytes32-)
`_deregisterInRelease(bytes32 _release, bytes32 _contractName)` internal
Internal function to deregister a contract in a specific release.
The "RegistryController" smart contract implements the IRegistry interface and inherits from the CoreController contract. It facilitates the registration, deregistration, and access of contracts within different releases. The contract maintains mappings and sets to store contract names and addresses in various releases. It provides functions to register and deregister contracts, retrieve contract addresses, and manage releases. The contract ensures sender verification and emits events to track contract registration and deregistration. The RegistryController contract serves as a centralized registry for managing contracts in different releases within the ecosystem.
### [](#TreasuryModule)
`TreasuryModule`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/modules/TreasuryModule.sol)
import "@etherisc/gif-contracts/contracts/modules/TreasuryModule.sol";
The smart contract implements the ITreasury interface and inherits from the CoreController and Pausable contracts. The contract imports several other contracts and interfaces, including ComponentController.sol, PolicyController.sol, BundleController.sol, PoolController.sol, CoreController.sol, TransferHelper.sol, and various interfaces from the "etherisc/gif-interface" and "openzeppelin/contracts" libraries.
The contract defines several state variables, including:
* FRACTION\_FULL\_UNIT: a constant representing the full unit value (10^18).
* FRACTIONAL\_FEE\_MAX: a constant representing the maximum fractional fee value (25%).
* event LogTransferHelperInputValidation1Failed: an event that logs a failed input validation.
* event LogTransferHelperInputValidation2Failed: an event that logs a failed input validation.
* event LogTransferHelperCallFailed: an event that logs a failed external call.
* \_instanceWalletAddress: a private variable representing the address of the instance wallet.
* \_riskpoolWallet: a mapping of riskpool IDs to wallet addresses.
* \_fees: a mapping of component IDs to FeeSpecification structs.
* \_componentToken: a mapping of product IDs/riskpool IDs to ERC20 token addresses.
* \_bundle: an instance of the BundleController contract.
* \_component: an instance of the ComponentController contract.
* \_policy: an instance of the PolicyController contract.
* \_pool: an instance of the PoolController contract.
The contract includes several modifiers that enforce certain conditions on function execution, such as the instanceWalletDefined modifier, which requires the instance wallet address to be defined; the riskpoolWalletDefinedForProcess modifier, which requires the riskpool wallet address to be defined for a given process ID; the riskpoolWalletDefinedForBundle modifier, which requires the riskpool wallet address to be defined for a given bundle ID; the whenNotSuspended modifier, which requires the contract to not be paused; and the onlyRiskpoolService modifier, which restricts access to the RiskpoolService contract.
The contract contains various functions for managing the treasury, such as setting the product token address, setting the instance wallet address, setting the riskpool wallet address, creating fee specifications, and setting premium and capital fees for components. There are also functions for suspending and resuming the treasury contract.
The contract includes a function to calculate the fee amount and net amount for a given component ID and amount. It also includes functions to process premium payments for policies, either for the remaining premium amount or for a specific amount.
Overall, the TreasuryModule contract provides functionality for managing fees, processing premium payments, and interacting with other controllers and contracts in the system.
Modifiers
* [`instanceWalletDefined()`](#TreasuryModule-instanceWalletDefined--)
* [`riskpoolWalletDefinedForProcess(processId)`](#TreasuryModule-riskpoolWalletDefinedForProcess-bytes32-)
* [`riskpoolWalletDefinedForBundle(bundleId)`](#TreasuryModule-riskpoolWalletDefinedForBundle-uint256-)
* [`whenNotSuspended()`](#TreasuryModule-whenNotSuspended--)
* [`onlyRiskpoolService()`](#TreasuryModule-onlyRiskpoolService--)
Functions
* [`_afterInitialize()`](#TreasuryModule-_afterInitialize--)
* [`suspend()`](#TreasuryModule-suspend--)
* [`resume()`](#TreasuryModule-resume--)
* [`setProductToken(productId, erc20Address)`](#TreasuryModule-setProductToken-uint256-address-)
* [`setInstanceWallet(instanceWalletAddress)`](#TreasuryModule-setInstanceWallet-address-)
* [`setRiskpoolWallet(riskpoolId, riskpoolWalletAddress)`](#TreasuryModule-setRiskpoolWallet-uint256-address-)
* [`createFeeSpecification(componentId, fixedFee, fractionalFee, feeCalculationData)`](#TreasuryModule-createFeeSpecification-uint256-uint256-uint256-bytes-)
* [`setPremiumFees(feeSpec)`](#TreasuryModule-setPremiumFees-struct-ITreasury-FeeSpecification-)
* [`setCapitalFees(feeSpec)`](#TreasuryModule-setCapitalFees-struct-ITreasury-FeeSpecification-)
* [`calculateFee(componentId, amount)`](#TreasuryModule-calculateFee-uint256-uint256-)
* [`processPremium(processId)`](#TreasuryModule-processPremium-bytes32-)
* [`processPremium(processId, amount)`](#TreasuryModule-processPremium-bytes32-uint256-)
* [`processPayout(processId, payoutId)`](#TreasuryModule-processPayout-bytes32-uint256-)
* [`processCapital(bundleId, capitalAmount)`](#TreasuryModule-processCapital-uint256-uint256-)
* [`processWithdrawal(bundleId, amount)`](#TreasuryModule-processWithdrawal-uint256-uint256-)
* [`getComponentToken(componentId)`](#TreasuryModule-getComponentToken-uint256-)
* [`getFeeSpecification(componentId)`](#TreasuryModule-getFeeSpecification-uint256-)
* [`getFractionFullUnit()`](#TreasuryModule-getFractionFullUnit--)
* [`getInstanceWallet()`](#TreasuryModule-getInstanceWallet--)
* [`getRiskpoolWallet(riskpoolId)`](#TreasuryModule-getRiskpoolWallet-uint256-)
* [`_calculatePremiumFee(feeSpec, processId)`](#TreasuryModule-_calculatePremiumFee-struct-ITreasury-FeeSpecification-bytes32-)
* [`_calculateFee(feeSpec, amount)`](#TreasuryModule-_calculateFee-struct-ITreasury-FeeSpecification-uint256-)
* [`_getRiskpoolWallet(processId)`](#TreasuryModule-_getRiskpoolWallet-bytes32-)
Pausable
* [`paused()`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-paused--)
* [`_requireNotPaused()`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-_requireNotPaused--)
* [`_requirePaused()`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-_requirePaused--)
* [`_pause()`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-_pause--)
* [`_unpause()`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-_unpause--)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
* [`LogTransferHelperInputValidation1Failed(tokenIsContract, from, to)`](#TreasuryModule-LogTransferHelperInputValidation1Failed-bool-address-address-)
* [`LogTransferHelperInputValidation2Failed(balance, allowance)`](#TreasuryModule-LogTransferHelperInputValidation2Failed-uint256-uint256-)
* [`LogTransferHelperCallFailed(callSuccess, returnDataLength, returnData)`](#TreasuryModule-LogTransferHelperCallFailed-bool-uint256-bytes-)
Pausable
* [`Paused(account)`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-Paused-address-)
* [`Unpaused(account)`](https://docs.openzeppelin.com/contracts/3.x/api/security#Pausable-Unpaused-address-)
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
ITreasury
* [`LogTreasurySuspended()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryResumed()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryProductTokenSet(productId, riskpoolId, erc20Address)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryInstanceWalletSet(walletAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryRiskpoolWalletSet(riskpoolId, walletAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryPremiumFeesSet(productId, fixedFee, fractionalFee)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryCapitalFeesSet(riskpoolId, fixedFee, fractionalFee)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryPremiumTransferred(from, riskpoolWalletAddress, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryPayoutTransferred(riskpoolWalletAddress, to, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryCapitalTransferred(from, riskpoolWalletAddress, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryFeesTransferred(from, instanceWalletAddress, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryWithdrawalTransferred(riskpoolWalletAddress, to, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryPremiumProcessed(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryPayoutProcessed(riskpoolId, to, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryCapitalProcessed(riskpoolId, bundleId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
* [`LogTreasuryWithdrawalProcessed(riskpoolId, bundleId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/ITreasury.sol)
#### [](#TreasuryModule-instanceWalletDefined--)
`instanceWalletDefined()` modifier
#### [](#TreasuryModule-riskpoolWalletDefinedForProcess-bytes32-)
`riskpoolWalletDefinedForProcess(bytes32 processId)` modifier
#### [](#TreasuryModule-riskpoolWalletDefinedForBundle-uint256-)
`riskpoolWalletDefinedForBundle(uint256 bundleId)` modifier
#### [](#TreasuryModule-whenNotSuspended--)
`whenNotSuspended()` modifier
#### [](#TreasuryModule-onlyRiskpoolService--)
`onlyRiskpoolService()` modifier
#### [](#TreasuryModule-_afterInitialize--)
`_afterInitialize()` internal
Sets the addresses of the BundleController, ComponentController, PolicyController, and PoolController contracts.
#### [](#TreasuryModule-suspend--)
`suspend()` external
Suspends the treasury contract, preventing any further transfers or withdrawals. Can only be called by the instance operator.
#### [](#TreasuryModule-resume--)
`resume()` external
Resumes the treasury contract after it has been paused.
#### [](#TreasuryModule-setProductToken-uint256-address-)
`setProductToken(uint256 productId, address erc20Address)` external
Sets the ERC20 token address for a given product ID and its associated risk pool.
#### [](#TreasuryModule-setInstanceWallet-address-)
`setInstanceWallet(address instanceWalletAddress)` external
Sets the address of the instance wallet.
#### [](#TreasuryModule-setRiskpoolWallet-uint256-address-)
`setRiskpoolWallet(uint256 riskpoolId, address riskpoolWalletAddress)` external
Sets the wallet address for a specific riskpool.
#### [](#TreasuryModule-createFeeSpecification-uint256-uint256-uint256-bytes-)
`createFeeSpecification(uint256 componentId, uint256 fixedFee, uint256 fractionalFee, bytes feeCalculationData) → struct ITreasury.FeeSpecification` external
Creates a fee specification for a given component.
#### [](#TreasuryModule-setPremiumFees-struct-ITreasury-FeeSpecification-)
`setPremiumFees(struct ITreasury.FeeSpecification feeSpec)` external
Sets the premium fees for a specific component.
#### [](#TreasuryModule-setCapitalFees-struct-ITreasury-FeeSpecification-)
`setCapitalFees(struct ITreasury.FeeSpecification feeSpec)` external
Sets the fee specification for a given component, which includes the fixed and fractional fees.
#### [](#TreasuryModule-calculateFee-uint256-uint256-)
`calculateFee(uint256 componentId, uint256 amount) → uint256 feeAmount, uint256 netAmount` public
Calculates the fee amount and net amount for a given component ID and amount.
#### [](#TreasuryModule-processPremium-bytes32-)
`processPremium(bytes32 processId) → bool success, uint256 feeAmount, uint256 netPremiumAmount` external
Processes the premium for a given policy process ID.
#### [](#TreasuryModule-processPremium-bytes32-uint256-)
`processPremium(bytes32 processId, uint256 amount) → bool success, uint256 feeAmount, uint256 netAmount` public
Processes a premium payment for a policy.
#### [](#TreasuryModule-processPayout-bytes32-uint256-)
`processPayout(bytes32 processId, uint256 payoutId) → uint256 feeAmount, uint256 netPayoutAmount` external
Processes a payout for a specific process and payout ID.
#### [](#TreasuryModule-processCapital-uint256-uint256-)
`processCapital(uint256 bundleId, uint256 capitalAmount) → uint256 feeAmount, uint256 netCapitalAmount` external
Processes capital for a given bundle ID and calculates fees. Transfers fees to the instance wallet and net capital to the riskpool wallet.
#### [](#TreasuryModule-processWithdrawal-uint256-uint256-)
`processWithdrawal(uint256 bundleId, uint256 amount) → uint256 feeAmount, uint256 netAmount` external
Processes a withdrawal of a specified amount from a bundle, transferring the funds to the bundle owner’s wallet.
#### [](#TreasuryModule-getComponentToken-uint256-)
`getComponentToken(uint256 componentId) → contract IERC20 token` public
Returns the ERC20 token address associated with the given component ID.
#### [](#TreasuryModule-getFeeSpecification-uint256-)
`getFeeSpecification(uint256 componentId) → struct ITreasury.FeeSpecification` public
Returns the fee specification of a given component.
#### [](#TreasuryModule-getFractionFullUnit--)
`getFractionFullUnit() → uint256` public
Returns the value of the constant FRACTION\_FULL\_UNIT.
#### [](#TreasuryModule-getInstanceWallet--)
`getInstanceWallet() → address` public
Returns the address of the instance wallet.
#### [](#TreasuryModule-getRiskpoolWallet-uint256-)
`getRiskpoolWallet(uint256 riskpoolId) → address` public
Returns the wallet address of the specified risk pool.
#### [](#TreasuryModule-_calculatePremiumFee-struct-ITreasury-FeeSpecification-bytes32-)
`_calculatePremiumFee(struct ITreasury.FeeSpecification feeSpec, bytes32 processId) → struct IPolicy.Application application, uint256 feeAmount` internal
Calculates the premium fee for a given fee specification and process ID.
#### [](#TreasuryModule-_calculateFee-struct-ITreasury-FeeSpecification-uint256-)
`_calculateFee(struct ITreasury.FeeSpecification feeSpec, uint256 amount) → uint256 feeAmount` internal
Calculates the fee amount based on the given fee specification and the transaction amount.
#### [](#TreasuryModule-_getRiskpoolWallet-bytes32-)
`_getRiskpoolWallet(bytes32 processId) → uint256 riskpoolId, address riskpoolWalletAddress` internal
Returns the riskpool ID and wallet address for a given process ID.
#### [](#TreasuryModule-LogTransferHelperInputValidation1Failed-bool-address-address-)
`LogTransferHelperInputValidation1Failed(bool tokenIsContract, address from, address to)` event
#### [](#TreasuryModule-LogTransferHelperInputValidation2Failed-uint256-uint256-)
`LogTransferHelperInputValidation2Failed(uint256 balance, uint256 allowance)` event
#### [](#TreasuryModule-LogTransferHelperCallFailed-bool-uint256-bytes-)
`LogTransferHelperCallFailed(bool callSuccess, uint256 returnDataLength, bytes returnData)` event
The "TreasuryModule" smart contract implements the ITreasury interface and inherits from the CoreController and Pausable contracts. It imports various contracts and interfaces to handle treasury operations. The contract defines state variables, including constants, wallet addresses, fee specifications, and instances of other contracts. It includes modifiers to enforce conditions for function execution. The contract provides functions to set token and wallet addresses, create fee specifications, process premium payments, and manage suspension/resumption. It also calculates fee amounts and net amounts. The TreasuryModule contract serves as a central component for managing fees and treasury operations, interacting with other controllers and contracts within the system.
[← Flows](/contracts/2.x/api/flows)
[Services →](/contracts/2.x/api/services)
---
# Test - Etherisc Docs
Test
====
| | |
| --- | --- |
| | This document is better viewed at [https://docs.etherisc.com/contracts/api/test](https://docs.etherisc.com/contracts/api/test) |
[](#contracts)
Contracts
------------------------
### [](#TestCoin)
`TestCoin`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestCoin.sol)
import "@etherisc/gif-contracts/contracts/test/TestCoin.sol";
Functions
* [`constructor()`](#TestCoin-constructor--)
ERC20
* [`name()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-name--)
* [`symbol()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-symbol--)
* [`decimals()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decimals--)
* [`totalSupply()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-totalSupply--)
* [`balanceOf(account)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-balanceOf-address-)
* [`transfer(to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-transfer-address-uint256-)
* [`allowance(owner, spender)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-allowance-address-address-)
* [`approve(spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-approve-address-uint256-)
* [`transferFrom(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-transferFrom-address-address-uint256-)
* [`increaseAllowance(spender, addedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-increaseAllowance-address-uint256-)
* [`decreaseAllowance(spender, subtractedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decreaseAllowance-address-uint256-)
* [`_transfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_transfer-address-address-uint256-)
* [`_mint(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_mint-address-uint256-)
* [`_burn(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_burn-address-uint256-)
* [`_approve(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_approve-address-address-uint256-)
* [`_spendAllowance(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_spendAllowance-address-address-uint256-)
* [`_beforeTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_beforeTokenTransfer-address-address-uint256-)
* [`_afterTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_afterTokenTransfer-address-address-uint256-)
Events
IERC20
* [`Transfer(from, to, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Transfer-address-address-uint256-)
* [`Approval(owner, spender, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Approval-address-address-uint256-)
#### [](#TestCoin-constructor--)
`constructor()` public
Constructor function that initializes the ERC20 token with a given name, symbol, and initial supply.
### [](#TestCoinAlternativeImplementation)
`TestCoinAlternativeImplementation`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestCoinAlternativeImplementation.sol)
import "@etherisc/gif-contracts/contracts/test/TestCoinAlternativeImplementation.sol";
Functions
* [`constructor()`](#TestCoinAlternativeImplementation-constructor--)
* [`transferFrom(_from, _to, _value)`](#TestCoinAlternativeImplementation-transferFrom-address-address-uint256-)
ERC20
* [`name()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-name--)
* [`symbol()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-symbol--)
* [`decimals()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decimals--)
* [`totalSupply()`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-totalSupply--)
* [`balanceOf(account)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-balanceOf-address-)
* [`transfer(to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-transfer-address-uint256-)
* [`allowance(owner, spender)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-allowance-address-address-)
* [`approve(spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-approve-address-uint256-)
* [`increaseAllowance(spender, addedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-increaseAllowance-address-uint256-)
* [`decreaseAllowance(spender, subtractedValue)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-decreaseAllowance-address-uint256-)
* [`_transfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_transfer-address-address-uint256-)
* [`_mint(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_mint-address-uint256-)
* [`_burn(account, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_burn-address-uint256-)
* [`_approve(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_approve-address-address-uint256-)
* [`_spendAllowance(owner, spender, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_spendAllowance-address-address-uint256-)
* [`_beforeTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_beforeTokenTransfer-address-address-uint256-)
* [`_afterTokenTransfer(from, to, amount)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#ERC20-_afterTokenTransfer-address-address-uint256-)
Events
IERC20
* [`Transfer(from, to, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Transfer-address-address-uint256-)
* [`Approval(owner, spender, value)`](https://docs.openzeppelin.com/contracts/3.x/api/token/ERC20#IERC20-Approval-address-address-uint256-)
#### [](#TestCoinAlternativeImplementation-constructor--)
`constructor()` public
Constructor function that creates a new ERC20 token with the given name and symbol, and mints the initial supply to the sender.
#### [](#TestCoinAlternativeImplementation-transferFrom-address-address-uint256-)
`transferFrom(address _from, address _to, uint256 _value) → bool` public
Transfer tokens from one address to another.
### [](#TestCompromisedProduct)
`TestCompromisedProduct`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestCompromisedProduct.sol)
import "@etherisc/gif-contracts/contracts/test/TestCompromisedProduct.sol";
Modifiers
* [`onlyPolicyHolder(policyId)`](#TestCompromisedProduct-onlyPolicyHolder-bytes32-)
Functions
* [`constructor(fakeProductName, tokenAddress, fakeComponentId, fakeRiskpoolId, registryAddress)`](#TestCompromisedProduct-constructor-bytes32-address-uint256-uint256-address-)
* [`applyForPolicy(premium, sumInsured, metaData, applicationData)`](#TestCompromisedProduct-applyForPolicy-uint256-uint256-bytes-bytes-)
* [`collectPremium(policyId)`](#TestCompromisedProduct-collectPremium-bytes32-)
* [`submitClaim(policyId, claimAmount)`](#TestCompromisedProduct-submitClaim-bytes32-uint256-)
* [`getToken()`](#TestCompromisedProduct-getToken--)
* [`getPolicyFlow()`](#TestCompromisedProduct-getPolicyFlow--)
* [`getRiskpoolId()`](#TestCompromisedProduct-getRiskpoolId--)
* [`getApplicationDataStructure()`](#TestCompromisedProduct-getApplicationDataStructure--)
* [`getClaimDataStructure()`](#TestCompromisedProduct-getClaimDataStructure--)
* [`getPayoutDataStructure()`](#TestCompromisedProduct-getPayoutDataStructure--)
* [`riskPoolCapacityCallback(capacity)`](#TestCompromisedProduct-riskPoolCapacityCallback-uint256-)
* [`setId(id)`](#TestCompromisedProduct-setId-uint256-)
* [`getName()`](#TestCompromisedProduct-getName--)
* [`getId()`](#TestCompromisedProduct-getId--)
* [`getType()`](#TestCompromisedProduct-getType--)
* [`getState()`](#TestCompromisedProduct-getState--)
* [`getOwner()`](#TestCompromisedProduct-getOwner--)
* [`getRegistry()`](#TestCompromisedProduct-getRegistry--)
* [`isProduct()`](#TestCompromisedProduct-isProduct--)
* [`isOracle()`](#TestCompromisedProduct-isOracle--)
* [`isRiskpool()`](#TestCompromisedProduct-isRiskpool--)
* [`proposalCallback()`](#TestCompromisedProduct-proposalCallback--)
* [`approvalCallback()`](#TestCompromisedProduct-approvalCallback--)
* [`declineCallback()`](#TestCompromisedProduct-declineCallback--)
* [`suspendCallback()`](#TestCompromisedProduct-suspendCallback--)
* [`resumeCallback()`](#TestCompromisedProduct-resumeCallback--)
* [`pauseCallback()`](#TestCompromisedProduct-pauseCallback--)
* [`unpauseCallback()`](#TestCompromisedProduct-unpauseCallback--)
* [`archiveCallback()`](#TestCompromisedProduct-archiveCallback--)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
Events
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
IProduct
* [`LogProductCreated(productAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductProposed(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductApproved(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductDeclined(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
IComponent
* [`LogComponentCreated(componentName, componentType, componentAddress, registryAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IComponent.sol)
#### [](#TestCompromisedProduct-onlyPolicyHolder-bytes32-)
`onlyPolicyHolder(bytes32 policyId)` modifier
#### [](#TestCompromisedProduct-constructor-bytes32-address-uint256-uint256-address-)
`constructor(bytes32 fakeProductName, address tokenAddress, uint256 fakeComponentId, uint256 fakeRiskpoolId, address registryAddress)` public
Constructor function to initialize the component with the given parameters.
#### [](#TestCompromisedProduct-applyForPolicy-uint256-uint256-bytes-bytes-)
`applyForPolicy(uint256 premium, uint256 sumInsured, bytes metaData, bytes applicationData) → bytes32 processId` external
Allows a policy holder to apply for a new policy by submitting an application with the specified premium, sum insured, metaData, and applicationData.
#### [](#TestCompromisedProduct-collectPremium-bytes32-)
`collectPremium(bytes32 policyId)` external
Collects the premium for a given policy.
#### [](#TestCompromisedProduct-submitClaim-bytes32-uint256-)
`submitClaim(bytes32 policyId, uint256 claimAmount)` external
Allows a policy holder to submit a claim for the specified policy.
#### [](#TestCompromisedProduct-getToken--)
`getToken() → address token` external
Returns the address of the token used by this contract.
#### [](#TestCompromisedProduct-getPolicyFlow--)
`getPolicyFlow() → address policyFlow` external
Returns the address of the policy flow contract.
#### [](#TestCompromisedProduct-getRiskpoolId--)
`getRiskpoolId() → uint256 riskpoolId` external
Returns the ID of the risk pool.
#### [](#TestCompromisedProduct-getApplicationDataStructure--)
`getApplicationDataStructure() → string dataStructure` external
Returns the data structure of the application.
#### [](#TestCompromisedProduct-getClaimDataStructure--)
`getClaimDataStructure() → string dataStructure` external
Returns the data structure of the claim data.
#### [](#TestCompromisedProduct-getPayoutDataStructure--)
`getPayoutDataStructure() → string dataStructure` external
Returns the data structure of the payout information.
#### [](#TestCompromisedProduct-riskPoolCapacityCallback-uint256-)
`riskPoolCapacityCallback(uint256 capacity)` external
Callback function to update the risk pool’s capacity.
#### [](#TestCompromisedProduct-setId-uint256-)
`setId(uint256 id)` external
Sets the ID of the contract.
#### [](#TestCompromisedProduct-getName--)
`getName() → bytes32` external
Returns the name of the component.
#### [](#TestCompromisedProduct-getId--)
`getId() → uint256` external
Returns the ID of the component.
#### [](#TestCompromisedProduct-getType--)
`getType() → enum IComponent.ComponentType` external
Returns the ComponentType of the product.
#### [](#TestCompromisedProduct-getState--)
`getState() → enum IComponent.ComponentState` external
Returns the current state of the component.
#### [](#TestCompromisedProduct-getOwner--)
`getOwner() → address` external
Returns the address of the contract owner.
#### [](#TestCompromisedProduct-getRegistry--)
`getRegistry() → contract IRegistry` external
Returns the current registry contract instance.
#### [](#TestCompromisedProduct-isProduct--)
`isProduct() → bool` public
Checks if the contract is a product.
#### [](#TestCompromisedProduct-isOracle--)
`isOracle() → bool` public
Returns a boolean value indicating whether the contract is an oracle.
#### [](#TestCompromisedProduct-isRiskpool--)
`isRiskpool() → bool` public
Check if the contract is a risk pool.
#### [](#TestCompromisedProduct-proposalCallback--)
`proposalCallback()` external
This function is a callback function for proposals.
Returns: None
#### [](#TestCompromisedProduct-approvalCallback--)
`approvalCallback()` external
This function is a callback function that is called after an approval has been made.
#### [](#TestCompromisedProduct-declineCallback--)
`declineCallback()` external
This function is called when a user declines a transaction in the dApp.
#### [](#TestCompromisedProduct-suspendCallback--)
`suspendCallback()` external
Suspends the callback function.
#### [](#TestCompromisedProduct-resumeCallback--)
`resumeCallback()` external
This function is a callback function that is triggered when a paused contract is resumed.
#### [](#TestCompromisedProduct-pauseCallback--)
`pauseCallback()` external
Callback function that is called when the contract is paused. This function does not take any parameters.
#### [](#TestCompromisedProduct-unpauseCallback--)
`unpauseCallback()` external
This function is called by the owner of the contract to unpause the contract after it has been paused.
#### [](#TestCompromisedProduct-archiveCallback--)
`archiveCallback()` external
This function is a callback function that is executed when a contract is archived.
### [](#TestOracle)
`TestOracle`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestOracle.sol)
import "@etherisc/gif-contracts/contracts/test/TestOracle.sol";
Functions
* [`constructor(oracleName, registry)`](#TestOracle-constructor-bytes32-address-)
* [`request(requestId, input)`](#TestOracle-request-uint256-bytes-)
* [`cancel(requestId)`](#TestOracle-cancel-uint256-)
* [`respond(requestId, isLossEvent)`](#TestOracle-respond-uint256-bool-)
* [`_oracleCalculation(counter)`](#TestOracle-_oracleCalculation-uint256-)
Oracle
* [`_afterApprove()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Oracle.sol)
* [`_afterPropose()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Oracle.sol)
* [`_afterDecline()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Oracle.sol)
* [`_respond(requestId, data)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Oracle.sol)
Component
* [`setId(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getName()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getId()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getType()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getState()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getOwner()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isProduct()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isOracle()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isRiskpool()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getRegistry()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`proposalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`approvalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`declineCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`suspendCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`resumeCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`pauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`unpauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`archiveCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterSuspend()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterResume()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterPause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterUnpause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterArchive()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getAccess()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getInstanceService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getComponentOwnerService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getContractAddress(contractName)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
Events
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
IComponentEvents
* [`LogComponentProposed(componentName, componentType, componentAddress, id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentApproved(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentDeclined(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentSuspended(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentResumed(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentPaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentUnpaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentArchived(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentStateChanged(id, stateOld, stateNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
IOracle
* [`LogOracleCreated(oracleAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IOracle.sol)
* [`LogOracleProposed(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IOracle.sol)
* [`LogOracleApproved(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IOracle.sol)
* [`LogOracleDeclined(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IOracle.sol)
IComponent
* [`LogComponentCreated(componentName, componentType, componentAddress, registryAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IComponent.sol)
#### [](#TestOracle-constructor-bytes32-address-)
`constructor(bytes32 oracleName, address registry)` public
Constructor function for creating an Oracle contract.
#### [](#TestOracle-request-uint256-bytes-)
`request(uint256 requestId, bytes input)` external
Requests data from the oracle contract.
#### [](#TestOracle-cancel-uint256-)
`cancel(uint256 requestId)` external
Cancels a Chainlink request.
#### [](#TestOracle-respond-uint256-bool-)
`respond(uint256 requestId, bool isLossEvent)` public
Responds to an oracle request with a boolean value indicating whether a loss event occurred.
#### [](#TestOracle-_oracleCalculation-uint256-)
`_oracleCalculation(uint256 counter) → bool isLossEvent` internal
Performs an oracle calculation to determine if a loss event occurred.
### [](#TestProduct)
`TestProduct`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestProduct.sol)
import "@etherisc/gif-contracts/contracts/test/TestProduct.sol";
Functions
* [`constructor(productName, tokenAddress, capitalOwner, oracleId, riskpoolId, registryAddress)`](#TestProduct-constructor-bytes32-address-address-uint256-uint256-address-)
* [`applyForPolicy(premium, sumInsured, metaData, applicationData)`](#TestProduct-applyForPolicy-uint256-uint256-bytes-bytes-)
* [`applyForPolicy(policyHolder, premium, sumInsured, metaData, applicationData)`](#TestProduct-applyForPolicy-address-payable-uint256-uint256-bytes-bytes-)
* [`newAppliation(premium, sumInsured, metaData, applicationData)`](#TestProduct-newAppliation-uint256-uint256-bytes-bytes-)
* [`revoke(processId)`](#TestProduct-revoke-bytes32-)
* [`decline(processId)`](#TestProduct-decline-bytes32-)
* [`underwrite(processId)`](#TestProduct-underwrite-bytes32-)
* [`collectPremium(policyId)`](#TestProduct-collectPremium-bytes32-)
* [`collectPremium(policyId, amount)`](#TestProduct-collectPremium-bytes32-uint256-)
* [`adjustPremiumSumInsured(processId, expectedPremiumAmount, sumInsuredAmount)`](#TestProduct-adjustPremiumSumInsured-bytes32-uint256-uint256-)
* [`expire(policyId)`](#TestProduct-expire-bytes32-)
* [`close(policyId)`](#TestProduct-close-bytes32-)
* [`submitClaim(policyId, claimAmount)`](#TestProduct-submitClaim-bytes32-uint256-)
* [`submitClaimNoOracle(policyId, claimAmount)`](#TestProduct-submitClaimNoOracle-bytes32-uint256-)
* [`submitClaimWithDeferredResponse(policyId, claimAmount)`](#TestProduct-submitClaimWithDeferredResponse-bytes32-uint256-)
* [`confirmClaim(policyId, claimId, confirmedAmount)`](#TestProduct-confirmClaim-bytes32-uint256-uint256-)
* [`declineClaim(policyId, claimId)`](#TestProduct-declineClaim-bytes32-uint256-)
* [`closeClaim(policyId, claimId)`](#TestProduct-closeClaim-bytes32-uint256-)
* [`createPayout(policyId, claimId, payoutAmount)`](#TestProduct-createPayout-bytes32-uint256-uint256-)
* [`newPayout(policyId, claimId, payoutAmount)`](#TestProduct-newPayout-bytes32-uint256-uint256-)
* [`processPayout(policyId, payoutId)`](#TestProduct-processPayout-bytes32-uint256-)
* [`oracleCallback(requestId, policyId, responseData)`](#TestProduct-oracleCallback-uint256-bytes32-bytes-)
* [`getClaimId(policyId)`](#TestProduct-getClaimId-bytes32-)
* [`getPayoutId(policyId)`](#TestProduct-getPayoutId-bytes32-)
* [`applications()`](#TestProduct-applications--)
* [`policies()`](#TestProduct-policies--)
* [`claims()`](#TestProduct-claims--)
Product
* [`getToken()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`getPolicyFlow()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`getRiskpoolId()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_afterApprove()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_afterPropose()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_afterDecline()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_newApplication(applicationOwner, premiumAmount, sumInsuredAmount, metaData, applicationData)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_collectPremium(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_collectPremium(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_adjustPremiumSumInsured(processId, expectedPremiumAmount, sumInsuredAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_revoke(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_underwrite(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_decline(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_expire(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_close(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_newClaim(processId, claimAmount, data)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_confirmClaim(processId, claimId, payoutAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_declineClaim(processId, claimId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_closeClaim(processId, claimId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_newPayout(processId, claimId, amount, data)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_processPayout(processId, payoutId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_request(processId, input, callbackMethodName, responsibleOracleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_cancelRequest(requestId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_getMetadata(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_getApplication(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_getPolicy(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_getClaim(processId, claimId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`_getPayout(processId, payoutId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`getApplicationDataStructure()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`getClaimDataStructure()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`getPayoutDataStructure()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
* [`riskPoolCapacityCallback(capacity)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol)
Component
* [`setId(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getName()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getId()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getType()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getState()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getOwner()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isProduct()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isOracle()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isRiskpool()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getRegistry()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`proposalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`approvalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`declineCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`suspendCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`resumeCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`pauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`unpauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`archiveCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterSuspend()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterResume()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterPause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterUnpause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterArchive()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getAccess()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getInstanceService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getComponentOwnerService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getContractAddress(contractName)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
Events
* [`LogTestProductFundingReceived(sender, amount)`](#TestProduct-LogTestProductFundingReceived-address-uint256-)
* [`LogTestOracleCallbackReceived(requestId, policyId, response)`](#TestProduct-LogTestOracleCallbackReceived-uint256-bytes32-bytes-)
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
IComponentEvents
* [`LogComponentProposed(componentName, componentType, componentAddress, id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentApproved(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentDeclined(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentSuspended(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentResumed(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentPaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentUnpaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentArchived(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentStateChanged(id, stateOld, stateNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
IProduct
* [`LogProductCreated(productAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductProposed(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductApproved(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
* [`LogProductDeclined(componentId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IProduct.sol)
IComponent
* [`LogComponentCreated(componentName, componentType, componentAddress, registryAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IComponent.sol)
#### [](#TestProduct-constructor-bytes32-address-address-uint256-uint256-address-)
`constructor(bytes32 productName, address tokenAddress, address capitalOwner, uint256 oracleId, uint256 riskpoolId, address registryAddress)` public
Constructor function for creating a new instance of the Product contract.
#### [](#TestProduct-applyForPolicy-uint256-uint256-bytes-bytes-)
`applyForPolicy(uint256 premium, uint256 sumInsured, bytes metaData, bytes applicationData) → bytes32 processId` external
Allows a policy holder to apply for a new insurance policy by submitting an application with the specified premium, sum insured, metadata and application data.
#### [](#TestProduct-applyForPolicy-address-payable-uint256-uint256-bytes-bytes-)
`applyForPolicy(address payable policyHolder, uint256 premium, uint256 sumInsured, bytes metaData, bytes applicationData) → bytes32 processId` external
Creates a new insurance application and underwrites it if possible.
#### [](#TestProduct-newAppliation-uint256-uint256-bytes-bytes-)
`newAppliation(uint256 premium, uint256 sumInsured, bytes metaData, bytes applicationData) → bytes32 processId` external
Creates a new insurance application.
#### [](#TestProduct-revoke-bytes32-)
`revoke(bytes32 processId)` external
Revokes a process identified by its processId. Only the policy holder can revoke a process.
#### [](#TestProduct-decline-bytes32-)
`decline(bytes32 processId)` external
Declines a specific process by its ID.
#### [](#TestProduct-underwrite-bytes32-)
`underwrite(bytes32 processId)` external
Underwrites a policy for a given process ID.
#### [](#TestProduct-collectPremium-bytes32-)
`collectPremium(bytes32 policyId) → bool success, uint256 fee, uint256 netPremium` external
Collects the premium for a specific policy.
#### [](#TestProduct-collectPremium-bytes32-uint256-)
`collectPremium(bytes32 policyId, uint256 amount) → bool success, uint256 fee, uint256 netPremium` external
Collects the premium for a specific policy.
#### [](#TestProduct-adjustPremiumSumInsured-bytes32-uint256-uint256-)
`adjustPremiumSumInsured(bytes32 processId, uint256 expectedPremiumAmount, uint256 sumInsuredAmount)` external
Adjusts the premium and sum insured amounts for a given process ID.
#### [](#TestProduct-expire-bytes32-)
`expire(bytes32 policyId)` external
Expire a policy by its ID.
#### [](#TestProduct-close-bytes32-)
`close(bytes32 policyId)` external
Closes a policy with the given ID.
#### [](#TestProduct-submitClaim-bytes32-uint256-)
`submitClaim(bytes32 policyId, uint256 claimAmount) → uint256 claimId` external
Allows a policy holder to submit a claim for a specific policy.
#### [](#TestProduct-submitClaimNoOracle-bytes32-uint256-)
`submitClaimNoOracle(bytes32 policyId, uint256 claimAmount) → uint256 claimId` external
Allows a policy holder to submit a claim without the need for an oracle.
#### [](#TestProduct-submitClaimWithDeferredResponse-bytes32-uint256-)
`submitClaimWithDeferredResponse(bytes32 policyId, uint256 claimAmount) → uint256 claimId, uint256 requestId` external
Submits a claim for a specific policy with a deferred response from the oracle. Increases the claims counter and creates a new claim application. Then, requests a response from the oracle via an external call with encoded query data.
#### [](#TestProduct-confirmClaim-bytes32-uint256-uint256-)
`confirmClaim(bytes32 policyId, uint256 claimId, uint256 confirmedAmount)` external
Confirms the amount to be paid out for a specific claim.
#### [](#TestProduct-declineClaim-bytes32-uint256-)
`declineClaim(bytes32 policyId, uint256 claimId)` external
Allows the owner of the contract to decline a claim.
#### [](#TestProduct-closeClaim-bytes32-uint256-)
`closeClaim(bytes32 policyId, uint256 claimId)` external
Closes a specific claim for a given policy.
#### [](#TestProduct-createPayout-bytes32-uint256-uint256-)
`createPayout(bytes32 policyId, uint256 claimId, uint256 payoutAmount) → uint256 payoutId` external
Creates a new payout for a specific policy and claim.
#### [](#TestProduct-newPayout-bytes32-uint256-uint256-)
`newPayout(bytes32 policyId, uint256 claimId, uint256 payoutAmount) → uint256 payoutId` external
Creates a new payout for a claim under a policy.
#### [](#TestProduct-processPayout-bytes32-uint256-)
`processPayout(bytes32 policyId, uint256 payoutId)` external
Processes a payout for a specific policy.
#### [](#TestProduct-oracleCallback-uint256-bytes32-bytes-)
`oracleCallback(uint256 requestId, bytes32 policyId, bytes responseData)` external
This function is called by the oracle to provide the response data for a specified policy ID and request ID.
#### [](#TestProduct-getClaimId-bytes32-)
`getClaimId(bytes32 policyId) → uint256` external
Returns the claim ID associated with a given policy ID.
#### [](#TestProduct-getPayoutId-bytes32-)
`getPayoutId(bytes32 policyId) → uint256` external
Returns the payout ID associated with a given policy ID.
#### [](#TestProduct-applications--)
`applications() → uint256` external
Returns the number of applications that have been submitted.
#### [](#TestProduct-policies--)
`policies() → uint256` external
Returns the number of policies in the \_policies array.
#### [](#TestProduct-claims--)
`claims() → uint256` external
Returns the number of claims made by users.
#### [](#TestProduct-LogTestProductFundingReceived-address-uint256-)
`LogTestProductFundingReceived(address sender, uint256 amount)` event
#### [](#TestProduct-LogTestOracleCallbackReceived-uint256-bytes32-bytes-)
`LogTestOracleCallbackReceived(uint256 requestId, bytes32 policyId, bytes response)` event
### [](#TestRegistryCompromisedController)
`TestRegistryCompromisedController`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestRegistryCompromisedController.sol)
import "@etherisc/gif-contracts/contracts/test/TestRegistryCompromisedController.sol";
Functions
* [`getContract(contractName)`](#TestRegistryCompromisedController-getContract-bytes32-)
* [`upgradeToV2(compromisedPolicyModuleAddress, originalQueryModuleAddress)`](#TestRegistryCompromisedController-upgradeToV2-address-address-)
#### [](#TestRegistryCompromisedController-getContract-bytes32-)
`getContract(bytes32 contractName) → address moduleAddress` external
Returns the address of a registered contract.
#### [](#TestRegistryCompromisedController-upgradeToV2-address-address-)
`upgradeToV2(address compromisedPolicyModuleAddress, address originalQueryModuleAddress)` public
Upgrades the Policy Manager contract to version 2.
### [](#TestRegistryControllerUpdated)
`TestRegistryControllerUpdated`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestRegistryControllerUpdated.sol)
import "@etherisc/gif-contracts/contracts/test/TestRegistryControllerUpdated.sol";
Functions
* [`setMessage(_message)`](#TestRegistryControllerUpdated-setMessage-string-)
* [`getMessage()`](#TestRegistryControllerUpdated-getMessage--)
* [`upgradeToV2(_message)`](#TestRegistryControllerUpdated-upgradeToV2-string-)
RegistryController
* [`initializeRegistry(_initialRelease)`](modules#RegistryController-initializeRegistry-bytes32-)
* [`ensureSender(sender, _contractName)`](modules#RegistryController-ensureSender-address-bytes32-)
* [`getRelease()`](modules#RegistryController-getRelease--)
* [`getContract(_contractName)`](modules#RegistryController-getContract-bytes32-)
* [`register(_contractName, _contractAddress)`](modules#RegistryController-register-bytes32-address-)
* [`deregister(_contractName)`](modules#RegistryController-deregister-bytes32-)
* [`getContractInRelease(_release, _contractName)`](modules#RegistryController-getContractInRelease-bytes32-bytes32-)
* [`registerInRelease(_release, _contractName, _contractAddress)`](modules#RegistryController-registerInRelease-bytes32-bytes32-address-)
* [`deregisterInRelease(_release, _contractName)`](modules#RegistryController-deregisterInRelease-bytes32-bytes32-)
* [`prepareRelease(_newRelease)`](modules#RegistryController-prepareRelease-bytes32-)
* [`contracts()`](modules#RegistryController-contracts--)
* [`contractName(idx)`](modules#RegistryController-contractName-uint256-)
* [`_getContractInRelease(_release, _contractName)`](modules#RegistryController-_getContractInRelease-bytes32-bytes32-)
* [`_registerInRelease(_release, isNewRelease, _contractName, _contractAddress)`](modules#RegistryController-_registerInRelease-bytes32-bool-bytes32-address-)
* [`_deregisterInRelease(_release, _contractName)`](modules#RegistryController-_deregisterInRelease-bytes32-bytes32-)
CoreController
* [`initialize(registry)`](shared#CoreController-initialize-address-)
* [`_getName()`](shared#CoreController-_getName--)
* [`_afterInitialize()`](shared#CoreController-_afterInitialize--)
* [`_getContractAddress(contractName)`](shared#CoreController-_getContractAddress-bytes32-)
Initializable
* [`_disableInitializers()`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-_disableInitializers--)
Events
Initializable
* [`Initialized(version)`](https://docs.openzeppelin.com/contracts/3.x/api/proxy#Initializable-Initialized-uint8-)
IRegistry
* [`LogContractRegistered(release, contractName, contractAddress, isNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
* [`LogContractDeregistered(release, contractName)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
* [`LogReleasePrepared(release)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IRegistry.sol)
#### [](#TestRegistryControllerUpdated-setMessage-string-)
`setMessage(string _message)` public
Sets the message variable to a given string.
#### [](#TestRegistryControllerUpdated-getMessage--)
`getMessage() → string` public
Returns the current message stored in the contract.
#### [](#TestRegistryControllerUpdated-upgradeToV2-string-)
`upgradeToV2(string _message)` public
Upgrades the contract to version 2.
### [](#TestRiskpool)
`TestRiskpool`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestRiskpool.sol)
import "@etherisc/gif-contracts/contracts/test/TestRiskpool.sol";
Functions
* [`constructor(name, collateralization, erc20Token, wallet, registry)`](#TestRiskpool-constructor-bytes32-uint256-address-address-address-)
* [`bundleMatchesApplication(bundle, application)`](#TestRiskpool-bundleMatchesApplication-struct-IBundle-Bundle-struct-IPolicy-Application-)
BasicRiskpool
* [`_lockCollateral(processId, collateralAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
* [`_processPayout(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
* [`_processPremium(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
* [`_releaseCollateral(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
Riskpool
* [`_afterPropose()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`createBundle(filter, initialAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`fundBundle(bundleId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`defundBundle(bundleId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`lockBundle(bundleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`unlockBundle(bundleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`closeBundle(bundleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`burnBundle(bundleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`collateralizePolicy(processId, collateralAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`processPolicyPayout(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`processPolicyPremium(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`releasePolicy(processId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`setMaximumNumberOfActiveBundles(maximumNumberOfActiveBundles)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getMaximumNumberOfActiveBundles()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getWallet()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getErc20Token()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getSumOfSumInsuredCap()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getFullCollateralizationLevel()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getCollateralizationLevel()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`bundles()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getBundle(idx)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`activeBundles()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getActiveBundleId(idx)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getFilterDataStructure()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getCapital()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getTotalValueLocked()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getCapacity()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`getBalance()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
* [`_afterArchive()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Riskpool.sol)
Component
* [`setId(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getName()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getId()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getType()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getState()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getOwner()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isProduct()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isOracle()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`isRiskpool()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`getRegistry()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`proposalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`approvalCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`declineCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`suspendCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`resumeCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`pauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`unpauseCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`archiveCallback()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterApprove()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterDecline()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterSuspend()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterResume()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterPause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_afterUnpause()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getAccess()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getInstanceService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getComponentOwnerService()`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
* [`_getContractAddress(contractName)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Component.sol)
Ownable
* [`owner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-owner--)
* [`_checkOwner()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_checkOwner--)
* [`renounceOwnership()`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-renounceOwnership--)
* [`transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-transferOwnership-address-)
* [`_transferOwnership(newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-_transferOwnership-address-)
Events
BasicRiskpool
* [`LogBasicRiskpoolBundlesAndPolicies(activeBundles, bundleId)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
* [`LogBasicRiskpoolCandidateBundleAmountCheck(index, bundleId, maxAmount, collateralAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/BasicRiskpool.sol)
Ownable
* [`OwnershipTransferred(previousOwner, newOwner)`](https://docs.openzeppelin.com/contracts/3.x/api/access#Ownable-OwnershipTransferred-address-address-)
IComponentEvents
* [`LogComponentProposed(componentName, componentType, componentAddress, id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentApproved(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentDeclined(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentSuspended(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentResumed(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentPaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentUnpaused(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentArchived(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
* [`LogComponentStateChanged(id, stateOld, stateNew)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IComponentEvents.sol)
IRiskpool
* [`LogRiskpoolCreated(riskpoolAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolProposed(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolApproved(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolDeclined(id)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolBundleCreated(bundleId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolBundleMatchesPolicy(bundleId, isMatching)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolCollateralLocked(processId, collateralAmount, isSecured)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolPremiumProcessed(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolPayoutProcessed(processId, amount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
* [`LogRiskpoolCollateralReleased(processId, collateralAmount)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IRiskpool.sol)
IComponent
* [`LogComponentCreated(componentName, componentType, componentAddress, registryAddress)`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/IComponent.sol)
#### [](#TestRiskpool-constructor-bytes32-uint256-address-address-address-)
`constructor(bytes32 name, uint256 collateralization, address erc20Token, address wallet, address registry)` public
Constructor function for the Riskpool contract.
#### [](#TestRiskpool-bundleMatchesApplication-struct-IBundle-Bundle-struct-IPolicy-Application-)
`bundleMatchesApplication(struct IBundle.Bundle bundle, struct IPolicy.Application application) → bool isMatching` public
This function checks if a given bundle matches a given application.
### [](#TestTransferFrom)
`TestTransferFrom`[](https://github.com/etherisc/gif-contracts/blob/release-v2.0.0-rc.1-0/contracts/test/TestTransferFrom.sol)
import "@etherisc/gif-contracts/contracts/test/TestTransferFrom.sol";
Functions
* [`unifiedTransferFrom(token, from, to, amount)`](#TestTransferFrom-unifiedTransferFrom-contract-IERC20-address-address-uint256-)
Events
* [`LogTransferHelperInputValidation1Failed(tokenIsContract, from, to)`](#TestTransferFrom-LogTransferHelperInputValidation1Failed-bool-address-address-)
* [`LogTransferHelperInputValidation2Failed(balance, allowance)`](#TestTransferFrom-LogTransferHelperInputValidation2Failed-uint256-uint256-)
* [`LogTransferHelperCallFailed(callSuccess, returnDataLength, returnData)`](#TestTransferFrom-LogTransferHelperCallFailed-bool-uint256-bytes-)
#### [](#TestTransferFrom-unifiedTransferFrom-contract-IERC20-address-address-uint256-)
`unifiedTransferFrom(contract IERC20 token, address from, address to, uint256 amount) → bool` external
Transfers tokens from a specified address to another specified address using the TransferHelper library.
#### [](#TestTransferFrom-LogTransferHelperInputValidation1Failed-bool-address-address-)
`LogTransferHelperInputValidation1Failed(bool tokenIsContract, address from, address to)` event
#### [](#TestTransferFrom-LogTransferHelperInputValidation2Failed-uint256-uint256-)
`LogTransferHelperInputValidation2Failed(uint256 balance, uint256 allowance)` event
#### [](#TestTransferFrom-LogTransferHelperCallFailed-bool-uint256-bytes-)
`LogTransferHelperCallFailed(bool callSuccess, uint256 returnDataLength, bytes returnData)` event
[← Shared](/contracts/2.x/api/shared)
[Tokens →](/contracts/2.x/api/tokens)
---
# Error Codes - Etherisc Docs
Error Codes
===========
[](#error_codes)
Error Codes
----------------------------
Test
### [](#test)
Test
Test
\==== \`ERROR:ACL-001:ADMIN\_ROLE\_ALREADY\_SET \`#x#x Contract: modules/AccessController.sol
Thrown if you try to set the admin role twice.
\==== \`ERROR:ACL-002:ROLE\_UNKNOWN\_OR\_INVALID \`\## Contract: modules/AccessController.sol
Thrown if
\==== \`ERROR:ACL-003:ROLE\_EXISTING\_AND\_VALID \`\## Contract: modules/AccessController.sol
Thrown if
\==== \`ERROR:ACL-004:ROLE\_UNKNOWN\_OR\_INVALID \`\## Contract: modules/AccessController.sol
Thrown if
\==== \`ERROR:ACM-001:NOT\_INSTANCE\_OPERATOR \`\## Contract: shared/WithRegistry.sol
Thrown if
\==== \`ERROR:ACM-004:NOT\_ORACLE\_SERVICE \`\## Contract: shared/WithRegistry.sol
Thrown if
\==== \`ERROR:ACM-005:NOT\_ORACLE\_OWNER \`\## Contract: shared/WithRegistry.sol
Thrown if
\==== \`ERROR:ACM-006:NOT\_PRODUCT\_OWNER \`\## Contract: shared/WithRegistry.sol
Thrown if
\==== \`ERROR:BOC-074:INITIAL\_STATE\_NOT\_HANDLED \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BTK-001:NOT\_INITIALIZED \`\## Contract: tokens/BundleToken.sol
Thrown if
\==== \`ERROR:BTK-002:NOT\_BUNDLE\_MODULE \`\## Contract: tokens/BundleToken.sol
Thrown if
\==== \`ERROR:BTK-003:BUNDLE\_MODULE\_ALREADY\_DEFINED \`\## Contract: tokens/BundleToken.sol
Thrown if
\==== \`ERROR:BTK-004:INVALID\_BUNDLE\_MODULE\_ADDRESS \`\## Contract: tokens/BundleToken.sol
Thrown if
\==== \`ERROR:BTK-005:TOKEN\_ID\_INVALID \`\## Contract: tokens/BundleToken.sol
Thrown if
\==== \`ERROR:BUC-001:NOT\_RISKPOOL\_SERVICE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-002:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-003:BUNDLE\_BURNED\_OR\_CLOSED \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-010:BUNDLE\_ALREADY\_EXISTS \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-011:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-012:BUNDLE\_CLOSED \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-013:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-014:CAPACITY\_OR\_BALANCE\_TOO\_LOW \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-015:BUNDLE\_WITH\_ACTIVE\_POLICIES \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-016:BUNDLE\_NOT\_CLOSED \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-017:BUNDLE\_HAS\_BALANCE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-019:BUNDLE\_NOT\_IN\_RISKPOOL \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-020:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-021:BUNDLE\_NOT\_ACTIVE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-022:CAPACITY\_TOO\_LOW \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-023:INCREMENTAL\_COLLATERALIZATION\_NOT\_IMPLEMENTED \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-031:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-041:NO\_ACTIVE\_POLICIES\_FOR\_BUNDLE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-042:COLLATERAL\_INSUFFICIENT\_FOR\_POLICY \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-043:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-044:BUNDLE\_STATE\_INVALID \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-045:CAPITAL\_TOO\_LOW \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-046:LOCKED\_CAPITAL\_TOO\_LOW \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-047:BALANCE\_TOO\_LOW \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-051:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-052:NO\_ACTIVE\_POLICIES\_FOR\_BUNDLE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-060:BUNDLE\_DOES\_NOT\_EXIST \`\## Contract: modules/BundleController.sol
Thrown if you … and bundle doesn’t exist
\==== \`ERROR:BUC-070:ACTIVE\_INVALID\_TRANSITION \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-071:LOCKED\_INVALID\_TRANSITION \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-072:CLOSED\_INVALID\_TRANSITION \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:BUC-073:BURNED\_IS\_FINAL\_STATE \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:CCR-001:NOT\_COMPONENT\_OWNER\_SERVICE \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-002:NOT\_INSTANCE\_OPERATOR\_SERVICE \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-003:COMPONENT\_ALREADY\_EXISTS \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-004:COMPONENT\_NAME\_ALREADY\_EXISTS \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-005:INVALID\_COMPONENT\_ID \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-006:COMPONENT\_ADDRESS\_ZERO \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-007:COMPONENT\_UNKNOWN \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-008:INVALID\_COMPONENT\_ID \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-010:COMPONENT\_TYPE\_UNKNOWN \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-011:UNKNOWN\_PRODUCT\_ID \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-020:SOURCE\_AND\_TARGET\_STATE\_IDENTICAL \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-021:CREATED\_INVALID\_TRANSITION \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-023:DECLINED\_IS\_FINAL\_STATE \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-024:ACTIVE\_INVALID\_TRANSITION \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-025:PAUSED\_INVALID\_TRANSITION \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-026:SUSPENDED\_INVALID\_TRANSITION \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-027:INITIAL\_STATE\_NOT\_HANDLED \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:CCR-22:PROPOSED\_INVALID\_TRANSITION \`\## Contract: modules/ComponentController.sol
Thrown if
\==== \`ERROR:COS-001:NOT\_OWNER \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-002:REQUIRED\_ROLE\_MISSING \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-003:COMPONENT\_ID\_INVALID \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-004:NOT\_OWNER \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-005:REQUIRED\_ROLE\_MISSING \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-006:IMPLEMENATION\_MISSING \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:COS-007:IMPLEMENATION\_MISSING \`\## Contract: services/ComponentOwnerService.sol
Thrown if
\==== \`ERROR:CRC-001:NOT\_INSTANCE\_OPERATOR \`\## Contract: shared/CoreController.sol
Thrown if
\==== \`ERROR:CRC-001:NOT\_ORACLE\_SERVICE \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:CRC-002:NOT\_ON\_STORAGE \`\## Contract: shared/CoreController.sol
Thrown if
\==== \`ERROR:CRC-003:NOT\_PRODUCT\_SERVICE \`\## Contract: shared/CoreController.sol
Thrown if
\==== \`ERROR:CRC-004:CONTRACT\_NOT\_REGISTERED \`\## Contract: shared/CoreController.sol
Thrown if
\==== \`ERROR:CRP-001:NOT\_ADMIN \`\## Contract: shared/CoreProxy.sol
Thrown if
\==== \`ERROR:IOS-001:NOT\_INSTANCE\_OPERATOR \`\## Contract: services/InstanceOperatorService.sol
Thrown if
\==== \`ERROR:IOS-010:IMPLEMENATION\_MISSING \`\## Contract: services/InstanceOperatorService.sol
Thrown if
\==== \`ERROR:IOS-011:IMPLEMENATION\_MISSING \`\## Contract: services/InstanceOperatorService.sol
Thrown if
\==== \`ERROR:IS-001:IMPLEMENATION\_MISSING \`\## Contract: services/InstanceService.sol
Thrown if
\==== \`ERROR:IS-002:IMPLEMENATION\_MISSING \`\## Contract: services/InstanceService.sol
Thrown if
\==== \`ERROR:LIC-001:COMPONENT\_NOT\_PRODUCT \`\## Contract: modules/LicenseController.sol
Thrown if
\==== \`ERROR:PFD-001:POLICY\_NOT\_ACTIVE \`\## Contract: flows/PolicyDefaultFlow.sol
Thrown if
\==== \`ERROR:PFD-002:POLICY\_NOT\_EXPIRED \`\## Contract: flows/PolicyDefaultFlow.sol
Thrown if
\==== \`ERROR:PFD-003:POLICY\_CLOSED \`\## Contract: flows/PolicyDefaultFlow.sol
Thrown if
\==== \`ERROR:PFD-004:PROCESSID\_PRODUCT\_MISMATCH \`\## Contract: flows/PolicyDefaultFlow.sol
Thrown if
\==== \`ERROR:PFD-005:REQUESTID\_PRODUCT\_MISMATCH \`\## Contract: flows/PolicyDefaultFlow.sol
Thrown if
\==== \`ERROR:POC-004:METADATA\_ALREADY\_EXISTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-010:METADATA\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-011:APPLICATION\_ALREADY\_EXISTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-012:PREMIUM\_AMOUNT\_ZERO \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-013:SUM\_INSURED\_AMOUNT\_TOO\_SMALL \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-014:METADATA\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-015:APPLICATION\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-016:APPLICATION\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-017:APPLICATION\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-018:APPLICATION\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-019:METADATA\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-020:APPLICATION\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-021:APPLICATION\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-022:APPLICATION\_ACCESS\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-023:POLICY\_ALREADY\_EXISTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-024:APPLICATION\_ACCESS\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-025:APPLICATION\_PREMIUM\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-026:APPLICATION\_SUM\_INSURED\_INCREASE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-027:POLICY\_ACCESS\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-028:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-029:APPLICATION\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-030:METADATA\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-031:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-032:POLICY\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-033:POLICY\_HAS\_OPEN\_CLAIMS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-040:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-041:POLICY\_NOT\_ACTIVE \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-042:CLAIM\_AMOUNT\_EXCEEDS\_MAX\_PAYOUT \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-043:CLAIM\_ALREADY\_EXISTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-050:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-051:POLICY\_WITHOUT\_OPEN\_CLAIMS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-052:PAYOUT\_MAX\_AMOUNT\_EXCEEDED \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-053:CLAIM\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-054:CLAIM\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-060:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-061:POLICY\_WITHOUT\_OPEN\_CLAIMS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-062:CLAIM\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-063:CLAIM\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-070:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-071:POLICY\_WITHOUT\_OPEN\_CLAIMS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-072:CLAIM\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-073:CLAIM\_STATE\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-074:CLAIM\_WITH\_UNPAID\_PAYOUTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-080:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-081:CLAIM\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-082:CLAIM\_NOT\_CONFIRMED \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-083:PAYOUT\_AMOUNT\_ZERO\_INVALID \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-084:PAYOUT\_AMOUNT\_TOO\_BIG \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-085:PAYOUT\_ALREADY\_EXISTS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-090:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-091:POLICY\_WITHOUT\_OPEN\_CLAIMS \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-092:PAYOUT\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-093:PAYOUT\_ALREADY\_PAIDOUT \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-100:METADATA\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-101:APPLICATION\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-102:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-103:CLAIM\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-104:PAYOUT\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-110:POLICY\_DOES\_NOT\_EXIST \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POC-111:AMOUNT\_TOO\_BIG \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POL-001:INVALID\_OWNER \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POL-001:NOT\_INSTANCE\_OPERATOR \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-002:INVALID\_PRODUCT \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POL-002:NOT\_RISKPOOL\_SERVICE \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-003:PRODUCT\_NOT\_ACTIVE \`\## Contract: modules/PolicyController.sol
Thrown if
\==== \`ERROR:POL-003:RISKPOOL\_NOT\_ACTIVE \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-004:RISKPOOL\_NOT\_ACTIVE \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-005:RISKPOOL\_ALREADY\_REGISTERED \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-006:WALLET\_ADDRESS\_ZERO \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-007:ERC20\_ADDRESS\_ZERO \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-008:COLLATERALIZATION\_ \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-009:SUM\_OF\_SUM\_INSURED\_CAP\_ZERO \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-010:NOT\_PRODUCT \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-011:NOT\_RISKPOOL \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-012:RISKPOOL\_ALREADY\_SET \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-020:APPLICATION\_STATE\_INVALID \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-022:RISKPOOL\_SUM\_INSURED\_CAP\_EXCEEDED \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-025:POLICY\_STATE\_INVALID \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-026:RISKPOOL\_ID\_INVALID \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-027:CAPITAL\_TOO\_LOW \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-028:LOCKED\_CAPITAL\_TOO\_LOW \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-029:BALANCE\_TOO\_LOW \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-030:POLICY\_STATE\_INVALID \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:POL-032:MAX\_NUMBER\_OF\_ACTIVE\_BUNDLES\_INVALID \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-040:POLICY\_STATE\_INVALID \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:POL-040:RISKPOOL\_NOT\_REGISTERED \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-041:BUNDLE\_IDX\_TOO\_LARGE \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-042:BUNDLE\_ID\_ALREADY\_IN\_SET \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-043:MAXIMUM\_NUMBER\_OF\_ACTIVE\_BUNDLES\_REACHED \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-044:BUNDLE\_ID\_NOT\_IN\_SET \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-045:RISKPOOL\_DOES\_NOT\_EXIST \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-046:COMPONENT\_NOT\_RISKPOOL \`\## Contract: modules/PoolController.sol
Thrown if
\==== \`ERROR:POL-050:POLICY\_STATE\_INVALID \`\## Contract: modules/BundleController.sol
Thrown if
\==== \`ERROR:PRS-001:NOT\_AUTHORIZED \`\## Contract: services/ProductService.sol
Thrown if
\==== \`ERROR:PRS-002:POLICY\_FLOW\_NOT\_RESOLVED \`\## Contract: services/ProductService.sol
Thrown if
\==== \`ERROR:QUC-002:REQUEST\_ID\_INVALID \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-003:ORACLE\_NOT\_RESPONSIBLE \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-010:CALLBACK\_ADDRESS\_IS\_NOT\_PRODUCT \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-020:PRODUCT\_CALLBACK\_UNSUCCESSFUL \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-030:REQUEST\_ID\_INVALID \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-040:REQUEST\_ID\_INVALID \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-041:COMPONENT\_NOT\_ORACLE \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:QUC-042:ORACLE\_NOT\_ACTIVE \`\## Contract: modules/QueryModule.sol
Thrown if
\==== \`ERROR:REC-001:EMPTY\_RELEASE \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-002:NEW\_RELEASE\_NOT\_EMPTY \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-010:MAX\_CONTRACTS\_LIMIT \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-011:RELEASE\_UNKNOWN \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-012:CONTRACT\_NAME\_EMPTY \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-013:CONTRACT\_NAME\_EXISTS \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-014:CONTRACT\_ADDRESS\_ZERO \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-015:CONTRACT\_NUMBER\_MISMATCH \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-020:CONTRACT\_UNKNOWN \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-021:CONTRACT\_NUMBER\_MISMATCH \`\## Contract: modules/RegistryController.sol
Thrown if
\==== \`ERROR:REC-102:UPGRADE\_ONCE\_OMLY \`\## Contract: test/TestRegistryControllerUpdated.sol
Thrown if
\==== \`ERROR:RPS-001:SENDER\_NOT\_RISKPOOL \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-002:RISKPOOL\_NOT\_PROPOSED \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-003:SENDER\_NOT\_RISKPOOL \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-004:RISKPOOL\_NOT\_ACTIVE \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-005:SENDER\_NOT\_RISKPOOL \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-006:BUNDLE\_RISKPOOL\_MISMATCH \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-007:RISKPOOL\_NOT\_ACTIVE \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-008:SENDER\_NOT\_OWNING\_RISKPOOL \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-009:RISKPOOL\_NOT\_ACTIVE \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-010:BUNDLE\_CLOSED\_OR\_BURNED \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-011:BUNDLE\_BURNED \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-013:UNEXPECTED\_FEE\_SUBTRACTION \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:RPS-020:BUNDLE\_NOT\_CLOSED \`\## Contract: services/RiskpoolService.sol
Thrown if
\==== \`ERROR:TCP-1:INVALID\_POLICY\_OR\_HOLDER \`\## Contract: test/TestCompromisedProduct.sol
Thrown if
\==== \`ERROR:TI-2:TOKEN\_ADDRESS\_ZERO \`\## Contract: test/TestProduct.sol
Thrown if
\==== \`ERROR:TRS-001:INSTANCE\_WALLET\_UNDEFINED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-002:RISKPOOL\_WALLET\_UNDEFINED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-003:RISKPOOL\_WALLET\_UNDEFINED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-004:TREASURY\_SUSPENDED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-005:NOT\_RISKPOOL\_SERVICE \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-010:TOKEN\_ADDRESS\_ZERO \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-011:NOT\_PRODUCT \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-012:PRODUCT\_TOKEN\_ALREADY\_SET \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-013:PRODUCT\_TOKEN\_ADDRESS\_NOT\_MATCHING \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-014:RISKPOOL\_TOKEN\_ADDRESS\_NOT\_MACHING \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-015:WALLET\_ADDRESS\_ZERO \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-016:NOT\_RISKPOOL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-017:WALLET\_ADDRESS\_ZERO \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-020:ID\_NOT\_PRODUCT\_OR\_RISKPOOL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-021:FRACIONAL\_FEE\_TOO\_BIG \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-022:NOT\_PRODUCT \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-023:NOT\_RISKPOOL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-024:FEE\_SPEC\_UNDEFINED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-030:AMOUNT\_TOO\_BIG \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-031:FEE\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-032:PREMIUM\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-042:RISKPOOL\_WALLET\_BALANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-043:PAYOUT\_ALLOWANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-044:PAYOUT\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-050:FEE\_SPEC\_UNDEFINED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-052:BALANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-053:CAPITAL\_TRANSFER\_ALLOWANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-054:FEE\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-055:CAPITAL\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-060:CAPACITY\_OR\_BALANCE\_SMALLER\_THAN\_WITHDRAWAL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-061:RISKPOOL\_WALLET\_BALANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-062:WITHDRAWAL\_ALLOWANCE\_TOO\_SMALL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-063:WITHDRAWAL\_TRANSFER\_FAILED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-070:NOT\_PRODUCT\_OR\_RISKPOOL \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-090:FEE\_CALCULATION\_DATA\_NOT\_SUPPORTED \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-091:FEE\_TOO\_BIG \`\## Contract: modules/TreasuryModule.sol
Thrown if
\==== \`ERROR:TRS-092:PRODUCT\_WITHOUT\_RISKPOOL \`\## Contract: modules/TreasuryModule.sol
Thrown if Contract:
---
# Token Model - Etherisc Docs
Token Model
===========
[](#overview)
Overview
----------------------
In the Etherisc ecosystem, all kinds of token can be used. However, for example, you want to avoid having a volatile token as a backup currency in a risk pool. Here you want to use stablecoins. This minimizes the risk and gives you planning security.
An NFT, which confirms the ownership of a risk bundle, can very well be volatile. This way, you can realize your profit.
If you have calculated your risk model to make a profit, then over time, the parts of the premiums in the risk bundle that have not been used to cover claims or general maintenance costs (instance operator, risk pool keeper, product owner and oracle owner) will accumulate. These can then be credited to the investor as profit distribution.
Sum premiums > sum claims + costs
The costs incurred are paid to the instance operator, the product owner, the oracle owner, the risk pool keeper and the instance operator from the premiums. While the tokens in which the fees are paid can be freely determined for all participants except the instance operator, the instance operator is paid exclusively in DIP tokens.
[](#dip_token)
DIP Token
------------------------
The DIP (Decentralized Insurance Token) token is the native token of Etherisc.
It started with the DIP Token Generating Event (TGE) - from Jun 23rd to July 25th, 2018. The supply is 1 billion, hardcap was 30 million USD. Only registered contributors were able to participate. During the TGE, 30 million DIP tokens were issued to registered contributors. The exchange rate for 1 DIP was 0.10 USD.
Each project must purchase a certain number of DIP tokens to secure production. The number varies per project, similar to a cooperative. A high-risk project to maximize profits must purchase more DIP tokens than a non-profit or scientific project. Ultimately, the DAO decides this. Each project receives voting rights proportionally to DIP token deposits.
[](#risk_pool_token)
Risk Pool Token
------------------------------------
When the risk pool keeper creates the risk pool, he receives an NFT that secures the rights to the risk pool. The risk pool NFT cannot be sold or disposed of and therefore has no value. The risk pool keeper must buy DIP tokens to operate the risk pool on the instance. In return, the risk pool keeper will pick up a management fee.
[](#bundle_token)
Bundle Token
------------------------------
Now you create a risk bundle within the risk pool. The prerequisite for this is that you buy an amount of DIP tokens determined by the DAO depending on the risk and the amount of the risk bundle and pay in the tokens. You will also receive an NFT that secures your rights to the bundle. The value of the NFT at the beginning is equal to the value of the paid tokens.
However, this value changes as soon as premiums have been paid so that a part of the token is also logged. Furthermore, payouts in the event of a claim or profit distributions may have taken place. The bundle NFT is tradable.
[](#fees)
Fees
--------------
All involved parties can use fees for the use of the respective infrastructure.
The instance operator for providing the hardware and keeps the instance up and running and highly available.
The risk pool keeper and for keeping the risk pool highly performant. The risk pool keeper can also provide other services, such as booking all fees for all participants.
The product owner for providing the smart contracts and ensuring a smooth and error-free process.
The oracle owner for the correct and uninterrupted data supply of the smart contracts on the blockchain.
[](#use_of_permits)
Use of Permits
----------------------------------
To transfer ERC 20 token, you need two functions (transferFrom, approve) and each will cost you a gas fee. Those gas fees are high and If you are trading often on DEX, you will pay a lot of gas fees.
With the permit function, you do not need to call the approve function. You are approving the transaction by signing the transaction. This transaction is signed off-chain, so you are not paying gas fees. Front-end developers handle this part and derive the signature’s v,r,s.
Permit () function allows anyone to authorize and swap a token in one transaction instead of two transactions. But this does not mean that you are saving half the gas fees. For example, if you paid ten wei gas fees for two transactions, now it will not be five wei because the permit function has more logic to implement. So the total gas fee will be between 5-10 wei. A permit is not about just saving the gas fee but delegating the transaction to another wallet so that the wallet will pay the transaction. That is called a gasless transaction.
[← Services](/gif/services)
[Governance →](/gif/governance-model)
---
# Learn - Etherisc Docs
Learn
=====
Comprehensive guides for every step of your journey in the Etherisc ecosystem.
[Depeg Protection Tutorial Learn how to purchase depeg protection and stake into risk bundles.](depeg-purchase)
[Depeg Protection FAQ Frequently Asked Questions regarding Depeg Protection.](depeg-faq)
[DIP Staking Tutorial Learn how to stake your DIP token.](dip-staking)
[DIP Staking FAQ Frequently Asked Questions regarding DIP Staking.](staking-faq)
[Basics of the GIF Framework Understanding the basic concepts of the GIF Framework.](basics-gif)
[The GIF sandbox Setting up and using the GIF sandbox - a place to learn and experiment.](sandbox)
[Staking in risk pools Staking as a fundamental building block for insurance.](staking-insurance)
[The DIP token The essential utility token of the Etherisc ecosystem.](token)
[Depeg Protection Tutorial →](/learn/depeg-purchase)
---
# Q & A - Etherisc Docs
Q & A
=====
[](#creating_risk_bundles_by_staking_usdt)
Creating risk bundles by staking USDT
--------------------------------------------------------------------------------
### [](#how_do_i_stake_usdt_create_a_risk_bundle)
How do I stake USDT / create a risk bundle?
#### [](#step_1_connect_your_wallet)
Step 1: Connect your wallet
Before staking, you must ensure you are connected with your wallet with the [Etherisc depeg protection app](https://depeg.etherisc.com)
on the Ethereum mainnet and ensure your wallet holds a small amount of ETH to afford the transaction fees.
Caution: Please ensure you know how to use non-custodial wallets like Metamask before staking your tokens. As a rule of thumb, never give anyone your seed phrase or private key and never interact with non-official websites.
#### [](#step_2_create_a_risk_bundle)
Step 2: Create a risk bundle
Click the ‘Stake’ button. You can create a new risk bundle or click on 'Risk bundles' and then on 'CREATE NEW RISK BUNDLE' in the upper right corner.
#### [](#step_3_stake_your_usdt)
Step 3: Stake your USDT
Enter the desired amount of USDC tokens in your new or applied risk bundle.
With a new risk bundle, you can model all other parameters; some parameters are given with participation.
Read and agree to the terms and conditions by checking the box and clicking the ‘STAKE’ button.
Note: You will be prompted to do an approved transaction.
### [](#how_can_i_avoid_high_gas_fees)
How can I avoid high gas fees?
If your wallet offers maximum gas fees for the transaction, you can set the price to a maximum of 25GWei, confirm the transaction, and take a nap. During our ‘friends and family’ period, we made some transactions with an upper limit of 25 GWei. The most extended duration was one day.
### [](#how_much_usdt_can_i_stake)
How much USDT can I stake?
Currently, you can stake between 1,000 - 10,000 USDT per risk bundle
### [](#what_are_the_minimum_maximum_usdt_staking_durations)
What are the minimum / maximum USDT staking durations?
You determine the lifetime of your risk bundle, ranging from 14-180 days. However, If a 180 day policy is purchased on day 170 of your 180 day risk bundle, you can unstake your USDT and claim your reward against that policy on day 170 + 180 days.
### [](#ive_staked_usdt_can_i_stake_more)
I’ve staked USDT. Can I stake more?
Of course! You can create a new risk bundle by clicking the ‘Stake’ or 'Risk bundles' buttons and then on 'CREATE NEW RISK BUNDLE' in the upper right corner.
You can also stake more in one of your existing risk bundles by clicking 'SHOW BUNDLE' after clicking the 'Risk bundles' button. Then click the 'stake' button when the risk bundle details are shown.
The maximum amount of a risk bundle is 10,000 USDT now. We will increase the maximum amount.
### [](#how_and_when_can_i_unstake_my_usdt)
How and when can I unstake my USDT?
You can unstake your USDT at any time until policies are purchased against it. Your staked USDT is locked from the moment a policy is purchased until it expires.
For example, if you stake 10,000 and policies are purchased against 1,000 of it, you can unstake 9,000 at any time. After the policies expire, you can unstake the remaining USDT, minus any claims paid.
You’ll get to the list of all risk bundles by clicking the 'Risk bundles' button. Search for the desired risk bundle, click 'SHOW BUNDLE' on the right (mouseover), then click 'UNSTAKE' and enter the quantity.
### [](#what_rewards_will_i_receive_for_my_staked_usdt)
What rewards will I receive for my staked USDT?
USDT rewards come from depeg protection premiums purchased against your risk bundle, minus Etherisc fees. If no policies are sold, no rewards accumulate. If there is a depeg event and claims are paid, claims will be subtracted from your reward. Therefore your capital is at risk.
### [](#when_will_i_receive_my_rewards)
When will I receive my rewards?
### [](#are_risk_bundles_an_nft)
Are risk bundles an NFT?
Every risk bundle is an NFT (ERC721). You can import the NFT contract address for this to be displayed in your wallet.
### [](#is_there_a_maximum_bundle_lifetime)
Is there a maximum bundle lifetime?
The risk bundle lifetime describes how long new policies can be accepted/covered by a risk bundle. The maximal risk bundle lifetime is 180 days now. So the absolute risk bundle time is the risk bundle lifetime plus the maximum coverage duration.
### [](#my_risk_bundle_is_not_displayed_why)
My risk bundle is not displayed. Why?
Your risk bundle will only be available with policies to purchase against it if there are sufficient DIP tokens staked to support the minimal sum insured.
[](#purchasing_depeg_protection)
Purchasing depeg protection
------------------------------------------------------------
### [](#how_can_i_buy_a_policy)
How can I buy a policy?
Click the 'Apply' button, enter the appropriate data, and select a risk bundle. After agreeing to the terms and conditions, you can buy the policy by clicking the ‘Buy’ button. Click the 'Policies' button and then right on 'APPLY FOR NEW POLICY.' This brings you to the same input screen.
### [](#why_are_not_all_risk_bundles_available_for_me_to_choose_from_when_applying_for_a_policy)
Why are not all risk bundles available for me to choose from when applying for a policy?
The application automatically filters risk bundles suitable for you - the bundles must be 1) active and not expired 2) the USDT capacity is large enough for your USDC balance to be protected from a 20% USDC depeg 3) the appropriate level if USDT capacity has been ‘activated’ by a sufficient amount of staked DIP tokens.
You can claim your rewards after the end of the risk bundle lifetime and when all policies associated with the risk bundle are either paid off or expired.
### [](#do_i_have_to_have_the_usdc_in_the_protected_wallet_when_i_sign_the_policy)
Do I have to have the USDC in the protected wallet when I sign the policy?
In order to be eligible for a claim, the protected USDC amount has to be in your wallet at the time of a depeg event. It does not have to be in your wallet at the time of purchasing the policy.
### [](#can_i_insure_multiple_wallets_from_one_wallet)
Can I insure multiple wallets from one wallet?
Yes. When you complete the protection, you can enter any address in the 'Protected wallet' field. We check if it is a valid address.
### [](#can_i_protect_my_usdc_with_multiple_policies)
Can I protect my USDC with multiple policies?
If you have a USDC balance in your wallet which is higher than a single available risk bundle, you can protect your balance through multiple smaller policies. However, you are not able to protect the same USDC through multiple policies. If there are several policies for the same wallet, the processing order of the claims will determine which policy gets how much of the payout covering this wallet. The order of processing is random and cannot be controlled by policyholders.
For example: you have a 500'000 USDC wallet that you’d like to protect and you can only find risk bundles that provide coverage up to 200'000 USDC. in this case you can buy 2x200'000 and 1x 100'000 coverage. In a depeg situation a wallet can only lead to (accumulated) payouts up to the balance of the wallet. it doesn’t matter how many policies are needed to cover the full balance.
[](#the_depeg_case)
The depeg case
----------------------------------
### [](#the_definition_of_a_depeg_event)
The definition of a depeg event
The Depeg event is ‘triggered at’ when the Chainlink USDC/USD price feed on the Ethereum Mainnet falls below 0.995. If the Chainlink USDC/USD price fails to recover to 0.999 within 24h, the product changes into 'depegged' state.
### [](#the_depegged_payout_price)
The depegged payout price
The depeg payout price is defined as the latest chainlink USDC/USD value exactly 24h after the 'triggered at' event.
The depegged payout price is used for all payout calculations, regardless of when a policyholder requests their payout. The maximum payout price is up to 20% of the value of your protected amount.
An Example: The depegged payout price is 0.9. So, if you purchased protection for 10,000 USDC for a particular Mainnet wallet, you would receive 1
,,30000 USDT (1 - 0.9) \* 10,000) (assuming the USDC balance on your protected wallet is at l,e0ast $10,000 USDC at the time of payout).
### [](#why_wait_for_24hrs)
Why wait for 24hrs?
The idea is that you should be flexible in deciding what to do. When the product enters the 'triggered' state, you can start thinking about how you see the situation. You have 24 hours to evaluate the market and the situation. After 24 hours, the product either goes back to the 'normal' state (when USDC goes back above 0.999) or it goes into the 'depegged' state.
Another important point for us when implementing the 24-hour period was that we did not want to react too quickly in order not to trigger a depeg case too hastily.
### [](#what_happens_in_the_depegged_state)
What happens in the ‘depegged’ state?
Once the product enters the 'depegged' state, you have two options:
* You trigger a payout immediately and you get the gap paid in USDT.
* You sell all your USDC at market conditions and suffer a loss
* Your loss will be covered exactly by the payout of the Etherisc depeg protection in USDT
* You wait and see. If USDC recovers, you can make a slight profit because you also get a payout in USDT, but USDC recovers
### [](#what_happens_when_usdt_depegs)
What happens when USDT depegs?
The Etherisc depeg protection app only protects your USDC against a Depeg event. The staked USDT are unprotected in the app.
If the USDT has a depeg event and the USDC follows up, it is depegged as well, then you, as a USDC depeg policyholder, will get a payout in the ratio 1 USDT = 1 USD. The depeg of the USDT is ignored.
If the USDT is depegged and the USDC is not, the depeg app will not take action because there is no need. You have no reason to act as a USDC depeg policyholder as well. As a USDT risk bundle holder, you can at most unstake the USDT not yet used to protect USDC and close the risk bundle.
[← Depeg Protection Tutorial](/learn/depeg-purchase)
[DIP Staking FAQ →](/learn/staking-faq)
---
# Basics about the GIF framework - Etherisc Docs
Basics about the GIF framework
==============================
[](#introduction)
Introduction
------------------------------
Welcome to our tutorial about the Generic Insurance Framework (GIF). We would like to take you step by step to the topic of insurance in general and how to model insurance with the generic insurance framework.
First we will establish some definitions, functions and roles in order to have a common domain-oriented basis.
### [](#what_is_insurance)
What is insurance?

**Insurance** is a means of protection from financial loss. It is a form of risk management primarily used to hedge against a contingent or uncertain loss risk. The loss associated with the risk may or may not be financial, but it must be reducible to financial terms.
An insurance company takes over risks from a customer, often called the insured. Insurable risks can be events related to weather, like too much or too little rain, but also the delay of a booked flight or a classic car liability insurance. The insurance promises to compensate the insured in case of a covered loss. In return, the insured (also the policyholder) pays a premium. The insurance creates a payout to reimburse the agreed financial amount if a claim occurs.
The insurance company can outsource all services, such as sales or data management, to other service providers. The only exception is the fundamental assumption of the risk. This risk must always remain with the insurance company.
The exact legal requirements for insurance vary around the world. In most countries, an insurance company requires a state-issued license.
### [](#what_is_an_insurance_policy)
What is an insurance policy?
An insurance policy is the contract provided by the insurance to the insured that details conditions and circumstances under which the insurance makes payouts to cover the insured losses that occurred from accepted claims.
Let’s look at the lifecycle of a typical insurance policy. Such a lifecycle usually consists of the following chronologically listed sub-steps.
* The customer inquires about an insurance policy. By taking out the insurance policy, one wants to protect oneself against a specific risk.
* The insurance company examines the customer’s application.
* The application is accepted or rejected.
* In case of rejection, the customer is informed, no further activities occur.
* In case of acceptance, the contract comes to the "underwriter". The acceptance of the application is called "underwriting".
* The insurance company commits itself with the “underwriting” to take over the customer’s risk and transfer it to itself. It further undertakes to cover the loss if the insured event occurs.
* The customer, for his part, undertakes to pay the premium.
* Both declarations of obligation are documented in a contract. This contract is called the insurance policy.
* If a claim occurs, the customer reports it to the insurance company.
* The claim is checked by the insurance company and accepted or rejected.
* In case of acceptance, the agreed insurance sum is paid out.
At this point, it is easy to see that the insurance business triggers a substantial amount of record-keeping. Many of the individual sub-steps in the classic insurance business require manual activities. For example, when a customer makes a claim, the insurance company has to check the details of the claim manually. This involves a lot of effort and thus incurring costs.
### [](#what_is_parametric_insurance)
What is parametric insurance?
Parametric insurances cover the occurrence of predefined events instead of indemnifying actual losses incurred.
Parametric insurance policies correspond to agreements between the insurance and the insured where the insurance approves payouts to the insured when predefined triggering events occur.
In parametric insurance, loss events (the risks) are defined as functions of underlying indices or parameters that meet the criteria defined by the insurance product. Example indices/parameters include rainfall amounts and wind speeds for insurance linked to weather conditions. In the case of flight delay insurance, the parameter/index can directly be derived from the difference between the actual arrival time and the scheduled arrival time of an insured flight. To make parametric insurance feasible and attractive to all parties, the underlying indices/parameters must be transparent, reliable and trusted.
Once such events occur, the insurance may directly calculate and trigger a payout to the insured without an often costly claims acceptance process.
The big win of parametric insurance is their potential for efficiency and automation. Claims handling, one of the most complex and costly parts of the operation of an insurance business, can be reduced to a simple and fully automated process.
### [](#what_are_the_advantages_of_blockchain_in_insurance)
What are the advantages of blockchain in insurance?

There are many benefits that blockchain technology may provide to the insurance domain. Some of the advantages are directly linked to the foundations of blockchain technology.
* Transparency and accountability for records keeping. Information regarding policies, claims and payouts may be stored on-chain. Once on the chain, they can only be deleted or changed with proper permission, and each time data is updated or adjusted, the original data is kept in the history. This means a complete audit trail is available and transparent for all data. This is a clear security aspect and provides value to inexperienced customers with the insurance business and low trust levels towards financial organizations.
* Minimize friction and transaction costs for payment handling. On-chain handling of premium payments and claims payouts may be a substantial efficiency boost for the operation of an insurance business.
* Create new markets/opportunities by opening risk pools. The transparent pooling of large numbers of insurance policies of a particular type provides the opportunity to open up this market to a wider audience. Participating in such risk pools allows investors to diversify their risk portfolios.
Blockchain technology may provide additional value for the particular case of parametric insurance.
* Transparent and trusted handling of indices/parameters. Providing this central data in a trusted way to the blockchain world may be managed through oracle services, which makes it very hard/too costly to feed manipulated index/parameter information into smart contracts implementing parametric insurance policies.
* Huge efficiency gains with fully automated policies. Once the index/parameter feed is provided reliably to policy contract claims, payout handling may be fully automated for parametric insurance.
* Immediate payouts. Running in a blockchain context and having automated claims/payout handling allows for near-real-time payouts, as no intermediate financial layers need to be considered.
### [](#the_etherisc_model)
The Etherisc model
In general, the Etherisc ecosystem is based on three pillars. Risk transfer market, regulatory framework and technical framework.
With the generic insurance framework (GIF) it is possible to model insurance policies individually.
In each country, the legal and monetary frameworks differ from slightly until to seriously different. Etherisc relies on cooperation with local teams and offers its own insurance policies to a limited extent. Etherisc can support interested parties and help to guide the coordination process with the relevant agencies and ministries.
In the paragraphs below the pillars risk transfer market, legal framework and technical framework are introduced individually.
### [](#the_three_pillars_of_the_etherisc_ecosystem)
The three pillars of the Etherisc ecosystem

#### [](#risk_transfer_market)
Risk transfer market

Raising capital to back the technical guarantees is done by investors. In other words, they are risk capital providers. In this process, investors will lock a certain amount of DIP token - also known as “staking."The staked DIP token are a prerequisite to investing the actual risk capital in DIP or stablecoins. This cryptocurrency is built in a way that it has a stable economic value, e.g., by pegging it to a fiat currency like USD. What is the reason for this? The community of DIP token holders created the entire Etherisc ecosystem. Therefore, we will demand that parties who profit from the ecosystem also own a share by owning and staking DIP token. This idea is borrowed from the space of cooperative enterprises. It reflects that the Etherisc ecosystem is a public good that must be protected from the “tragedy of the commons.”
#### [](#legal_framework)
Legal framework

Insurance companies are highly regulated worldwide for good reasons, to protect customers as well as investors. Regulation ensures, for example, that the policyholder receives the promised compensation in the event of an insurance claim. Most countries have enacted a great deal of legislation for this purpose. Concerning jurisdiction, a general distinction can be made between the American, European and Anglo-Saxon regions.
The financial and organizational hurdles to establishing a new insurance company are high. For specific countries like Germany, Etherisc offers a legal model, where the legal claim is exchanged for a technical guarantee using blockchain and smart contracts. Thus, the provider - in this case Etherisc - is no longer subject to an insurance company’s legal and financial requirements. Still, the legal framework has to be considered for each project, product and jurisdiction, and the product owner is responsible for the proper implementation. The Etherisc team has accumulated a lot of experience in this field and is happy to share these insights with platform users.
#### [](#technical_framework)
Technical framework

The GIF developed and maintained by Etherisc allows to model, deploy and operate insurance products based on blockchain in a decentralized and transparent way.
Using GIF, interested parties may quickly implement and securely operate their insurance products.
### [](#what_is_gif)
What is GIF?

GIF is an acronym and means generic insurance framework. At its core, it consists of a collection of open-source smart contracts that implement essential functions of the lifecycle of insurance products and policies. Thus, GIF enables the modeling of a wide variety of insurance types.
It is a basic implementation that can be used to create blockchain-based insurance applications.
In order to be able to design insurance products quickly and easily, processing steps that run similarly in all products have been identified and made available as modules. Thus, only product-specific aspects such as pricing etc. need to be implemented for each product.
GIF provides these generic functions for all sub-steps in the lifecycle of an insurance policy, thus enabling an automated workflow that controls the sequence of processing steps. The following section will describe these functions and how they work in detail.
### [](#gif_and_gif_instances)
GIF and GIF instances

As introduced above, the GIF provides the means to model and implement specific insurance products and product-specific policy handling based on open-source smart contracts.
To operate insurance products, including selling policies, collecting premiums, calculating trigger events and handling payouts, a complete execution environment is needed in addition to the smart contract collections that define products and policies.
GIF provides these generic functions for all sub-steps in the lifecycle of an insurance policy, thus enabling an automated workflow that controls the sequence of processing steps. The following section will describe these functions and how they work in detail.
The picture below provides an overview of the stakeholder roles involved with a GIF instance.

#### [](#stakeholder_roles)
Stakeholder roles
* **Insured/Customer**
The Insured / customer is the policyholder who wants to pass his risk to the risk pools. He is a customer of the insurance company.
* **Investor**
Investors have an interest to participate in risk pools to balance/diversify their risk portfolios. Investors provide collateral for risk pools in exchange for interest payments.
* **Oracle owner**
The oracle owner provides oracles that interface between the blockchain smart contracts and external data sources. For example, in the case of flight delay insurance, the oracle informs the smart contract whether the flight landed in time, how much it was delayed or if it was canceled entirely. For weather index insurance, an oracle could provide historical and real-time weather data like rainfall, wind speed, etc.
* **Product owner**
The product owner designs and operates one or more products. This would be an insurance company or an MGA (managing general agent) in the traditional insurance industry. Due to the multi-client capability, a product owner can use all oracles located on the respective platform by the oracle owners.
* **Risk pool keeper**
A risk pool keeper manages one or more risk pools. A risk pool is a smart contract that assigns (“pools”) several risks, represented by policy objects, to risk capital.
Risk pools can collect collateral that investors invest in. Risk investors allocate and lock DIP token and /or stable coins in the risk pool and receive a reward for binding their assets. This process is called “staking.” Losses are paid from the risk pool. Therefore, the capital in the pool (more specifically, the stablecoin part of the pool) is at risk. Investors can top up their investments in the risk pool and withdraw their funds. However, before withdrawing their funds, the risks they bear must expire or be paid out.
DIP tokens link to access risk pools to investors who have also invested in the platform represented by this GIF instance.
* **Instance operator**
The GIF is a framework, i.e., a collection of open-source smart contracts. Any complete deployment of this framework is called a “GIF instance”. There will always be at least one complete instance of the GIF which is operated by the Etherisc project, but in principle, anybody can deploy a new GIF instance. The instance operator is the key role which operates a specific GIF instance.

The key responsibilities of the instance operator are the administration of products and oracles (as introduced above) and a few other basic actions. Any GIF instance is multi-client capable, which means that any number of product owners and oracle providers can be operated and administered on one GIF instance. Due to the different legal regulations for insurances worldwide, it can turn out that different GIF instances and, therefore, several instance operators are required.
The instance operator is represented by an Ethereum address. Therefore, the instance operator could be a natural person owning the private key of that address or a smart contract - either a multisig (a digital signature scheme that allows a group of people to sign a single document) or a DAO (d\\Decentralized Autonomous Organisation) structure. This enables a completely decentralized operation of any GIF instance. One address can, of course, manage several independent GIF instances.
The dedicated goal of the Etherisc Project is that control over all GIF instances will be handed over to DAOs controlled by the platform’s stakeholders (customers, product owners, oracle owners and risk pool keepers).
### [](#generic_lifecycle_functions_in_gif)
Generic lifecycle functions in GIF
#### [](#core_objects_of_the_gif)
Core objects of the GIF
Any instance of the GIF maintains collections of three basic objects:
* Products
* Oracles
* Risk pools
Each object has its own lifecycle, which we discuss in the next paragraphs.
These three basic objects are connected by the framework to execute the lifecycle of insurance policies, which are also maintained as objects in the framework.
#### [](#product_lifecycle)
Product lifecycle

The product life cycle defines the stages a new product will undergo.
A product is a specific smart contract that implements the functionality of this product. The product can implement its specific requirements, or it can use the generic functionality of the GIF. After the product is technically developed and deployed to the blockchain, it must be registered in the GIF instance. This action is typically integrated in the deployment process.
The GIF instance offers the following functions to the product owner for this:
* `registerProduct`
After registering a product, it needs to be approved by the instance operator. The instance operator will check the details, such as no malicious code in the product contract, and may impose other requirements for approval of the product. A possible and likely requirement is that the product owner stakes a certain amount of DIP token in a particular contract and then must be actively selling products and earning money on the platform.
Approval is made by the instance operator using the function
* `approveProduct`
After approval of the product, the product is active and can start selling policies.
Should there be a change in terms imply a re-deployment of the product, the old product needs to be deactivated. For this, the GIF instance offers two functions:
* `pauseProduct`
A product which shouldn’t be sold anymore, or is defective, can be paused.
* `unpauseProduct`
This reverses the effect of `pauseProduct`.
#### [](#oracle_lifecycle)
Oracle lifecycle

Oracles form a vital part of the GIF, as they link the blockchain-based smart contracts and the index / parameter information necessary to operate real-world insurance products.
Products can utilize product-specific oracles, but they can also make use of generic oracles, which can, in turn, be implemented by many different parties.
For example, the FlightDelay ratings oracle has one input parameter, the carrier/flight number combination, and one output parameter, an array of integers which represent the historical number of delays for different amounts of delays.
There can be an arbitrary number of oracles implementing this service.
An oracle owner can propose oracles that they would like to offer (in case of the oracle owner) or use (in case of the product owner). The instance operator checks the suggested oracles and activates them after successfully checking. The instance operator can deactivate or remove the oracle as well, if necessary.
The following functions are available for oracles:
* `proposeOracle` (oracle owner)
* `activateOracle` (instance operator)
* `deactivateOracle` (instance operator)
* `removeOracle` (instance operator)
#### [](#risk_pool_lifecycle)
Risk pool lifecycle

The risk pool lifecycle will be described here as soon as the implementation is published.
#### [](#policy_lifecycle)
Policy lifecycle

Independent of the specific product, each policy that is processed on the GIF instance has a lifecycle. Typically, a policy undergoes several state changes during the lifecycle. While any product designer could implement his own lifecycle (in our terminology, the life cycle is called “PolicyFlow”), the GIF offers a default lifecycle which should be sufficient for most use cases. This generic life cycle is called “PolicyFlowDefault”.
The “PolicyFlowDefault” lifecycle offers the following functions:
1. `_newApplication` (to generate and store a new application from a customer)
2. `_underwrite` (to sign an application and create a new policy)
3. `_decline` (to reject an application)
4. `_newClaim` (to generate and store a new claim in case of loss)
5. `_confirmClaim` (to confirm a claim and create a payout)
6. `_declineClaim` (to reject a claim)
7. `_payout` (to confirm and initiate a payout)
The names of these functions start with an underscore to indicate that they are internal functions that you can override in your product. For example, you are free to have the newApplication function in your contract and also use \_newApplication in it.
#### [](#payments)
Payments
The GIF instance is agnostic to the way payments are made. Therefore, we don’t offer specific functionality for this.
Pure crypto payments can be made directly to the product contract, while fiat payments need a fiat gateway and potentially an external banking or credit card infrastructure.
Information on how to implement fiat gateways can be requested from the core team.
[← DIP Staking FAQ](/learn/staking-faq)
[The GIF sandbox - a place to learn and experiment →](/learn/sandbox)
---
# Developing smart contracts - Etherisc Docs
Developing smart contracts
==========================
Welcome to the exciting world of smart contract development! This guide will let you get started writing Solidity contracts by going over the following:
* [Setting up a Solidity Project](#setting-up-a-solidity-project)
* [Compiling Solidity Source Code](#compiling-solidity-source-code)
* [Adding More Contracts](#adding-more-contracts)
* [Using OpenZeppelin Contracts](#using-openzeppelin-contracts)
[](#about_solidity)
About Solidity
----------------------------------
We won’t cover language concepts such as syntax or keywords in this guide. For that, you’ll want to check out the following curated content, which feature great learning resources for both newcomers and experienced developers:
* For a general overview of how Ethereum and smart contracts work, the official website hosts a [Learn about Ethereum](https://ethereum.org/learn/)
section with lots of beginner-friendly content.
* If you’re new to the language, the [official Solidity documentation](https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html)
is a good resource to have handy. Take a look at their [security recommendations](https://solidity.readthedocs.io/en/latest/security-considerations.html)
, which nicely go over the differences between blockchains and traditional software platforms.
* Consensys' [best practices](https://consensys.github.io/smart-contract-best-practices/)
are quite extensive, and include both [proven patterns](https://consensys.github.io/smart-contract-best-practices/development-recommendations/)
to learn from and [known pitfalls](https://consensys.github.io/smart-contract-best-practices/attacks/)
to avoid.
* The [Ethernaut](https://ethernaut.openzeppelin.com/)
web-based game will have you look for subtle vulnerabilities in smart contracts as you advance through levels of increasing difficulty.
With that out of the way, let’s get started!
[](#setting-up-a-solidity-project)
Setting up a Project
-------------------------------------------------------
The first step after [creating a project](#setting-up-a-node-project.adoc#creating-a-project)
is to install a development tool.
The most popular development framework for Ethereum is [Hardhat](https://hardhat.org/)
, and we cover its most common use with [ethers.js](https://docs.ethers.io/)
. The next most popular is [Truffle](https://www.trufflesuite.com/truffle)
which uses [web3.js](https://web3js.readthedocs.io/)
. Each has their strengths and it is useful to be comfortable using all of them.
In these guides we will show how to develop, test and deploy smart contracts using Truffle and Hardhat.
| | |
| --- | --- |
| | Instructions are available for both Truffle and Hardhat. Choose your preference using this toggle!
Toggle Hardhat or Truffle |
To get started with Truffle we will install it in our [project directory](#setting-up-a-node-project.adoc#creating-a-project)
.
$ npm install --save-dev truffle
Once installed, we can initialize Truffle. This will create an empty Truffle project in our project directory.
$ npx truffle init
Starting init...
================
> Copying project files to /home/openzeppelin/learn
Init successful, sweet!
To get started with Hardhat we will install it in our [project directory](#setting-up-a-node-project.adoc#creating-a-project)
.
$ npm install --save-dev hardhat
Once installed, we can run `npx hardhat`. This will create a Hardhat config file (`hardhat.config.js`) in our project directory.
$ npx hardhat
888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888
Welcome to Hardhat v2.2.1
✔ What do you want to do? · Create an empty hardhat.config.js
Config file created
[](#first-contract)
First contract
----------------------------------
We store our Solidity source files (`.sol`) in a `contracts` directory. This is equivalent to the `src` directory you may be familiar with from other languages.
We can now write our first simple smart contract, called `Box`: it will let people store a value that can be later retrieved.
We will save this file as `contracts/Box.sol`. Each `.sol` file should have the code for a single contract, and be named after it.
// contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Box {
uint256 private _value;
// Emitted when the stored value changes
event ValueChanged(uint256 value);
// Stores a new value in the contract
function store(uint256 value) public {
_value = value;
emit ValueChanged(value);
}
// Reads the last stored value
function retrieve() public view returns (uint256) {
return _value;
}
}
[](#compiling-solidity-source-code)
Compiling Solidity
------------------------------------------------------
The Ethereum Virtual Machine (EVM) cannot execute Solidity code directly: we first need to compile it into EVM bytecode.
Our `Box.sol` contract uses Solidity 0.8 so we need to first [configure Truffle to use an appropriate solc version](https://truffleframework.com/docs/truffle/reference/configuration#compiler-configuration)
.
We specify a Solidity 0.8 solc version in our `truffle-config.js`.
// truffle-config.js
...
// Configure your compilers
compilers: {
solc: {
version: "0.8.4", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
// settings: { // See the solidity docs for advice about optimization and evmVersion
// optimizer: {
// enabled: false,
// runs: 200
// },
// evmVersion: "byzantium"
// }
}
},
...
Our `Box.sol` contract uses Solidity 0.8 so we need to first [configure Hardhat to use an appropriate solc version](https://hardhat.org/config/#solidity-configuration)
.
We specify a Solidity 0.8 solc version in our `hardhat.config.js`.
// hardhat.config.js
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
};
Compiling can then be achieved by running a single compile command:
| | |
| --- | --- |
| | If you’re unfamiliar with the `npx` command, check out our [Node project setup guide](#setting-up-a-node-project.adoc#using-npx)
. |
$ npx truffle compile
Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
✔ Downloading compiler. Attempt #1.
> Compiling ./contracts/Box.sol
> Compiling ./contracts/Migrations.sol
> Artifacts written to /home/openzeppelin/learn/build/contracts
> Compiled successfully using:
- solc: 0.8.4+commit.c7e474f2.Emscripten.clang
The [`compile`](https://www.trufflesuite.com/docs/truffle/reference/truffle-commands#compile)
command will automatically look for all contracts in the `contracts` directory, and compile them using the Solidity compiler using the configuration in [`truffle-config.js`](https://www.trufflesuite.com/docs/truffle/reference/configuration#compiler-configuration)
.
You will notice a `build/contracts` directory was created: it holds the compiled artifacts (bytecode and metadata), which are .json files. It’s a good idea to add this directory to your `.gitignore`.
$ npx hardhat compile
Solidity 0.8.4 is not fully supported yet. You can still use Hardhat, but some features, like stack traces, might not work correctly.
Learn more at https://hardhat.org/reference/solidity-support"
Compiling 1 file with 0.8.4
Compilation finished successfully
The [`compile`](https://hardhat.org/guides/compile-contracts.html#compiling-your-contracts)
built-in task will automatically look for all contracts in the `contracts` directory, and compile them using the Solidity compiler using the configuration in [`hardhat.config.js`](https://hardhat.org/config/#solidity-configuration)
.
You will notice an `artifacts` directory was created: it holds the compiled artifacts (bytecode and metadata), which are .json files. It’s a good idea to add this directory to your `.gitignore`.
[](#adding-more-contracts)
Adding more contracts
------------------------------------------------
As your project grows, you will begin to create more contracts that interact with each other: each one should be stored in its own `.sol` file.
To see how this looks, let’s add a simple access control system to our `Box` contract: we will store an administrator address in a contract called `Auth`, and only let `Box` be used by those accounts that `Auth` allows.
Because the compiler will pick up all files in the `contracts` directory and subdirectories, you are free to organize your code as you see fit. Here, we’ll store the `Auth` contract in an `access-control` subdirectory:
// contracts/access-control/Auth.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Auth {
address private _administrator;
constructor(address deployer) {
// Make the deployer of the contract the administrator
_administrator = deployer;
}
function isAdministrator(address user) public view returns (bool) {
return user == _administrator;
}
}
To use this contract from `Box` we use an `import` statement, referring to `Auth` by its relative path:
// contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Import Auth from the access-control subdirectory
import "./access-control/Auth.sol";
contract Box {
uint256 private _value;
Auth private _auth;
event ValueChanged(uint256 value);
constructor() {
_auth = new Auth(msg.sender);
}
function store(uint256 value) public {
// Require that the caller is registered as an administrator in Auth
require(_auth.isAdministrator(msg.sender), "Unauthorized");
_value = value;
emit ValueChanged(value);
}
function retrieve() public view returns (uint256) {
return _value;
}
}
Separating concerns across multiple contracts is a great way to keep each one simple, and is generally a good practice.
However, this is not the only way to split your code into modules. You can also use _inheritance_ for encapsulation and code reuse in Solidity, as we’ll see next.
[](#using-openzeppelin-contracts)
Using OpenZeppelin Contracts
--------------------------------------------------------------
Reusable modules and libraries are the cornerstone of great software. [**OpenZeppelin Contracts**](../contracts/2.x/)
contains lots of useful building blocks for smart contracts to build on. And you can rest easy when building on them: they’ve been the subject of multiple audits, with their security and correctness battle-tested.
### [](#about_inheritance)
About inheritance
Many of the contracts in the library are not standalone, that is, you’re not expected to deploy them as-is. Instead, you will use them as a starting point to build your own contracts by adding features to them. Solidity provides _multiple inheritance_ as a mechanism to achieve this: take a look at the [Solidity documentation](https://solidity.readthedocs.io/en/latest/contracts.html#inheritance)
for more details.
For example, the [`Ownable`](#contracts:api:ownership.adoc#Ownable)
contract marks the deployer account as the contract’s owner, and provides a modifier called `onlyOwner`. When applied to a function, `onlyOwner` will cause all function calls that do not originate from the owner account to revert. Functions to [transfer](#contracts:api:ownership.adoc#Ownable-transferOwnership-address-)
and [renounce](#contracts:api:ownership.adoc#Ownable-renounceOwnership--)
ownership are also available.
When used this way, inheritance becomes a powerful mechanism that allows for modularization, without forcing you to deploy and manage multiple contracts.
### [](#importing_openzeppelin_contracts)
Importing OpenZeppelin Contracts
The latest published release of the OpenZeppelin Contracts library can be downloaded by running:
$ npm install @openzeppelin/contracts
| | |
| --- | --- |
| | You should always use the library from these published releases: copy-pasting library source code into your project is a dangerous practice that makes it very easy to introduce security vulnerabilities in your contracts. |
To use one of the OpenZeppelin Contracts, `import` it by prefixing its path with `@openzeppelin/contracts`. For example, in order to replace our own [`Auth`](#auth-contract)
contract, we will import `@openzeppelin/contracts/access/Ownable.sol` to add access control to `Box`:
// contracts/Box.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Import Ownable from the OpenZeppelin Contracts library
import "@openzeppelin/contracts/access/Ownable.sol";
// Make Box inherit from the Ownable contract
contract Box is Ownable {
uint256 private _value;
event ValueChanged(uint256 value);
// The onlyOwner modifier restricts who can call the store function
function store(uint256 value) public onlyOwner {
_value = value;
emit ValueChanged(value);
}
function retrieve() public view returns (uint256) {
return _value;
}
}
The [OpenZeppelin Contracts documentation](../contracts/2.x/)
is a great place to learn about developing secure smart contract systems. It features both guides and a detailed API reference: see for example the [Access Control](#contracts::access-control.adoc)
guide to know more about the `Ownable` contract used in the code sample above.
[](#next_steps)
Next steps
--------------------------
Writing and compiling Solidity contracts are but the first steps in the journey to having your decentralized application running on the Ethereum network. Once you are comfortable with this setup, you’ll want to move on to more advanced tasks:
* [Deploying and Interacting](deploying-and-interacting)
* [Writing Automated Tests](#writing-automated-tests.adoc)
* [Connecting to Public Test Networks](#connecting-to-public-test-networks.adoc)
---
# Staking as a fundamental building block for insurance - Etherisc Docs
Staking as a fundamental building block for insurance
=====================================================
Hello and welcome to part three of Etherisc’s tutorial series. Today, we’ll start diving into the meaning and functionality of ‘staking’ in the context of decentralized insurance. In what is a complex topic, we’re dividing this tutorial into two. Here we will examine the general principals and applications of staking, with part two to follow and explore the more financial and technical details of staking as related to Etherisc.
Before reading on, please do also check out our tutorial [Basics about the GIF framework](https://docs.etherisc.com/learn/basics-gif/)
. We’d highly recommend it as it provides an excellent overview of Etherisc’s platform, along with facts about insurance, parametric insurance, and much more.
The term ‘staking’ is used in abundance in the world of decentralized finance and blockchain, and so it’s worth exploring its different meanings before we dive into the specific use of the term in the domain of decentralized insurance.
We will discuss different types of staking, the advantages and disadvantages of each, and finally, how we use staking to coordinate various stakeholders in a decentralized insurance ecosystem. We also describe the current state of staking in Etherisc’s Generic Insurance Framework (GIF) and give an outlook on our planned next steps.
[](#mining)
Mining
------------------
The origins of staking in decentralized finance stem from the use of staking in blockchain consensus algorithms. Let’s have a look at how the production (mining) of blocks in a blockchain works — in other words, how value is created in coins, gas, and transaction fees on a blockchain. Due to its decentralized nature, block production needs to be controlled and coordinated either through high effort (and energy) processes or other mechanisms, such as depositing collateral. If the production process was effortless, everyone would do it — opening the door for so-called ‘Sybil attacks’ which would leave the coins worthless. A Sybil attack is an attack on peer-to-peer networks by creating false identities. The attack can be aimed at influencing majority voting and network organization, slowing down the grid, disrupting networking, or intercepting communications between peers.
The two currently most popular ways to create blocks and avoid such an attack are proof of work (PoW) and proof of stake (PoS).
[](#proof_of_work)
Proof of Work
--------------------------------

The principle of proof of work is based on the idea that miners bundle transactions to blocks and prove that they have invested a certain amount of computational effort, which in turn is connected to energy consumption and therefore economic capital. This effort makes it prohibitively expensive for a single miner to take control of the network.
Proof of work typically means that the miner must calculate a verifiable block hash that meets predefined criteria. For this, the miner needs to systematically repeat these calculations with different so-called nonce (number used once) values. These calculations make mining a very computation-intensive process that requires specialized hardware and a lot of electrical power. For this reason, miners often join together in mining pools. Once a block is created, the miner or mining pool receives the transaction fees of the transactions contained in the block and a block reward in the form of the native coin of the blockchain, for example Bitcoin.
Proof of work is currently the predominant consensus method used by most major blockchains, including Bitcoin, its variants and layer 2 blockchains.
There are a lot of disadvantages connected to proof of work, starting with its vast energy consumption and associated ecological footprint. Additionally, there is also a tendency towards a form of centralization because only big players have access to the required specialized hardware needed to process a block, with the added fact that there is a monopoly of manufacturers producing this hardware.
[](#proof_of_stake)
Proof of Stake
----------------------------------

Because of the apparent disadvantages of PoW, there has been extensive research on alternative consensus models. One method which solves most of the core problems raised by PoW, is proof of stake (PoS). In PoS, the validator (node) must deposit coins in a particular cryptocurrency if it wants to create blocks for that network, and the process of depositing coins is called ‘staking.’
Proof of stake networks use complex algorithms to determine the validator of the next block, and they need mechanisms to recover from different types of validator misbehavior. As in the case of successful PoW mining nodes, the selected validator nodes in a PoS network are rewarded with transaction fees and block rewards.
The more stakes a validator has, the more voting rights it has or the more of a say it has. You can compare this process to a public limited company or a cooperative: the more shares you own in the company, the more voting rights you have in decisions.
[](#what_is_staking)
What is staking?
-------------------------------------

This all leads us to our discussion on staking. While originating from consensus research for blockchains, staking has become a fundamental primitive for decentralized finance (DeFi).
Staking crypto assets in the blockchain world is the process of actively participating in securing a blockchain-based protocol. So in staking, blockchain users lock their crypto assets as collateral for some protocol ‘value,’ thus ensuring the proper functioning of the protocol. The value could be some desirable property of the protocol, be it protection from sybil attacks, collateralization of a lending protocol, ensuring the compliant behavior of protocol participants, and so on. Because of its flexibility, staking has become a widely used primitive of many blockchain protocols.
Staking is always connected with a specific risk. Even if the protocol would not incorporate any risk, locking crypto assets for a certain time always incurs the risk of loss of value because of market price action. To compensate for the risk the stakers take, they receive rights and/or rewards.
Staking can be implemented in different ways. Participants contribute to a staking pool and receive rights and rewards directly, or they use an intermediary — the so-called ‘Delegated Proof of Stake’ (DPoS).
A special case of staking occurs with governance tokens. Governance tokens are blockchain tokens that grant voting and management power to their users. Some of you may have followed the vote regarding the listing of our DIP token (cryptocurrency of Etherisc) on Bancor. Here, all registered voters had the opportunity to participate in the decision. Many did too, and Bancor whitelisted our DIP token with almost 100% approval from the voters. Staking and governance in action!
[](#insurance_in_a_few_words)
Insurance — in a few words
--------------------------------------------------------
Before we get into the details of the requirements for staking in the decentralized insurance domain and how our new implementation will meet these requirements, let’s look at the essential function of insurance.
While insurance could be described broadly as ‘a means of protecting against financial loss,’ the term is usually defined in much more detail. Insurance protects against financial loss, usually by pooling a large number of similar risks, thus spreading the risk across all those insured.
### [](#an_example)
An example
Let’s have a look at fire insurance. We’ll make some assumptions to keep the numbers simple, in reality the numbers are different, but you’ll get the idea. If you own a house worth $100,000, there is an assumed risk of 1% per year that the house will burn down (that’s once in a century). Without insurance, if you want to make sure you always have a home, you need to have an additional $100,000 on top of the $100,000 you invested in the home to replace it in the event of a fire. This additional $100,000 may be challenging to come by, and it is very inefficient to have $100,000 in a bank account for an event that occurs on average only once in a century.
### [](#step_in_insurance)
Step in insurance
If 1,000 homeowners pool their risks, there are 10 homes worth $1 million that will burn down each year based on an anticipated fire risk of 1%. So, each homeowner only has to pay $1,000 as a premium into a risk pool to cover that ‘expected loss’ (the $1 million divided by the 1,000 homeowners).
This works well as long as there are no conflagrations. In the worst-case scenario, if more than 10 homes burn down in a catastrophic event, the pool will not be able to cover that loss. Examples of such devastating events include wildfires, hurricanes, and other natural events, as well as pandemics, terrorist attacks, and other man-made events, also called ‘black swan events.’
So what to do? The answer is to ask investors to add risk capital to the risk pool.
### [](#long_tail_risks)
Long-tail risks
Suppose the probability of a conflagration burning down 100 homes is 0.1% per year (once every 1,000 years on average). The damage is $10 million. These high but implausible risks are also called ‘long-tail risks’ because they are represented by the ‘long tail’ of the risk distribution curve:

_\*Visualization of the '\`long tail.’_
In addition to the $1 million paid by premiums, you need another $9 million from investors. For example, they will charge a compound interest risk of, say, 5%, which equates to $450,000, so each homeowner would incur another $450. But with a total premium of $1,450, they are now insured not only against the typical risk of 10 burned homes per year but also against the risk of a once-in-a-millennium conflagration and everything in between.
Investors must commit their capital for the entire lifetime of the insurance policy because otherwise, they could move out of their capital as soon as there are signs that a ‘Black Swan event’ is becoming more likely. And, of course, the groups of insureds and investors could also overlap.
Traditional insurance features very high administrative fees on top of this lifelong $1,450 premium, which can be done away with by using decentralized blockchain-based insurance.
[](#staking_for_risk_pools)
Staking for risk pools
--------------------------------------------------
Now, let’s outline the core features of Etherisc’s staking model and risk pools. You can study the model in more depth in our paper The Etherisc Staking Model, and we will dive into the topic even further in the upcoming part two of this blog.
### [](#the_concept_of_risk_pools)
The concept of risk pools
A risk pool is a smart contract that collects funds that are used to compensate for insurance claims.
In its simplest form, a risk pool could be a multi-signature that would be funded by some interested parties, be it investors or product owners. The risk pool is registered in the GIF (Generic Insurance Framework), approved by the Instance Operator and connected to one or more products that are registered in the same GIF instance.
The party which organizes the risk pool is called a ‘risk pool keeper.’ Premiums from purchase of policies are paid into the risk pool, and claims are covered from the funds of the risk pool. In this most simple form, investors have little control over their investments, therefore the risk pool and its keeper need to be trusted by the investors. To address this need, we have developed a concept that enables us to launch trust-free risk pools which can be operated in a decentralized way.
### [](#trustless_risk_pools)
Trustless risk pools
For a trustless risk pool to function, methods must be implemented that technically and transparently guarantee that the interests of both insured and investors are met.
For the insured, this means that we can prove that the risk pool will always be able to fulfill claims.
For investors, this means that they will receive a fair share of the profits made, and that they can decide for which risks they will engage with their funds.
For both, this also means that the risk pool needs to be economically attractive for investors, without whom there may not be enough capital to enable the purchase of policies.
It is clear that it is challenging to design smart contracts which fulfill all of these guarantees, given that the amount of calculation involved on-chain needs to be limited.
While we expect that sooner or later, e.g. with the further rapid development of zero-knowledge-proofs, it will be possible to perform arbitrary complex, untrusted computations reliably off-chain and verify the results on-chain. This brings the need to devise a system which is somehow simplified, can be run fully on-chain and still meets the mentioned requirements.
We achieve this goal by using so-called ‘epochs.’ An epoch is a period of time that is typically a small fraction of the average period of a policy. For example, flight delay policies typically have a period of a few days to a few weeks as the maximum. A good choice for the duration of an epoch would then be a week. For crop insurance, the period of the policy is typically some months, so a good choice for the duration of an epoch would be one month.
For each epoch, all policies which are sold in this epoch are handled equally. This step massively reduces complexity.
[](#core_functions_of_a_risk_pool)
Core functions of a risk pool
----------------------------------------------------------------
Each risk pool needs to provide a minimum interface to be able to meet the requirements.
### [](#receiving_premiums)
Receiving premiums
Each risk pool needs a function that enables the risk pool to receive premium payments. The function may only be called by a registered and approved product contract in a GIF instance. Premium payments can be made in the form of a native token of a blockchain (e.g. xDai on the Gnosis Chain, or ETH on Ethereum Mainnet), or in the form of a stablecoin (e.g. USDC).
### [](#claims_payout)
Claims payout
Each risk pool needs a function that will payout a claim in case of a loss. The amount of the payout and the decision if a certain loss will trigger a payout is controlled by the product contract. Therefore, this function may only be called by a registered and approved product contract in a GIF instance. The product contract also needs to specify in which token or currency the payout is made.
### [](#receiving_investment_deposits)
Receiving investment deposits
Each risk pool needs a function to receive investments. Investments can be made in any currency or token which is specified by the risk pool keeper. Investments need to be registered in the risk pool, so that an investor can always check the status of his investment and the share of profit he makes during his investment.
The risk pool keeper may provide additional requirements from an investor, e.g. KYC. The GIF framework supports the implementation of such requirements, but they are not enforced by the framework — it’s the responsibility of the risk pool keeper to enforce them.
### [](#processing_investment_withdrawals)
Processing investment withdrawals
No investor wants to invest for an unbounded time, so we need to provide a mechanism that allows withdrawal of investments.
This mechanism is designed in a way that ensures that there are always sufficient funds available to cover losses.
The bookkeeping system which tracks investment deposits and withdrawals is the most complex part of the system.
### [](#processing_profit_distribution)
Processing profit distribution
Part of the premiums paid are used as revenue for investors. Investors lock their capital for a certain period of time and risk losing all or part of their investment. Therefore, a revenue is needed to make an investment attractive.
Profit and revenue need to be distributed among investors in a transparent and fair way, according to the time the funds have been locked, and the risk taken.
The distribution mechanism is another complex process and will be described in the upcoming part two of this tutorial in more detail.
### [](#autonomous_control_of_risk_pool_parameters)
Autonomous control of risk pool parameters
Risk pools vary in size, depending on the demand of the underlying product. We will provide mechanisms that will enable autonomous control of risk pool parameters so the risk pool will reflect increasing demand of the product by increasing the attractiveness for investors, and vice versa.
Therefore, a risk pool can be connected to a product with a feedback loop. Should the demand for a product increase, the risk pool could increase investors’ revenue to make the risk pool more attractive for further investments.
On the other hand, given that there is a lot of capital available, the risk pool could trigger a price adjustment to make the product more attractive on the market.
[](#conclusion)
Conclusion
--------------------------
The core economic process of insurance, the risk transfer between insured and investors, is implemented in the GIF framework via risk pools.
While the standard template for risk pools contains all of the core functionality for processing premiums, claims, deposits, withdrawals, and revenue, the template leaves the maximum flexibility for risk pool keepers to design the economic model of their pool in a way that makes it attractive for insureds, product owners and investors.
Thanks for reading part one of this tutorial on staking and risk pools. Stay tuned for part two by following Etherisc across our social channels including Telegram, Twitter, LinkedIn, and Medium!
---
# DIP Token - Etherisc Docs
DIP Token
=========
[](#the_dip_token_is_the_essential_utility_token_of_the_etherisc_ecosystem)
The DIP token is the essential utility token of the Etherisc ecosystem.
------------------------------------------------------------------------------------------------------------------------------------------------------
[](https://www.flickr.com/photos/javh/5448336655)
Get all the information you need about the DIP token as a concentrate on our [DIP Dashboard](https://dune.com/etherisc_dune_wizards/dip-dashboard)
.
[](#dip_utility)
DIP utility
----------------------------
DIP tokens give users access to the Decentralized Insurance Platform. By staking DIP token, participants provide collateral (bond) for risk pools and to guarantee future performance, availability, and service levels. Staking also signals quality and reputation. As a result, participants can earn money monetizing their skills, software (for example risk models or UI/UX), risk capital, insurance licenses, claim processing, or regulatory compliance/reporting services.
[](https://docs.etherisc.com/learn/staking-insurance)
[](https://docs.etherisc.com/learn/basics-gif)
[](https://docs.etherisc.com/gif/governance-model)
[](#the_dip_token_generating_event_tge_jun_23rd_to_july_25th_2018)
The DIP Token Generating Event (TGE) - Jun 23rd to July 25th, 2018
=====================================================================================================================================

[](#revenue_model_for_protocol_users_crypro_investors)
Revenue model for protocol users & crypro investors
==========================================================================================================

---
# Deploying and interacting with smart contracts - Etherisc Docs
Deploying and interacting with smart contracts
==============================================
Unlike most software, smart contracts don’t run on your computer or somebody’s server: they live on the Ethereum network itself. This means that interacting with them is a bit different from more traditional applications.
This guide will cover all you need to know to get you started using your contracts, including:
* [Setting up a Local Blockchain](#local-blockchain)
* [Deploying a Smart Contract](#deploying-a-smart-contract)
* [Interacting from the Console](#interacting-from-the-console)
* [Interacting Programmatically](#interacting-programmatically)
| | |
| --- | --- |
| | Instructions are available for both Truffle and Hardhat. Choose your preference using this toggle!
Toggle Hardhat or Truffle |
[](#local-blockchain)
Setting up a Local Blockchain
---------------------------------------------------
Before we begin, we first need an environment where we can deploy our contracts. The Ethereum blockchain (often called "mainnet", for "main network") requires spending real money to use it, in the form of Ether (its native currency). This makes it a poor choice when trying out new ideas or tools.
To solve this, a number of "testnets" (for "test networks") exist: these include the Sepolia, and Goerli blockchains. They work very similarly to mainnet, with one difference: you can get Ether for these networks for free, so that using them doesn’t cost you a single cent. However, you will still need to deal with private key management, blocktimes in the range of 5 to 20 seconds, and actually getting this free Ether.
During development, it is a better idea to instead use a _local_ blockchain. It runs on your machine, requires no Internet access, provides you with all the Ether that you need, and mines blocks instantly. These reasons also make local blockchains a great fit for [automated tests](#writing-automated-tests.adoc#setting-up-a-testing-environment)
.
| | |
| --- | --- |
| | If you want to learn how to deploy and use contracts on a _public_ blockchain, like the Ethereum testnets, head to our [Connecting to Public Test Networks](#connecting-to-public-test-networks.adoc)
guide. |
The most popular local blockchain is [Ganache](https://github.com/trufflesuite/ganache-cli)
. To install it on your project, run:
$ npm install --save-dev ganache-cli
Upon startup, Ganache will create a random set of unlocked accounts and give them Ether. In order to get the same addresses that will be used in this guide, you can start Ganache in deterministic mode:
$ npx ganache-cli --deterministic
Ganache will print out a list of available accounts and their private keys, along with some blockchain configuration values. Most importantly, it will display its address, which we’ll use to connect to it. By default, this will be `127.0.0.1:8545`.
Keep in mind that every time you run Ganache, it will create a brand new local blockchain - the state of previous runs is **not** preserved. This is fine for short-lived experiments, but it means that you will need to have a window open running Ganache for the duration of these guides. Alternatively, you can run Ganache with the `--db` option, providing a directory to store its data in between runs.
| | |
| --- | --- |
| | **Truffle** has a graphical version of `ganache-cli`, also called [Ganache](https://www.trufflesuite.com/ganache)
. |
Hardhat comes with a local blockchain built-in, the [Hardhat Network](https://hardhat.org/hardhat-network/)
.
Upon startup, Hardhat Network will create a set of unlocked accounts and give them Ether.
$ npx hardhat node
Hardhat Network will print out its address, `[http://127.0.0.1:8545](http://127.0.0.1:8545) `, along with a list of available accounts and their private keys.
Keep in mind that every time you run Hardhat Network, it will create a brand new local blockchain - the state of previous runs is **not** preserved. This is fine for short-lived experiments, but it means that you will need to have a window open running Hardhat Network for the duration of these guides.
| | |
| --- | --- |
| | Hardhat will always spin up an instance of **Hardhat Network** when no network is specified and there is no default network configured or the default network is set to `hardhat`. |
| | |
| --- | --- |
| | You can also run an actual Ethereum node in _[development](https://geth.ethereum.org/getting-started/dev-mode)
[mode](https://wiki.parity.io/Private-development-chain)
_. These are a bit more complex to set up, and not as flexible for testing and development, but are more representative of the real network. |
[](#deploying-a-smart-contract)
Deploying a Smart Contract
----------------------------------------------------------
In the [Developing Smart Contracts guide](#developing-smart-contracts.adoc)
we set up our development environment.
If you don’t already have this setup, please [create](#setting-up-a-node-project.adoc#creating-a-project)
and [setup](#developing-smart-contracts.adoc#setting-up-a-solidity-project)
the project and then [create](#developing-smart-contracts.adoc#first-contract)
and [compile](#developing-smart-contracts.adoc#compiling-solidity-source-code)
our Box smart contract.
With our project setup complete we’re now ready to deploy a contract. We’ll be deploying `Box`, from the [Developing Smart Contracts](#developing-smart-contracts.adoc#box-contract)
guide. Make sure you have a copy of [Box](#developing-smart-contracts.adoc#box-contract)
in `contracts/Box.sol`.
Truffle uses [migrations](https://www.trufflesuite.com/docs/truffle/getting-started/running-migrations)
to deploy contracts. Migrations consist of JavaScript files and a special Migrations contract to track migrations on-chain.
We will create a JavaScript migration to deploy our Box contract. We will save this file as `migrations/2_deploy.js`.
// migrations/2_deploy.js
const Box = artifacts.require('Box');
module.exports = async function (deployer) {
await deployer.deploy(Box);
};
Hardhat doesn’t currently have a native deployment system, instead we use [scripts](https://hardhat.org/guides/deploying.html)
to deploy contracts.
We will create a script to deploy our Box contract. We will save this file as `scripts/deploy.js`.
// scripts/deploy.js
async function main () {
// We get the contract to deploy
const Box = await ethers.getContractFactory('Box');
console.log('Deploying Box...');
const box = await Box.deploy();
await box.deployed();
console.log('Box deployed to:', box.address);
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
We use [ethers](https://github.com/ethers-io/ethers.js)
in our script, so we need to install it and the [@nomiclabs/hardhat-ethers plugin](https://hardhat.org/plugins/nomiclabs-hardhat-ethers.html)
.
$ npm install --save-dev @nomiclabs/hardhat-ethers ethers
Before we deploy we need to configure the connection to ganache. We need to add a development network for localhost and port 8545 which is what our local blockchain is using.
// truffle-config.js
module.exports = {
...
networks: {
...
development: {
host: "127.0.0.1", // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: "*", // Any network (default: none)
},
...
We need to add in our [configuration](https://hardhat.org/config/)
that we are using the `@nomiclabs/hardhat-ethers` plugin.
// hardhat.config.js
require('@nomiclabs/hardhat-ethers');
...
module.exports = {
...
};
Using the [`migrate`](https://www.trufflesuite.com/docs/truffle/reference/truffle-commands#migrate)
command, we can deploy the `Box` contract to the `development` network ([Ganache](#local-blockchain)
):
$ npx truffle migrate --network development
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'development'
> Network id: 1619762548805
> Block gas limit: 6721975 (0x6691b7)
1_initial_migration.js
======================
Deploying 'Migrations'
----------------------
...
2_deploy.js
===========
Deploying 'Box'
---------------
> transaction hash: 0x25b0a326bfc9aa64be13efb5a4fb3f784ffa845c36d049547eeb0f78e0a3108d
> Blocks: 0 Seconds: 0
> contract address: 0xCfEB869F69431e42cdB54A4F4f105C19C080A601
...
| | |
| --- | --- |
| | Truffle will keep track of your deployed contracts, but it also displays their addresses when deploying (in our example, `0xCfEB869F69431e42cdB54A4F4f105C19C080A601`). These values will be useful when interacting with them programmatically. |
Using the `run` command, we can deploy the `Box` contract to the local network ([Hardhat Network](#local-blockchain)
):
$ npx hardhat run --network localhost scripts/deploy.js
Deploying Box...
Box deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
| | |
| --- | --- |
| | Hardhat doesn’t keep track of your deployed contracts. We displayed the deployed address in our script (in our example, `0x5FbDB2315678afecb367f032d93F642f64180aa3`). This will be useful when interacting with them programmatically. |
All done! On a real network this process would’ve taken a couple of seconds, but it is near instant on local blockchains.
| | |
| --- | --- |
| | If you got a connection error, make sure you are running a [local blockchain](#local-blockchain)
in another terminal. |
| | |
| --- | --- |
| | Remember that local blockchains **do not** persist their state throughout multiple runs! If you close your local blockchain process, you’ll have to re-deploy your contracts. |
[](#interacting-from-the-console)
Interacting from the Console
--------------------------------------------------------------
With our `Box` contract [deployed](#deploying-a-smart-contract)
, we can start using it right away.
We will use the [Truffle console](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console)
to interact with our deployed `Box` contract on our local development network.
$ npx truffle console --network development
truffle(development)> const box = await Box.deployed();
undefined
We will use the [Hardhat console](https://hardhat.org/guides/hardhat-console.html)
to interact with our deployed `Box` contract on our localhost network.
| | |
| --- | --- |
| | We need to specify the address of our `Box` contract we displayed in our deploy script. |
| | |
| --- | --- |
| | It’s important that we explicitly set the network for Hardhat to connect our console session to. If we don’t, Hardhat will default to using a new ephemeral network, which our Box contract wouldn’t be deployed to. |
$ npx hardhat console --network localhost
Welcome to Node.js v12.22.1.
Type ".help" for more information.
> const Box = await ethers.getContractFactory('Box');
undefined
> const box = await Box.attach('0x5FbDB2315678afecb367f032d93F642f64180aa3')
undefined
### [](#sending_transactions)
Sending transactions
`Box`'s first function, `store`, receives an integer value and stores it in the contract storage. Because this function _modifies_ the blockchain state, we need to _send a transaction_ to the contract to execute it.
We will send a transaction to call the `store` function with a numeric value:
truffle(development)> await box.store(42)
{ tx:
'0x5d4cc78f5d5eac3650214740728192ac760978e261962736289b10da0ec0ea43',
...
event: 'ValueChanged',
args: [Result] } ] }
Notice how the transaction receipt also shows that `Box` emitted a `ValueChanged` event.
> await box.store(42)
{
hash: '0x3d86c5c2c8a9f31bedb5859efa22d2d39a5ea049255628727207bc2856cce0d3',
...
### [](#querying-state)
Querying state
`Box`'s other function is called `retrieve`, and it returns the integer value stored in the contract. This is a _query_ of blockchain state, so we don’t need to send a transaction:
truffle(development)> await box.retrieve()
> await box.retrieve()
BigNumber { _hex: '0x2a', _isBigNumber: true }
Because queries only read state and don’t send a transaction, there is no transaction hash to report. This also means that using queries doesn’t cost any Ether, and can be used for free on any network.
| | |
| --- | --- |
| | Our `Box` contract returns `uint256` which is too large a number for JavaScript so instead we get returned a big number object. We can display the big number as a string using `(await box.retrieve()).toString()`. |
truffle(development)> (await box.retrieve()).toString()
'42'
> (await box.retrieve()).toString()
'42'
| | |
| --- | --- |
| | To learn more about using the console, check out the [Truffle documentation](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console)
. |
| | |
| --- | --- |
| | To learn more about using the console, check out the [Hardhat documentation](https://hardhat.org/guides/hardhat-console.html)
. |
[](#interacting-programmatically)
Interacting programmatically
--------------------------------------------------------------
The console is useful for prototyping and running one-off queries or transactions. However, eventually you will want to interact with your contracts from your own code.
In this section, we’ll see how to interact with our contracts from JavaScript, and use [Truffle to execute our script](https://www.trufflesuite.com/docs/truffle/getting-started/writing-external-scripts)
with our Truffle configuration.
In this section, we’ll see how to interact with our contracts from JavaScript, and use [Hardhat to run our script](https://hardhat.org/guides/scripts.html)
with our Hardhat configuration.
| | |
| --- | --- |
| | Keep in mind that there are many other JavaScript libraries available, and you can use whichever you like the most. Once a contract is deployed, you can interact with it through any library! |
### [](#setup)
Setup
Let’s start coding in a new `scripts/index.js` file, where we’ll be writing our JavaScript code, beginning with some boilerplate, including for [writing async code](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
.
// scripts/index.js
module.exports = async function main (callback) {
try {
// Our code will go here
callback(0);
} catch (error) {
console.error(error);
callback(1);
}
};
// scripts/index.js
async function main () {
// Our code will go here
}
main()
.then(() => process.exit(0))
.catch(error => {
console.error(error);
process.exit(1);
});
We can test our setup by asking the local node something, such as the list of enabled accounts:
// Retrieve accounts from the local node
const accounts = await web3.eth.getAccounts();
console.log(accounts)
// Retrieve accounts from the local node
const accounts = await ethers.provider.listAccounts();
console.log(accounts);
| | |
| --- | --- |
| | We won’t be repeating the boilerplate code on every snippet, but make sure to always code _inside_ the `main` function we defined above! |
Run the code above using `truffle exec`, and check that you are getting a list of available accounts in response.
$ npx truffle exec --network development ./scripts/index.js
Using network 'development'.
[ '0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1',\
'0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0',\
...\
]
Run the code above using `hardhat run`, and check that you are getting a list of available accounts in response.
$ npx hardhat run --network localhost ./scripts/index.js
[\
'0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\
'0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\
...\
]
These accounts should match the ones displayed when you started the [local blockchain](#local-blockchain)
earlier. Now that we have our first code snippet for getting data out of a blockchain, let’s start working with our contract. Remember we are adding our code _inside_ the `main` function we defined above.
### [](#getting-a-contract-instance)
Getting a contract instance
In order to interact with the [`Box`](#box-contract)
contract we deployed, we’ll use the Truffle contract abstraction, a JavaScript object that represents our contract on the blockchain.
// Set up a Truffle contract, representing our deployed Box instance
const Box = artifacts.require('Box');
const box = await Box.deployed();
In order to interact with the [`Box`](#box-contract)
contract we deployed, we’ll use an [ethers contract instance](https://docs.ethers.io/v5/api/contract/contract/)
.
An ethers contract instance is a JavaScript object that represents our contract on the blockchain, which we can use to interact with our contract. To attach it to our deployed contract we need to provide the contract address.
// Set up an ethers contract, representing our deployed Box instance
const address = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const Box = await ethers.getContractFactory('Box');
const box = await Box.attach(address);
| | |
| --- | --- |
| | Make sure to replace the `address` with the one you got when deploying the contract, which may be different to the one shown here. |
We can now use this JavaScript object to interact with our contract.
### [](#calling-the-contract)
Calling the contract
Let’s start by displaying the current value of the `Box` contract.
We’ll need to call the `retrieve()` public method of the contract, and [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
the response:
// Call the retrieve() function of the deployed Box contract
const value = await box.retrieve();
console.log('Box value is', value.toString());
We’ll need to call the read only `retrieve()` public method of the contract, and [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
the response:
// Call the retrieve() function of the deployed Box contract
const value = await box.retrieve();
console.log('Box value is', value.toString());
This snippet is equivalent to the [query](#querying-state)
we ran earlier from the console. Now, make sure everything is running smoothly by running the script again and checking the printed value:
$ npx truffle exec --network development ./scripts/index.js
Using network 'development'.
Box value is 42
$ npx hardhat run --network localhost ./scripts/index.js
Box value is 42
| | |
| --- | --- |
| | If you restarted your local blockchain at any point, this script may fail. Restarting clears all local blockchain state, so the `Box` contract instance won’t be at the expected address.
If this happens, simply [start the local blockchain](#local-blockchain)
and [redeploy](#deploying-a-smart-contract)
the `Box` contract. |
### [](#sending-a-transaction)
Sending a transaction
We’ll now send a transaction to `store` a new value in our Box.
Let’s store a value of `23` in our `Box`, and then use the code we had written before to display the updated value:
// Send a transaction to store() a new value in the Box
await box.store(23);
// Call the retrieve() function of the deployed Box contract
const value = await box.retrieve();
console.log('Box value is', value.toString());
| | |
| --- | --- |
| | In a real-world application, you may want to [estimate the gas](https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#methods-mymethod-estimategas)
of your transactions, and check a [gas price oracle](https://ethgasstation.info/)
to know the optimal values to use on every transaction. |
// Send a transaction to store() a new value in the Box
await box.store(23);
// Call the retrieve() function of the deployed Box contract
const value = await box.retrieve();
console.log('Box value is', value.toString());
| | |
| --- | --- |
| | In a real-world application, you may want to [estimate the gas](https://docs.ethers.io/v5/api/contract/contract/#contract-estimateGas)
of your transactions, and check a [gas price oracle](https://ethgasstation.info/)
to know the optimal values to use on every transaction. |
We can now run the snippet, and check that the box’s value is updated!
$ npx truffle exec --network development ./scripts/index.js
Using network 'development'.
Box value is 23
$ npx hardhat run --network localhost ./scripts/index.js
Box value is 23
[](#next_steps)
Next steps
--------------------------
Now that you know how to set up a local blockchain, deploy contracts and interact with them both manually and programmatically, you will need to learn about testing environments, public test networks and going to production:
* [Writing Automated Tests](#writing-automated-tests.adoc)
* [Connecting to Public Test Networks](#connecting-to-public-test-networks.adoc)
* [Preparing for Mainnet](preparing-for-mainnet)
---
# Depeg protection tutorial - Etherisc Docs
Depeg protection tutorial
=========================
[](#introduction)
Introduction
------------------------------
### [](#what_is_a_stablecoin)
What is a stablecoin?
Stablecoins, in other words, pegged cryptocurrency, is a coin, token, or asset on a blockchain tied to a currency issued by a government or bank.
Fiat-linked cryptocurrencies are considered examples of stablecoins. They were created to deal with extreme fluctuations. Most stablecoins are pegged to the US dollar. There are also stablecoins in EUR or GBP.

Each stablecoin is designed to have a FIAT monetary value in reserve. Some are issued when the same amount of fiat money is deposited. Others use algorithms to stabilize their coins.
Stablecoins stabilize their price by decreasing or increasing the overall amount of supply. The changes in token supply change the relative price of each token until it reaches the same price as the FIAT currency.
Stablecoins with collateral tokens, such as USDT and DAI, are mined and burned as needed, with the newly minted tokens backed by other digital assets.
Algorithmic stablecoins stabilize through smart contracts and other mechanisms that automatically adjust the supply of the stablecoin to maintain its peg to the underlying asset.
### [](#what_is_a_depeg)
What is a depeg?
A 'peg' is a fixed price for the exchange rate between two assets. This minimizes trading risks and provides planning security.
In cryptocurrencies, a peg refers to stablecoins pegged to a FIAT currency.
Depeg refers to the event of the FIAT-Peg exchange rate drifting apart. The stablecoin is no longer stable and loses value. Trust is lost, many people exchange into other stablecoins and the depegged stablecoin crashes.
USDC, for example, is a fully reserved-backed stablecoin, meaning every USD Coin is backed by actual cash and short-dated United States treasuries.
Despite this, USDC issuers, Circle, announced 2023 on March 10 that USDC had depegged from the U.S. dollar, with around $3.3 billion of its $40 billion in USDC reserves stuck in the now defunct Silicon Valley Bank.
The bank — the 16th-largest in the U.S. — collapsed on March 10 and is one of the biggest bank failures in U.S. history. Given USDC’s collateral influence, other stablecoins followed suit in de-pegging from the U.S. dollar.
On March 11, the USDC-USD rate collapsed to 0.878874 cents. On March 13, the USDC was worth 0.99 cents again. Since then, the USDC has been stable. This scenario would have triggered a depeg event in the smart contracts of our depeg protection product.
This event occurred during our testing phase of the finalized Etherisc depeg protection web app. In our web app, you can protect USDC against a depeg event. At the first moment, we were scared. Then came the conviction for having designed precisely the right product at the right time!
[](#purchasing_depeg_protection)
Purchasing depeg protection
------------------------------------------------------------
You may be able to view a few things if you still need to connect your wallet, but we recommend connecting your wallet as a first step.
You can protect your USDC against a depeg event by buying a policy in the [Etherisc depeg protection web app](https://depeg.etherisc.com/)
. The web app will show you all the risk bundles that match your request and select the risk bundle with the best conditions from your point of view.
In the web app, you can also stake USDT as an investor. Each investor creates his risk bundle in the amount of the deposited token. Each investor can set his conditions, terms, etc., during the creation of the Bundle. Once created, these conditions cannot be changed during the term of the risk bundle.
### [](#apply_for_usdc_depeg_protection)
Apply for USDC depeg protection
Connect your wallet with our [Etherisc depeg protection web app](https://depeg.etherisc.com)
on the Ethereum mainnet and ensure your wallet holds a small amount of ETH to afford the transaction fees.
'Apply for USDC pepeg protection' is the landing page in the web app. You can also access them by clicking the 'Depeg Protection' or the 'Apply' button. You can also click 'APPLY FOR NEW POLICY' in the upper right corner of the 'Policies' section. You can purchase a policy and protect your USDC against a depeg case here.

**Here are the input options:**
#### [](#protected_wallet)
Protected wallet
The field is filled with your wallet ID if you have logged in with your wallet. You can also enter another wallet ID and protect USDC. At the time of policy application, we do not check whether there are USDC in the wallet.
So you can buy a policy without having USDC. However, you cannot bet on a depeg. In the depeg case, we check how many USDC you have in your protected wallet and payout according to the number. The maximum compensation you will get is the number of protected USDC in the policy. If the USDC balance on an actual depeg is lower than the protected USDC, only the actual balance at depeg time is covered.
You can purchase multiple policies for the same protected wallet holding USDC. The product will not compensate for more than the USDC balance at depeg time, independent of how much protection you bought.
We determine the number of USDC in the secured wallet using the [Moralis balance API](https://docs.moralis.io/web3-data-api/evm/balance-api)
.
#### [](#protected_amount)
Protected amount
Here you enter the USDC volume you want to protect against a depeg.
* the minimum volume is 2,000 USDC
* the maximum volume is 100,000 USDC. The maximum is also limited by the available risk capital in the selected risk bundle also limits the maximum.
#### [](#coverage_duration)
Coverage duration
Here you enter the period for which your USDCs are protected.
* the minimum period is 14 days
* the maximum period is 120 days; the maximum may be lower depending on the selected risk bundle
#### [](#coverage_until)
Coverage until
The field is automatically filled according to the 'Coverage duration.' By clicking on the calendar icon, you can set a different desired date by double-clicking.
Once you have filled all fields, we will determine the risk bundles that match your specifications in a table. You can then select the risk bundle with the ideal parameters. The premium will be displayed.
#### [](#i_would_like_etherisc_to_submit_the_transaction_and_pay_the_fees_on_my_behalf)
I would like Etherisc to submit the transaction and pay the fees on my behalf.
Gas fees can sometimes be very high on the Ethereum mainnet. Therefore, we offer an option in which Etherisc submits the policy creation transaction and pays the gas fees.
**And this is how it works:**
We accept the gas fees and submit the transaction by clicking this checkbox. You will receive the signature request, i.e., the request whether we may take the amount for the policy from your wallet.

You will find the following data in the request:

**ProtectedBalance** in the unit defined by USDC. So if you subtract six decimal places, you have your protected amount of USDC.
**Duration** in seconds. Sum seconds/60(seconds)/60 (minutes)/24 (hours)=number of days.
**Bundle ID**. The risk bundle you have selected to cover your USDC.
**Signature ID**. This is a random string that we generate to make the transaction unique. We use the random string internally to ensure this application cannot be submitted multiple times.
When you confirm the signature request, we generate a signature from all these values to make your application unique and tamper-proof.
Your application will be forwarded to our backend and put into a transaction queue. The backend then submits these applications one after the other using an internal wallet. The gas fee is limited to 30 Gwei.
This means there is no guarantee that the transaction will go through immediately and it might take a while until gas costs return to values at or below 30 Gwei. In the 'Policies' section, you can see the current status.
You take over the gas fee if you do not activate this checkbox. Taking over the gas fees gives you control over how quickly your protection becomes active.
You can buy the policy by accepting our terms of service and then clicking ‘BUY.’
**This is how it continues when you take over the gas fees yourself:**
After you clicked ‘BUY,’ you need to confirm the payment of the premium.


Then you need to confirm your wallet.


Then Etherisc will confirm the protection for you.

### [](#policies)
Policies
In this section, you can see all your policies. You can select in the top left corner of the table to have all your policies displayed or only the active ones. You can also create new policies by clicking on 'APPLY FOR NEW POLICY' in the top right corner of the table.
### [](#price)
Price

The red line marks the 0.995 US dollar limit.
The green line marks the 0.999 US dollar limit.
The blue line shows the current USDC price. If the USDC price drops below 0.995 US dollar, the line will turn orange. If the USDC price does not recover above the 0.999 US dollar line within 24 hours, the depeg case occurs and the line turns red.
In the following chapter, you will find more information about the depeg case.
When you click the 'Price' Button, you can see the current rate of USDC against the US dollar.
If you click 'Reference pricefeed,' you will be redirected to our data source. We get our data from [Chainlink](https://data.chain.link/ethereum/mainnet/stablecoins/usdc-usd)
.
#### [](#data_supply_interval)
Data supply interval

There are two types of data deliveries from Chainlink for updating the USDC rate. We aggregate this data and display it up to a maximum of one year in the past.
* Heartbeat: a one-time regular daily data delivery
* Deviation threshold: a data delivery when the deviation threshold of 0.25% of the USDC rate against the US dollar rate is exceeded. Sixteen oracles (smart contracts) send this data to Chainlink currently. At least eleven oracles must confirm and may deviate from each other by a maximum of 0.0001 USDC. Only then Chainlink outputs the averaged USDC rate.
[](#how_a_depeg_incident_is_handled)
How a depeg incident is handled
--------------------------------------------------------------------
### [](#states_of_the_depeg_protection)
States of the depeg protection
You can see three cases in the upper left section in the' Price' area. Stable, 'triggered at' and 'depegged.'
### [](#the_stable_state)
The 'stable' state

The USDC price is considered to be 'stable' as long it does not fall below the trigger level of 0.995 US dollar.
### [](#the_triggered_state)
The 'triggered' state

A 'depeg event' is 'triggered' when the Chainlink USDC/USD price feed on the Ethereum Mainnet falls below 0.995 US dollar. In this case, the product smart contract is temporarily deactivated and policies can no longer be sold. This is to prevent that malicious actors could exploit the situation and buy cover in a situation where the risk is high.

### [](#the_depegged_state)
The 'depegged' state

If the Chainlink USDC/USD price fails to recover over or equal to 0.999 within 24h, the product enters into a 'depegged' state. As for the 'triggered' scenario, policies can no longer be sold.
The product is closed. As the policy owner, you can claim during a claim window of seven days. Once claimed, the policy is fulfilled with the depeg and thus also terminated.
### [](#the_payout_price)
The payout price
The depeg payout price is defined by the latest chainlink USDC/USD available at the 'depegged at' event. The time of the depeg event is defined by the 'triggered at' event plus 24 hours.
The depegged payout price is used for all calculations, regardless of when a policy holder made their claims. The maximum payout price is up to 20% of the value of your protected amount.
An Example: The depegged payout price is 0.9. So, if you purchased protection for 10,000 USDC for a particular Mainnet wallet, you would receive 1,000 USDT (1 - 0.9) \* 10,000) (assuming the USDC balance on your protected wallet is at least $10,000 USDC at the time of payout).
### [](#how_to_claim)
How to claim?
You can claim the amount due to you after the 'depegged' status is activated. To do this, connect to the web application via Metamask using your protected wallet. Then, click on your policy under 'Policies.' In your policy, you then click 'Claim.' Claiming from the protected wallet is your proof that you are the rightful owner of the protected wallet.
Once a depeg event happens, you have a time window of seven days to create your claim. Create your claim as soon as possible.
Using the [Moralis Balance Api](https://docs.moralis.io/web3-data-api/evm/balance-api)
, the actual USDC balance of your protected wallet at the 'depegged at' event is determined and the amount of USDT due to you is transferred to your wallet.
### [](#why_wait_for_24hrs)
Why wait for 24hrs?
The idea is that you should be flexible in deciding what to do. When the product enters the 'triggered' state, you can start thinking about how you see the situation. You have 24 hours to evaluate the market and the situation. After 24 hours, the product returns to the 'normal' state (when USDC goes back above 0.999) or goes into the 'depegged' state.
Another critical point in introducing the 24 hours is that we want to avoid triggering a depeg case too quickly.
### [](#how_long_can_i_wait_to_claim)
How long can I wait to claim?
In the case of a depeg event, the policy holder has a grace period of seven days to create her/his claim. If the policy holder creates a claim, the associated payout needs to be made before the bundle investor can pull out the remaining funds. Once the grace period is over, the bundle investor might close the policy and withdraw capital immediately, in which case no payout will happen.
[](#staking_usdt_in_risk_bundles)
Staking USDT in risk bundles
--------------------------------------------------------------
### [](#create_a_risk_bundle)
Create a risk bundle
When you create a risk bundle, you start staking USDT.
#### [](#connect_your_wallet)
Connect your wallet
Connect your wallet with our [Etherisc depeg protection web app](https://depeg.etherisc.com)
on the Ethereum mainnet and ensure your wallet holds a small amount of ETH to afford the transaction fees.
#### [](#model_your_risk_bundle)
Model your risk bundle
To create a new risk bundle, click the 'Stake' button. You can enter the values and conditions for your risk bundle in the form that now opens. Please note that the customer will later choose the most attractive risk bundle. It is a good idea to look at the already existing risk bundles, their conditions and 'utilization' given by the number of covered policies. Some variables already have a default value that you can change.

**Here are the input options:**
**Name**
Choose an eye-catching and descriptive name for your risk pool.
**Lifetime**
How long should your risk bundle protect the USDC from a depeg case?
* the minimum term is 14 days
* the maximum term is 180 days **Open until**
This field is automatically filled depending on the lifetime you entered.
**Staked amount**
How much USDT do you want to stake as a risk bundle for the period mentioned above?
* the minimum investment is 2,500 USDT
* the maximum investment is 10,000 USDT We will start with these amounts to gain experience. If our risk pool proves itself, we will adjust the amounts.
**Minimum / Maximum protected amount**
What is the minimum/maximum amount of USDC you want a policy to cover?
* The 'minimum protected amount' cannot be less than 2000 USDT
* The 'maximum protected amount' cannot exceed 100,000 USDT **Minimum coverage duration**
How many days of coverage for policies do you want to permit?
* The 'minimum coverage duration' can not be less than 14 days
* The 'maximum coverage duration' can not exceed 90 days **Annual percentage return**
Here you can set the percentage of annual interest that the DIP token investor will receive for his staked DIP token.
* The 'annual percentage return' can not be less than 0,01 %
* The 'annual percentage return' can not exceed 15 % From the perspective of policy holders, the annual percentage return you enter here will determine the net premium paid for a policy. On top of this net premium, the depeg product adds a 5% fee to partially compensate the product owner and instance operator for their work and expenses.
**Checkbox**
You must agree to our terms of service if you want to create a risk bundle.
If you entered all variables and agreed to our terms of service, you can now create the risk bundle by pressing the 'STAKE' button.
The web app asks you to allow Etherisc to take the amount you want to stake from your wallet.

Afterward, the web app asks for permission to create the risk bundle.

Now you will receive a confirmation of the risk bundle creation in the form of a summary of the parameters. Technically, the risk bundle is an NFT (ERC 721).

| | |
| --- | --- |
| | You or other DIP token holders can now stake their DIP in your risk bundle in the [Etherisc DIP staking web app](https://staking.etherisc.com/)
. Then, you can sell policies in the amount of the staked DIP token. You can find detailed information in the [Etherisc DIP staking tutorial](https://docs.etherisc.com/learn/dip-staking/)
. |
### [](#manage_your_risk_bundle)
Manage your risk bundle
You can also manage your risk bundles. Every change in a risk bundle is associated with minimal transaction costs.
**Here are the input options:**
**Stake**
You can add more USDT to your risk bundle.
**Unstake**
Unstake is possible if the balance exceeds the capital that is needed to cover the current policies. Otherwise, the button will not be displayed. You can unstake at most the amount 'Balance' - 'Locked capital.' If you unstake the maximum possible amount, you cannot sell any more policies from this risk bundle.
**Extend**
As a risk bundle owner, you can extend your bundle lifetime by clicking the 'EXTEND' button. The button will be activated 30 days before the bundle’s lifetime expires. So you can extend within the last 30 days of your risk bundle’s lifetime. Once the risk bundle has expired, you can no longer extend the lifetime.

Transaction fees are incurred when extending the lifetime of a risk bundle, but they are low because only the new end date is transferred.
We offer you the period between the minimum (14 days) and maximum (180 days) possible lifetime for an extension. You can choose freely. You can extend the lifetime of your risk bundle as often as you want.
**Lock**

You can lock your risk bundle. Gas fees are incurred when locking the risk bundle. After you have confirmed the lock via your wallet, the 'LOCK' button is deactivated and the 'UNLOCK' button is active. You can sell no more policies. The existing policies continue to run normally.
Please note: The 'State' Locked means the complete risk bundle is locked. The 'Locked capital' shows the amount for which policies already exist.
**Unlock**
The risk bundle is activated again. You can sell policies again.

**Close**
You have the possibility of closing the risk bundle before expiry. You can only close the risk bundle irrevocably when there are no more open policies in the risk bundle.

If you want to close a risk bundle before the 'Open until' date, you can lock it first and then close it after all policies covered by the risk bundle have been closed.
**Burn**
After closing the risk bundle, withdraw your USDT by clicking the first 'Unstake' button. After that, you enter the remaining amount and confirm with the second 'Unstake' button.

Now you can burn the risk bundle. The NFT is also burned in the process. The risk bundle is empty and no longer has an owner.

### [](#usdt_staking_rewards)
USDT staking rewards
USDT rewards come from depeg protection net premiums purchased against your risk bundle, minus claims. If no policies are sold, no rewards accumulate. When a depeg event occurs and claims are paid, the claims are deducted from your reward. Depending on the depeg price, the collected net premium may not cover the claims. In this case, the missing amount of USDT is taken from your invested risk capital,
USDT staking rewards = net premiums - claims
You can claim your rewards after the end of the risk bundle lifetime and when all policies associated with the risk bundle have been closed.
### [](#how_can_i_avoid_high_gas_fees)
How can I avoid high gas fees?
If your wallet offers maximum gas fees for the transaction, you can set the price to a maximum of 25GWei, confirm the transaction, and take a nap. During our 'friends and family' period, we made some transactions with an upper limit of 25 GWei. The most extended duration was one day.
[](#activating_capital_through_dip_staking)
Activating capital through DIP staking
----------------------------------------------------------------------------------
DIP staking is required to activate staked USDT, with 10 DIP tokens activating 1 USDT. For example, if you create a risk bundle for 100k USDT and stake 500k DIP, you can sell policies for up to 50k USDT on that risk bundle.
The more $DIP are staked, the more capital is activated, the more policies can be purchased and thereby fees generated. Staked DIP tokens are not collateral used to pay out claims. Therefore they are not at risk, even if claims are paid out from the investors' capital.
USDT and DIPs staking can be done from the same or different wallets.
[← Overview](/learn/)
[Depeg Protection FAQ →](/learn/depeg-faq)
---
# Preparing for mainnet - Etherisc Docs
Preparing for mainnet
=====================
After [running your project on a testnet](#connecting-to-public-test-networks.adoc)
for some time without issues, you will want to deploy it to the main Ethereum network (aka _mainnet_). However, the planning for going to mainnet should begin much earlier than your planned release date.
In this guide, we will go through Ethereum-specific considerations for taking your project to production, such as:
* [Auditing and Security](#auditing-and-security)
* [Verifying Source Code](#verify-source-code)
* [Managing Keys Securely](#key-management)
* [Handling Project Governance](#project-governance)
Remember that, while managing your contracts in a testnet and in mainnet is technically the same, there are important differences when on mainnet, since your project now manages real value for your users.
[](#auditing-and-security)
Auditing and security
------------------------------------------------
While security affects all of software development, security in smart contracts is particularly important. Anyone can send a transaction directly to your contracts with any payload, and all your contract code and state is publicly accessible. To make matters worse, in the event you are hacked, there is no recourse to reclaim the stolen funds - they are gone for good in a decentralized network.
With this in mind, security should be a primary concern at all stages of development. This means that **security is not something that you sprinkle on your project a week before you release**, but a guiding principle starting day one of your project.
Review [smart contract security best practices](https://consensys.github.io/smart-contract-best-practices/)
as you begin coding, join the [security discussions in our forum](https://forum.openzeppelin.com/c/security/25)
, and make sure to go through our [quality checklist](https://blog.openzeppelin.com/follow-this-quality-checklist-before-an-audit-8cc6a0e44845/)
to ensure your project is healthy.
Once you are done, it’s a good time to request an audit with one or more auditing firms. You can [request an audit](https://openzeppelin.com/security-audits/)
from the OpenZeppelin Research Team - we are an experienced team with a [long track record](https://blog.openzeppelin.com/security-audits/)
.
Remember that audits do not ensure the absence of bugs, but having several experienced security researchers go through your code certainly helps.
[](#verify-source-code)
Verifying your source code
--------------------------------------------------
Right after you deploy your contracts to mainnet, you should **verify their source code**. This process involves submitting the Solidity code to a third-party, such as [Etherscan](https://etherscan.io/)
or [Etherchain](https://www.etherchain.org/)
, who will compile it and _verify_ that it matches the deployed assembly. This allows any user to view your contract code in a block explorer, and know that it corresponds to the assembly actually running at that address.
You can verify your contracts manually on the [Etherscan](https://etherscan.io/verifyContract)
website.
You can also use [Hardhat Etherscan plugin](https://hardhat.org/plugins/nomiclabs-hardhat-etherscan.html)
.
To do this, install the plugin:
npm install --save-dev @nomiclabs/hardhat-etherscan
Update your hardhat configuration:
// hardhat.config.js
const { etherscanApiKey, projectId, mnemonic } = require('./secrets.json');
require("@nomiclabs/hardhat-etherscan");
...
module.exports = {
networks: {
mainnet: { ... }
},
etherscan: {
apiKey: etherscanApiKey
}
};
Finally run the `verify` task, passing the address of the contract, the network where it’s deployed, and the constructor arguments that were used to deploy it (if any):
npx hardhat verify --network mainnet DEPLOYED_CONTRACT_ADDRESS "Constructor argument 1"
| | |
| --- | --- |
| | You will need an [Etherscan API key](https://etherscan.io/apis)
to use their service. |
| | |
| --- | --- |
| | When you deploy an upgradeable contract the contract that the user interacts with will be just a proxy, and the actual logic will be in the implementation contract. Etherscan does have [support for correctly showing OpenZeppelin proxies and their implementations](https://medium.com/etherscan-blog/and-finally-proxy-contract-support-on-etherscan-693e3da0714b)
, but other explorers may not. |
[](#key-management)
Key management
----------------------------------
When working on mainnet you need to take special care to secure your private keys. The accounts you use to deploy and interact with your contracts will hold real Ether, which has real value and is a tempting target for hackers. Take every precaution to protect your keys, and consider using a [hardware wallet](https://docs.ethhub.io/using-ethereum/wallets/hardware/)
if necessary.
| | |
| --- | --- |
| | Unlike on a testnet, you cannot get mainnet Ether from a faucet. You will need to head to an exchange to trade in other coins or fiat to get real Ether for deploying your contracts. |
Additionally, you may define certain accounts to have special privileges in your system - and you should take extra care to secure them.
### [](#admin-accounts)
Admin accounts
An _admin_ (short for _administrator_) account is one that has special privileges in your system. For example, an admin may have the power to [pause](#contracts/api/utils.adoc#Pausable)
a contract. If such an account were to fall in the hands of a malicious user, they could wreak havoc in your system.
A good option for securing admin accounts is to use a special contract, such as a multisig, instead of a regular externally owned account. A _multisig_ is a contract that can execute any action, _as long as a predefined number of trusted members agree upon it_. [Gnosis Safe](https://safe.gnosis.io/multisig)
is a good multisig to use.
### [](#set-admin)
Upgrades admin
A special administrator account in an [OpenZeppelin Upgrades Plugins](#upgrades-plugins::index.adoc)
project is the account with the power to [_upgrade_](#upgrading-smart-contracts.adoc)
other contracts. This defaults to the externally owned account used to deploy the contracts: while this is good enough for a local or testnet deployment, in mainnet you need to better secure your contracts. An attacker who gets hold of your upgrade admin account can change any contract in your system!
With this in mind, it is a good idea to **change the ownership of the ProxyAdmin** after deployment - for example, to a multisig. To do this, you can use `admin.transferProxyAdminOwnership` to transfer ownership of our `ProxyAdmin` contract.
When you need to upgrade your contracts, we can use `prepareUpgrade` to validate and deploy a new implementation contract ready to be used when our proxy is updated.
[](#project-governance)
Project governance
------------------------------------------
It can be argued that admin accounts reflect that a project is not actually _decentralized_. After all, if an account can single-handedly change any contract in the system, we are not exactly creating a trustless environment.
Here is where _governance_ comes in. In many cases there will be some operations in your project that require special privileges, from fine-tuning system parameters, to running full contract upgrades. You will need to choose how those actions will be decided upon: whether it is by a [small group](https://safe.gnosis.io/multisig)
of trusted developers, or by [public](https://daostack.io/)
[voting](https://aragon.org/)
of all project stakeholders.
There is no right answer here. Which governance scheme you pick for your project will largely depend on what you are building and who your community is.
[](#next_steps)
Next steps
--------------------------
Congratulations! You have reached the end of the development journey, from writing your first contract to deploying to production. But work is far from over. Now you have to start collecting live user feedback, adding new features to your system (made possible via contract upgrades!), monitoring your application, and ultimately scaling your project.
On this site, you have at your disposal detailed guides and reference for all the projects in the OpenZeppelin platform, so you can pick whatever you need to build your Ethereum application. Happy coding!
---
# The Etherisc DIP staking web app - Etherisc Docs
The Etherisc DIP staking web app
================================
Welcome to the following tutorial on our Etherisc DIP staking web app. This web app works closely with the Etherisc depeg protection web app.
We recommend you read the Etherisc depeg protection tutorial. You will find all information about the Etherisc depeg protection web app. Important information about the topics, depeg, risk bundles, staking USDT in a risk bundle, USDC depeg protection and much more.
[](#etherisc_dip_staking)
Etherisc DIP staking
==============================================
Please start the [Etherisc DIP staking web app](https://staking.etherisc.com/)
. You may be able to view a few things if you still need to connect your wallet, but we recommend connecting your wallet as a first step.
You can stake your DIP token and get a bonus. The DIP token are not at risk. With staking DIP token, you unlock USDT token in the ratio of 1:10, which in the Etherisc depeg web app policies can be concluded to protect against a depeg at the stablecoin USDC. The URL [https://staking.etherisc.com/](https://staking.etherisc.com/)
takes you to the ‘DIP Staking’ area of the Etherisc DIP Staking web app. In the menu bar, you can choose from the following menu items.

[](#tab_etherisc)
Tab ‘ETHERISC’
--------------------------------
You will be redirected to our [homepage](https://etherisc.com/)
if you click on our logo.
[](#tab_dip_staking)
Tab ‘DIP Staking’
--------------------------------------
When you start the web app, you will land in the ‘DIP Staking’ area. All risk bundles are listed here.

In the upper left corner, you can refresh the list of risk bundles.
### [](#the_table_contents)
The table contents
#### [](#show_only_my_stakes)
Show only my stakes
Activate this option only to show the risk bundles displayed in which you have DIP token staked. This filter is inactive by default, so we show you all risk bundles.
#### [](#instance)
Instance
Here you can see the location of the GIF instance of the risk bundle. When hovering the mouse over an instance, the instance ID in the form of a hash is displayed.
#### [](#risk_bundle)
Risk bundle
Here you can see the name of the risk bundle. The risk bundle ID is displayed when hovering the mouse over the name.
#### [](#my_staked_amount)
My staked amount
Here you can see how many DIP token you have staked in the particular risk bundle with the currently connected wallet. You can see the total staked amount by hovering with the mouse over the individual amounts.
**Supported Capacity (Mine/Total)**
On the left, you can see the amount of USDT activated by your staked DIP token in USDT in the particular risk bundle. On the right, you will find the total amount of USDT activated overall stakes for this particular risk bundle.
#### [](#state)
State
There are four different states a risk bundle can have.
* Active: The risk bundle is active. You can stake DIP token.
* Locked: The owner of a risk bundle can lock it. The owner can unlock the locked risk bundle again. You can’t stake DIP token in a locked risk bundle.
* Closed: The owner of a risk bundle can close it. You can’t stake DIP token in a closed risk bundle but can unstake your staked DIP tokens. Once closed, there is no possibility of activating the risk bundle again. A risk bundle can only be closed when all policies collateralized by this bundle have been closed.
* Expired: The lifetime of the bundle has expired. You can no longer stake new DIP token but can still unstake them if you have staked them in this risk bundle.
* Burned: All remaining risk capital, rewards and claims in USDT token are paid out and no more policies are running.
#### [](#active_until)
Active until
The end of the lifetime is displayed here. Once the bundle expires, you can unstake all your DIP tokens independent of the bundle’s state.
#### [](#usage)
Usage
Here you can see the usage of the risk bundle. Dots in three different colors display the usage of the risk bundle in the overview.
* Green dot: The locked capital in the risk bundle is less than the total supported capital. You can stake DIP token and buy depeg policies in the Etherisc depeg protection web app.
* Orange dot: The locked capital in the risk bundle reached 90% or more of the total supported capital. You can stake DIP token and buy depeg policies in the Etherisc depeg protection web app.
* Red dot: The locked capital in the risk bundle reached 100% or more of the total supported capital.
When hovering the mouse over the dots, you will see the stake usage in percent, the locked capital in USDT and the total supported capital in USDT.
You can sort the table by any information. Just click on the information. Default is sorted by 'Active until.’ You can recognize this by the small arrow to the right of the text.
#### [](#details)
DETAILS
On the table’s far right, you can click ‘DETAILS.’
[](#manage_your_staked_dip)
Manage your staked DIP
--------------------------------------------------
In the detail view, you can stake DIP token or manage your staked DIP token.

Here you will find detailed information about the risk bundle. The general information and personal information like ‘My Supported Capital.’
The buttons where you can act are highlighted in blue.
#### [](#stake)
STAKE
You can start staking or stake more DIP token in this risk bundle.
#### [](#unstake)
UNSTAKE
The ‘UNSTAKE’ button in the screenshot is not active. You cannot unstake your DIP token in the example screen because the risk bundle is in the state ‘Active.’ Unstaking is only available for expired risk bundles or in state ‘Closed’ or ‘Burned.’
Please note: Your DIP token are not at risk.
#### [](#claim_rewards)
CLAIM REWARDS
When you click the ‘CLAIM REWARDS’ button, your rewards will be sent to your wallet after you have approved the transaction in your wallet.
The ‘Accumulated Rewards’ are the currently accumulated, unclaimed rewards. They are not the rewards accumulated over the entire period. So, if you have already claimed a part of your rewards, the rewards already paid out are not included in the ‘Accumulated Rewards.’
You can claim your rewards at any time during the lifetime of a risk bundle, but at the latest when you unstake the total amount of your staked DIP tokens for this bundle.
#### [](#restake)
RESTAKE
Restaking is only possible in risk bundles that are already closed or expired. You can only restake the total amount of the DIP token you staked and earned in a new risk bundle. The staked DIP and the earned DIP will be treated as a newly staked DIP in the new risk bundle. You can only restake in a risk bundle in which you have not yet staked any DIP token.
Here is an example: you have staked 500,000 DIP and you have earned 5,000 DIP and you restake. The result will be that your stakes will show 505,000 staked DIP and 0 earned DIP in the new risk bundle initially.
[](#tab_stakes)
Tab ‘Stakes’
----------------------------
This area is identical to the ‘DIP Staking’ menu item. You can see all existing risk bundles.
[](#tab_stake_dip)
Tab ‘Stake DIP’
----------------------------------

In this area, you will only see the risk bundles in which you can stake DIP token. By clicking ‘SELECT’ on the right, compare the conditions and terms and choose a risk bundle. You see all details of the risk bundle. The minimum volume is 5,000 DIP.
#### [](#gasless_staking)
Gasless staking
By checking the box, ‘I would like Etherisc to submit the transaction and pay fees on my behalf,’ you can set Etherisc to pay the fees.
| | |
| --- | --- |
| | Etherisc limits the gas fee. The maximum fee is adjusted to the current market conditions. You can see the current limit by hovering over the info button. The text that appears contains the current limit. Etherisc does not guarantee that the transaction will be executed immediately. |
You will see this hint if the transaction still needs to be performed.

We cover the fees for the initial stake in a risk bundle that the current wallet has not yet staked in.
#### [](#gasless_restaking)
Gasless Restaking
Similar to gasless staking, you also have the choice of taking over the fees or Etherisc when you restake your DIP token.
Here, you can see how it continues when you pay the fees yourself.




#### [](#here_are_the_technical_details_of_the_gasless_dip_staking_and_restaking)
Here are the technical details of the gasless DIP staking and restaking
With gasless DIP staking or restaking, you do not sign a transaction hash, unlike standard transactions. With the signature request, you only confirm that you want to stake or restake the DIP token gasless. You have to create an allowance for a gasless staking transaction as you would for regular staking transactions. This will incur a small fee on your side.
The signature allows us to verify that the data on the blockchain is identical to the data you entered in the form when you initiated the transaction. Then, you get the signature request. This approval has to be made by you, the staker. Otherwise, everyone could move assets back and forth in the wallets of others. In the signature in Metamask, you will find the data you entered in the staking form in our web app. The signature is free of fee for you.

In the screenshot, you can see the popup of Metamask and the DIP staking web app.
In the red frame, as well as in the web app, you can find the following information:
* the NFT ID (framed green)
* the DIP amount you have staked (framed orange)
* the signature ID (framed pink)
The DIP amount is displayed in Wei, hence the 18 zeros after the entered amount.
The signature ID in Metamask is a random value used to identify the request uniquely.
Using the NFT ID, the DIP amount and the signature ID, metamask calculates a signature using your wallet’s private key and then sends all the data of the signature to our backend. The backend uses this data to create a staking request from our wallet (so that we pay for it) and writes the transaction to the blockchain.
Above the red frame, one more bluish-framed element is left in the screenshot: the "verify third-party details" link. It will show you the address of the "verifying contract." This smart contract verifies the signature. The address is included when calculating the signature to ensure no other contract can verify this.
If you open Etherscan or click the link in Metamask and go to the address of this smart contract, you should see the smart contract called ‘StakingMessageHelper.’ If you want to be sure it’s the correct one, then take Etherscan and open our staking registry ([https://etherscan.io/address/0x88Ce11f387d140bF639a16f55Bc38e7323Ab1D9c#readProxyContract](https://etherscan.io/address/0x88Ce11f387d140bF639a16f55Bc38e7323Ab1D9c#readProxyContract)
) and execute the getMessageHelperAddress function and this should return the same address as is shown in the signing request. If it’s different, don’t click ‘Sign.’
| | |
| --- | --- |
| | Our staking registry on mainnet is 0x88Ce11f387d140bF639a16f55Bc38e7323Ab1D9c ([https://etherscan.io/address/0x88Ce11f387d140bF639a16f55Bc38e7323Ab1D9c](https://etherscan.io/address/0x88Ce11f387d140bF639a16f55Bc38e7323Ab1D9c)
).
The staking message helper for the signature is 0xFFdC7c357363BcF0C4a142DFB61359322028523F ([https://etherscan.io/address/0xFFdC7c357363BcF0C4a142DFB61359322028523F](https://etherscan.io/address/0xFFdC7c357363BcF0C4a142DFB61359322028523F)
).
Stop immediately if you ever encounter different addresses during your staking process! |
[](#tab_unstake_dip)
Tab ‘Unstake DIP’
--------------------------------------
In this area, you can unstake your DIP token. Unstaking is only available on expired risk bundles or in states ‘Closed’ or ‘Burned.’
---
# Documentation - Etherisc Docs
Documentation
=============
Explore our guides and examples to build decentralized insurance products using Etherisc and the **G**eneric **I**nsurance **F**ramework _(GIF)_.
[](#explore_using_etherisc)
Explore using Etherisc
--------------------------------------------------
Etherisc provides a complete suite of solutions to build, manage, and inspect decentralized insurance products.
[GIF The Generic Insurance Framework: A library of modular, reusable, and secure smart contracts, written in Solidity.](gif/)
[Contracts The GIF contracts](gif/core-contracts)
[Documentation API-Documentation of the GIF contracts.](contracts/2.x/)
[](#learn)
Learn
----------------
Comprehensive guides for every step of your journey in the Etherisc ecosystem!
[Tutorials Overview An overview of the growing number of available tutorials.](learn/)
[Depeg Protection Tutorial Tutorial on how to purchase depeg protection and stake Tether in risk pools.](learn/depeg-purchase)
[Basics of the GIF Framework Understanding the basic concepts of the GIF Framework.](learn/basics-gif)
[](#whitepaper)
Whitepaper
--------------------------
Our principles, our ethics, our strategies, our ideas and visions.
[Whitepaper tl:dr A summary of the Whitepaper](learn/whitepaper-en-tldr)
[Whitepaper English Our Whitepaper. Our strategy.](learn/whitepaper-en)
[Whitepaper Français Notre Whitepaper. Notre stratégie.](learn/whitepaper-fr)
[](#more_from_etherisc)
More from Etherisc
------------------------------------------
### [](#careers)
Careers
Etherisc is growing. If you enjoy using our products or reading our audit reports, and have a genuine interest in protecting the open economy, please check out our jobs channel on our [Discord](https://discord.gg/cVsgakVG4R)
!
[](#questions)
Questions?
-------------------------
Join the Etherisc community in our [Telegram channel](https://t.me/etherisc_community)
and our [Discord](https://discord.gg/cVsgakVG4R)
, as well as share your feedback or showcase what you have built with Etherisc and the GIF!
---
# Etherisc Docs
[](#docs_etherisc_com)
docs.etherisc.com
----------------------------------------
How we organize the Etherisc documentation.
### [](#basic_idea)
Basic idea:
* Generally, we follow the documentation guidelines of [OpenZeppelin](https://openzeppelin.com)
. This means:
* In the repo `[github.com/etherisc/docs.etherisc.com](https://github.com/etherisc/docs.etherisc.com) ` we put all the general docs which are not specific for a certain code repository.
* General information
* Tutorials
* Architecture…
* In each code repo (e.g. `[github.com/etherisc/gif-contracts](https://github.com/etherisc/gif-contracts) ` etc) we create a folder `/docs`.
* The basic, manually created documentation which is specific for this code repo is put under `/docs/modules/ROOT/pages`
* All solidity code is documented with [NatSpec](https://docs.soliditylang.org/en/latest/natspec-format.html)
and documentation is generated with [solidity-docgen](https://github.com/OpenZeppelin/solidity-docgen)
and (automagically) put in `/docs/modules/api/…`
* On each commit, the docs are automatically preprocessed and published.
### [](#documentation_structure)
Documentation Structure
[](_images/structure.jpg)
### [](#using_solidity_docgen)
Using `solidity-docgen`
`solidity-docgen` automagically generates perfectly formatted AsciiDoc files for each smart contract, with each contract, function etc. nicely formatted. However, some prerequisites need to be made.
`solidity-docgen` works with [`hardhat`](https://hardhat.org/)
so both `solidity-docgen` and `hardhat` needs to be installed. Openzeppelin provides some necessary scripts and templates which enable AsciiDoc-formatted output, and which need to be copied in the `docs` folder of the repo. To make it work, we need a `README.adoc` file in every source directory under `/contracts`. All output generated by `solidity-docgen` needs to be included in these `README.adoc` files via `{{…}}` directive. Typically, the `README.adoc` will start with some general documentation of the smart contracts, formatted in AsciiDoc. Then you can include the generated AsciiDoc for each `Xyz.sol` contract simply via the `{{Xyz}}` directive.
#### [](#example_readme_adoc)
Example `README.adoc`
Lets assume we have a `contracts` folder with the following structure:
/contracts
├── Migrations.sol
├── main.sol
├── module1
│ ├── Part1.sol
│ ├── Part2.sol
│ └── Part3.sol
└── module2
├── Part4.sol
└── Part5.adoc
We add `README.adoc` in each folder:
/contracts
├── Migrations.sol
├── main.sol
├── module1
│ ├── Part1.sol
│ ├── Part2.sol
│ ├── Part3.sol
│ └── README.adoc
└── module2
├── Part3.sol
├── Part4.sol
└── README.adoc
The file `/contracts/module1/README.adoc` would then look like this:
= Documentation of `module1`
== General considerations
...
== Contracts
{{Part1}}
{{Part2}}
{{Part3}}
| | |
| --- | --- |
| | Put an empty line between each two contracts. |
#### [](#generation_of_asciidoc_files)
Generation of asciidoc files
In each source repo (e.g. `gif-contracts`, `gif-interface` etc.), `AsciiDoc` files are generated by
$ npx hardhat docgen
In addition, a table of contents is generated by
$ node scripts/gen-nav.js "$OUTDIR" > "$OUTDIR/../nav.adoc"
Both actions can be combined by calling
$ npm run prepare-docs
The scripts are executed automatically by github actions on push to a release branch.
#### [](#git_branches)
Git Branches
Documentation is maintained together with the source code in the main development branch.
Release branches adhere to the following regex:
`releaseBranchRegex = /^release-v(?(?\d+)\.(?\d+)(?:\.(?\d+))?)$/`
**Examples:**
release-v3
release-v3.0
release-v3.0.1
For each `major` release, a separate `docs-v{major}.x` branch is automatically generated by the `[update-docs-branch.js](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/scripts/update-docs-branch.js) ` script. The script is invoked by a github action each time a release branch is pushed and checks for conflicting branches and other conditions.
The `docs-v{major}.x` branch should never be manually edited.
### [](#cross_linking_between_docs)
Cross-linking between docs
Antora offers the capability to cross-link between doc sources with the `xref` macro. For details, see [here](https://docs.antora.org/antora/latest/page/xref/)
### [](#tech_stack)
Tech stack
* We use [AsciiDoc](https://asciidoc.org/)
* Here’s a nice [cheatsheet](https://drive.google.com/file/d/1Y7VaiafvidX5CaX90gJz7t6HZqE-dJWq/view?usp=share_link)
with most of the basic commands
* We use [Antora](https://antora.org/)
to publish the docs to [docs.etherisc.com](https://docs.etherisc.com)
* [docs.etherisc.com](https://docs.etherisc.com)
is hosted at [netlify](https://netlify.com)
* Netlify is integrated in our CI/CD workflow. Each code repo has a [webhook](https://docs.netlify.com/configure-builds/build-hooks/)
which is triggered on push and which will notify Netlify to re-generate the doc site.
* We use the Openzeppelin docs template.
---
# tl;dr - Etherisc Docs
tl;dr
=====
[](#whitepaper_2_0_tldr)
Whitepaper 2.0 tl:dr
================================================
[](#the_current_insurance_industry_isnt_working)
The current insurance industry isn’t working
---------------------------------------------------------------------------------------------
Giant corporations dominate a multi-trillion-dollar insurance industry. Insurance remains an indispensable part of the modern economy and is a critical society’s safety net.
However, the industry is not working for:
* **customers:**
* **the insured:** when they need help the most, they can struggle to get reimbursed by corporations whose profits rely on investing customer premiums and not paying out claims.
* **the underinsured:** millions of people are missing out on life-changing insurance benefits because policies are too expensive, intransparent and inefficient.
* **insurance providers:**
* **wrestle with trading off shareholder (generate profits) and customer interests (pay out claims)**, making them marginally unattractive to both have high operational costs as they need to collect, analyze and store enormous.
* **customer/industry data sets in huge private silos** in proprietary ways new entrants face a high entry-barrier due to complex regulations, reducing the ability for disruptive innovation.
* **investors:**
* customer premiums (risk pools) are very attractive investment instruments, however, they remain inaccessible to most investors or customers themselves.
[](#blockchain_will_revolutionize_the_insurance_industry)
Blockchain will revolutionize the insurance industry
--------------------------------------------------------------------------------------------------------------
* **Blockchain smart contracts:**
* completely cut out many processes, radically reducing coordination (and therefore policy) costs.
* use pre-defined claims payout criteria and publicly available data (parametric insurance) to eliminate conflict of interest, human error and increase transparency/trust.
* can fully automate claims/payout handling resulting in near-real-time payouts.
* **Blockchain tokenization:**
* democratizes investment access to other customer premiums (risk pools)
* enables access to new investment vehicles and markets (including crypto), which are usually inaccessible to non-professional investors.
* allows customers to benefit from investment returns for their insurance premium.
[](#etherisc_is_the_future_of_insurance)
Etherisc is the future of insurance
----------------------------------------------------------------------------
**Etherisc’s open-source blockchain platform is a growing ecosystem, benefiting for.**
* **customers:** who can easily access innovative, cheaper, faster, more transparent insurance.
* **insurance providers:** startups, large/small companies or non-profit groups can quickly and easily offer high-quality, innovative parametric peer-to-peer insurance products.
* **investors:** can benefit from a broad range of risk-based investment bundles (trustless risk pools), tailored to their risk/investment appetite.
[](#gif_generic_insurance_framework)
GIF (Generic Insurance Framework)
----------------------------------------------------------------------
**The Generic Insurance Framework (GIF) is the core of Etherisc’s multi-chain, multi-tenant decentralized insurance platform:**
* **open-source smart contracts** that implement generic insurance product and policy lifecycle functions across the complete value chain.
* **oracles** provide necessary data (e.g. flight or weather)
* **product-tailored end-to-end execution environments** (GIF instances) covering products, oraclesa nd risk pools.
**Etherisc offers insurance providers:**
* ready-to-use modules to quickly & easily design fully-compliant and licensed insurance products.
* a transparent, real-time, structured overview of all building blocks, events and transactions available in a GIF instance (GIF monitor).
* high-quality code audited by two independent reputable businesses
* a new legal model which removes most insurance company’s legal and financial requirements by exchanging a claim for a technical guarantee (certain countries only).
**Etherisc’s governance ensures that the protocol continues to improve and can be used freely.**
* Etherisc’s Swiss-based foundation (DIF) formally holds the IP rights of the protocol.
* DIP is Etherisc’s token, which participants need to join the ecosystem: Hardcap of 1 Billion (10^9)DIP, of which 30% (300M DIP) were distributed during 2016’s token generating event, the remainder is held in the DIF treasury.
* Use of the ecosystem is governed by the Etherisc Governance Model (EGM), bound by a set of rules and principles.
* GIF instances are certified by the DIF, registered in the token curated registry and set up as DAOs.
* Participants are required to stake their DIP tokens to be able to enact their EGM voting rights.
[](#etheriscs_economic_principles)
Etherisc’s economic principles
-----------------------------------------------------------------
* development and maintenance of the platform, EGM and GIF instances are intended to be self-sustaining and not profit-oriented.
* whilst providing high-quality, competitive products for customers, each GIF instance is intended to generate profits for participants.
* participants need to stake their DIP tokens to be able to invest capital (staking stable coins) in primary risk pools.
* contain customer premiums and investment capital to cover tail risks
* claims are 100% collateralized (i.e. sufficient capital to pay out all claims)
* invested capital is at risk and can generate attractive returns depending on claims frequency/severity (e.g. no claims = high profit, high claims = no profit).
* staking assets in the risk pool mints an NFT, which is automatically purchased by a secondary risk pool, which fractionalizes it into ERC20 risk pool tokens (RPT).
* specific RPT are minted for each risk pool and tradable on the open market.
* any profits are paid out to token holders at the end of an ‘epoch’ through the increased value of their RPTs.
* insurance providers also benefit from risk pool investments through staking. They must also pay a regular fee to cover the EGM’s operational cost and stake in governance pools for voting rights.
[](#so_what_are_you_waiting_for)
So what are you waiting for?
-------------------------------------------------------------
A fair and truly decentralized ecosystem that protects the unprotected and welcomes everyone to be a part of it. Want to be part of an ecosystem of cheaper, faster and more transparent insurance? Join the revolution today and say hello to insurance 2.0!
---
# Etherisc - Terms of Service - Etherisc Docs
Etherisc - Terms of Service
===========================
Last modified: March, 2023
These Terms of Service (the “Agreement”) explain the terms and conditions under which you may access and use the Products provided by Etherisc GmbH (referred to herein as “Etherisc GmbH”, “we”, “our”, or “us”). The Products shall include, but shall not necessarily be limited to, [https://etherisc.com](https://etherisc.com)
and all of its subdomains.
You must read this Agreement carefully as it governs your use of the Products. By accessing or using the Products, you confirm that you have read, understand, and agree to be unequivocally bound by this Agreement in its entirety. If you do not agree, you are not authorized to access or use the Products and must not use the Products.
**NOTICE**: This Agreement contains important information, including a binding arbitration provision and a class action waiver, both of which affect the way disputes are resolved in relation to your use of the Products.
[](#introduction)
Introduction
------------------------------
The Products provides access to a decentralized software protocol, which may be deployed on various public blockchains (including but not limited to Ethereum, Polygon, Gnosis Chain, Binance Smart Chain, Celo and Avalanche) and which allows users to enter into transactions with each other on a peer-to-peer basis to exchange various digital assets based on certain conditions (“the Decentralized Insurance Protocol” or the “Protocol”).
To access the Products, you must use **non-custodial wallet** software (for simplicity hereinafter referred to as wallet of wallets), which enables you to interact with public blockchains. Your relationship with that non-custodial wallet provider is governed by the applicable terms of service of that third party and does not form part of this Agreement. Wallets are not operated by, maintained by, or affiliated with us, and we do not have custody or control over the contents of your wallet and have no ability to retrieve or transfer its contents. By connecting your wallet to our Products, you agree to be bound by this Agreement and all of the terms incorporated herein by reference.
[](#modification_of_this_agreement)
Modification of this Agreement
------------------------------------------------------------------
We reserve the right, in our sole discretion, to modify this Agreement from time to time. If we make any material modifications, we may notify you by updating the date at the top of the Agreement and by maintaining a current version of the Agreement at [https://etherisc.com/terms-of-service](https://etherisc.com/terms-of-service)
, however, it remains your responsibility to check for the latest version of the Terms of Service prior to accessing and using the Products. All modifications will be effective when they are posted, and your continued access or use of the Products will serve as confirmation of your acceptance of all such modifications. If you do not agree with any modifications to this Agreement, you must stop accessing and using the Products immediately.
[](#description_of_services_provided_through_the_products)
Description of Services provided through the Products
----------------------------------------------------------------------------------------------------------------
The Products provide web or mobile-based means of accessing the Protocol.
The Products are distinct from the Protocol and are one, but not the exclusive, means of accessing the Protocol. The Protocol comprises open-source, self-executing smart contracts that are deployed on various public blockchains.
The smart contracts are purely technical functions which determine the transfer of various cryptographic assets subject to certain technical functions, processes and conditions. If you as a user connect a wallet to such a smart contract, you subject your assets irrevocably to the outcome of the technical function of the relevant smart contract. The smart contract as such executes autonomously as programmed and does not provide you with any legal claim vis-a-vis any other party.
Any transactions that users engage in by means of the Protocol are purely bilateral between such users on a peer-to-peer basis. Etherisc will never become a party to any such transactions.
Transactions may be subject to separate terms imposed by their creators with respect to the conditions and benefits associated with a particular transaction. We are not a party to any such intrinsic terms, which are valid only between the parties involved in a transaction. The parties involved in a transaction are solely responsible for communicating, promulgating, agreeing to, and enforcing those terms, and you are solely responsible for reviewing such terms.
Etherisc does not control or operate any version of the Protocol on any blockchain network. By using the Products, you understand that you are not transacting or exchanging digital assets with us. We do not operate any smart contracts nor do we engage in any transactions on the Protocol nor do we control their execution on the Protocol.
When users pay fees for transactions, those fees accrue to other users as their transaction counterparty who are third parties independent from Etherisc.
The Protocol was initially deployed on the Ethereum blockchain, and has since been deployed on several other blockchain networks. Future Instances may be deployed by parties other than Etherisc. Deployments on other networks may make use of cross-chain bridges, which allow assets native to one blockchain to be transferred to another blockchain. Please note that digital assets that have been “bridged” or “wrapped” to operate on other blockchain networks (including to blockchains compatible with the Ethereum Virtual Machine that are designed to ensure the Ethereum blockchain can effectively process more transactions or other blockchains that are frequently referred to as “Layer 2” solutions) are distinct from the original Ethereum mainnet asset.
The Products features a marketplace function, which is a series of smart contracts that allow users to search, filter, discover and choose transactions according to a number of criteria.
[](#eligibility)
Eligibility
----------------------------
To access or use the Products, you must be able to form a legally binding contract with us. Accordingly, you represent that you are at least the age of majority in your jurisdiction (e.g., 18 years old in Germany) and have the full capacity to enter into and comply with the terms and conditions of this Agreement on behalf of yourself and any company or legal entity for which you may access or use the Products.
You further represent that you are not (a) the subject of economic or trade sanctions administered or enforced by any governmental authority or otherwise designated on any list of prohibited or restricted parties or (b) a citizen, resident, or a legal entity organized in a jurisdiction or territory that is the subject of comprehensive country-wide, territory-wide, or regional economic sanctions by the United States, the UN or any EU member state or (c) a citizen, resident, green card holder or a legal entity organized in the US nor are you in any other way legally considered a US Person. Finally, you represent that your access and use of the Products will fully comply with all applicable laws and regulations including your jurisdiction of residence and the jurisdiction you are accessing the Products form, and that you will not access or use the Products to conduct, promote, or otherwise facilitate any illegal activity.
[](#intellectual_property_rights)
Intellectual Property Rights
--------------------------------------------------------------
We own all intellectual property and other rights in the Products and its contents, including (but not limited to) software, text, images, trademarks, service marks, copyrights, patents, designs, and its “look and feel.”. Unlike the Products, the Protocol consists entirely of open-source software running on public blockchains.
By using the Products to list, post, promote, offer or display transactions, you grant us a worldwide, non-exclusive, sublicensable, royalty-free license to use, copy, modify, and display any content, including but not limited to text, materials, images, files, communications, comments, feedback, suggestions, ideas, concepts, questions, data, or otherwise, that you post on or through the Products for our current and future business purposes, including to provide, promote, and improve the services.
You represent and warrant that you have, or have obtained, all rights, licenses, consents, permissions, powers and/or authorities necessary to offer any transaction that you list, post, promote, or display on or through the Products. You represent and warrant that such content does not contain material subject to copyright, trademark, publicity rights, or other intellectual property rights, unless you have necessary permission or are otherwise legally entitled to post the material and to grant us the license described above, and that the content does not violate any laws.
[](#additional_rights)
Additional Rights
----------------------------------------
We reserve the following rights, which do not constitute obligations of ours:
(a) with or without notice to you, to modify, substitute, eliminate or add to the Products;
(b) to review, modify, filter, disable, delete and remove any and all content and information from the Products; and
(c) to cooperate with any law enforcement, court or government investigation or order or third party requesting or directing that we disclose information or content or information that you provide.
[](#prohibited_activity)
Prohibited Activity
--------------------------------------------
You agree not to engage in, or attempt to engage in, any of the following categories of prohibited activity in relation to your access and use of the Products:
1. Intellectual Property Infringement. Activity that infringes on or violates any copyright, trademark, service mark, patent, right of publicity, right of privac, or other proprietary or intellectual property rights under the law.
2. Cyberattack. Activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including (but not limited to) the deployment of viruses and denial of service attacks.
3. Fraud and Misrepresentation. Activity that seeks to defraud us or any other person or entity, including (but not limited to) providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of another.
4. Market Manipulation. Activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including (but not limited to) the manipulative tactics commonly known as “rug pulls”, pumping and dumping, and wash trading.
5. Securities and Derivatives Violations. Activity that violates any applicable law, rule, or regulation concerning the trading of securities or derivatives, including (but not limited to) the unregistered offering of securities and the offering of leveraged and margined commodity products to retail customers in the United States.
6. Sale of Stolen Property. Buying, selling, or transferring of stolen items, fraudulently obtained items, items taken without authorization, and/or any other illegally obtained items.
7. Data Mining or Scraping. Activity that involves data mining, robots, scraping, or similar data gathering or extraction methods of content or information from the Products.
8. Objectionable Content. Activity that involves soliciting information from anyone under the age of 18 or that is otherwise harmful, threatening, abusive, harassing, tortious, excessively violent, defamatory, vulgar, obscene, pornographic, libelous, invasive of another’s privacy, hateful, discriminatory, or otherwise objectionable.
9. Any Other Unlawful Conduct. Activity that violates any applicable law, rule, or regulation of Germany, your country of residence, the country where you are accessing the Products from or another relevant jurisdiction, including (but not limited to) the restrictions and regulatory requirements imposed by German law.
[](#not_registered_with_bafin_or_any_other_agency)
Not Registered with BaFin or Any Other Agency
------------------------------------------------------------------------------------------------
We are not registered nor licensed with the German Financial Regulator BaFin in any capacity. You understand and acknowledge that we do not broker transactions on your behalf nor do we collect or earn fees from your transactions on the Products. We also do not facilitate the execution or settlement of your transactions, which occur entirely on public distributed blockchains like Ethereum and pursuant to the technical functions of smart contracts. As a result, we do not (and cannot) guarantee any pricing, conditions or proper execution through the Products.
[](#non_solicitation_and_no_investment_advice)
Non-Solicitation and No Investment Advice
----------------------------------------------------------------------------------------
You agree and understand that:
(a) all transactions you submit or engage in through the Products are considered unsolicited, which means that they are solely initiated by yourself;
(b) you have not received any investment or other advice from us in connection with any transactions; and
(c) we do not conduct a suitability review of any transactions you submit.
We may provide information about third party transactions posted on the Protocol or on the Products. Such provision of informational materials does not amount to advertising or solicitation of such transactions and is for informational purposes only. We are not attempting to induce you to become part of any transaction as a result of information provided. All such information provided by the Products is for informational purposes only and should not be construed as investment advice or a recommendation that a particular transaction is safe or sound. You should not take, or refrain from taking, any action based on any information contained in the Products. By providing information for your convenience, we do not make any recommendations to you or opine on the merits of any transaction or opportunity. You alone are responsible for determining whether any transaction is appropriate for you based on your personal objectives, financial circumstances, and risk tolerance.
[](#non_custodial_and_no_fiduciary_duties)
Non-Custodial and No Fiduciary Duties
--------------------------------------------------------------------------------
The Products is a purely non-custodial application, meaning we do not ever have custody, possession, or control of your digital assets at any time. It further means you are solely responsible for the custody of the cryptographic private keys to the digital asset wallets you hold and you should never share your wallet credentials or seed phrase with anyone. We accept no responsibility for, or liability to you, in connection with your use of a wallet and make no representations or warranties regarding how the Products will operate with any specific wallet. Likewise, you are solely responsible for any associated wallet and we are not liable for any acts or omissions by you in connection with or as a result of your wallet being compromised.
This Agreement is not intended to, and does not, create or impose any fiduciary duties on us. To the fullest extent permitted by law, you acknowledge and agree that we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, those duties and liabilities are hereby irrevocably disclaimed, waived, and eliminated, while we shall be indemnified by you and held harmless against any liabilities or claims that my be raised in relation to your use of the Products. You further agree that the only duties and obligations that we owe you are those set out expressly in this Agreement.
[](#compliance_and_tax_obligations)
Compliance and Tax Obligations
------------------------------------------------------------------
The Products may not be available or appropriate for use in your jurisdiction. By accessing or using the Products, you agree that you are solely and entirely responsible for compliance with all laws and regulations that may apply to you or to a transaction you engage in.
We are unable to verify the identity and location or jurisdiction, laws and regulation applicable to the users transacting on the Protocol. It is therefore entirely up to you to determine the legal nature of any transactions you engage in under the applicable law, verify any special legal and regulatory requirements under applicable law and to obtain any regulatory licenses that may be required to lawfully engage in the transaction.
Specifically, your use of the Products or the Protocol may result in various tax consequences, such as income or capital gains tax, value-added tax, goods and services tax, or sales tax in certain jurisdictions.
It is your responsibility to determine whether taxes apply to any transactions you initiate or receive and, if so, to report and/or remit the correct tax to the appropriate tax authority.
[](#assumption_of_risk)
Assumption of Risk
------------------------------------------
By accessing and using the Products, you represent that you are legally, financially and technically sophisticated enough to understand the transaction you are engaging in as well as the inherent risks associated with using cryptographic and blockchain-based systems, and that you have a working knowledge of the usage and intricacies of digital assets such as ether (ETH), the DIP Token, so-called stablecoins, and other digital tokens such as without limitation those following the Ethereum Token Standard (ERC-20).
In particular, you understand that the markets for these digital assets are nascent and highly volatile due to risk factors including (but not limited to) adoption, speculation, technology, security, and regulation. You understand that anyone can create a token, including fake versions of existing tokens and tokens that falsely claim to represent projects, and acknowledge and accept the risk that you may mistakenly trade those or other tokens. So-called stablecoins may not be as stable as they purport to be, may not be fully or adequately collateralized, and may be subject to panics and runs.
Further, you understand that smart contract transactions automatically execute and settle, and that blockchain-based transactions are irreversible when confirmed. You acknowledge and accept that the cost and speed of transacting with cryptographic and blockchain-based systems such as Ethereum are variable and may increase dramatically at any time.
You represent and warrant that you have done sufficient research before making any decisions to transact, obtain, transfer, or otherwise interact with any smart contracts.
If you stake assets on the Protocol through the Products, you understand that your digital assets may lose some or all of their value while they are locked in the Protocol due to the fluctuation of prices of tokens.
Finally, you understand that we do not create, own, or operate cross-chain bridges and we do not make any representation or warranty about the safety or soundness of any cross-chain bridge.
In summary, you acknowledge that we are not responsible for any of these variables or risks, do not own or control the Protocol, and cannot be held liable for any resulting losses that you experience while accessing or using the Products. Accordingly, you understand and agree to assume full responsibility for all of the risks of accessing and using the Products to interact with the Protocol.
[](#third_party_resources_and_promotions)
Third-Party Resources and Promotions
------------------------------------------------------------------------------
The Products may contain references or links to third-party resources, including (but not limited to) information, materials, products, transactions or services, that we do not own or control. In addition, third parties may offer promotions related to your access and use of the Products. We do not approve, monitor, endorse, warrant or assume any responsibility for any such resources or promotions. If you access any such resources or participate in any such promotions, you do so at your own risk, and you understand that this Agreement does not apply to your dealings or relationships with any third parties. You expressly relieve us of any and all liability arising from your use of any such resources or participation in any such promotions.
[](#release_of_claims)
Release of Claims
----------------------------------------
You expressly agree that you assume all risks in connection with your access and use of the Products. You further expressly waive and release us from any and all liability, claims, causes of action, or damages arising from or in any way relating to your use of the Products.
[](#indemnity)
Indemnity
------------------------
You agree to hold harmless, release, defend, and indemnify us and our officers, directors, employees, contractors, agents, affiliates, and subsidiaries from and against all claims, damages, obligations, losses, liabilities, costs, and expenses arising from: (a) your access and use of the Products; (b) your violation of any term or condition of this Agreement, the right of any third party, or any other applicable law, rule, or regulation; and (c) any other party’s access and use of the Products with your assistance or using any device or account that you own or control.
[](#no_warranties)
No Warranties
--------------------------------
The Products is provided on an "AS IS" and "AS AVAILABLE" basis. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ANY REPRESENTATIONS AND WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING (BUT NOT LIMITED TO) THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
You acknowledge and agree that your use of the Products is at your own risk. We do not represent or warrant that access to the Products will be continuous, uninterrupted, timely, or secure; that the information contained in the Products will be accurate, reliable, complete, or current; or that the Products will be free from errors, defects, viruses, or other harmful elements. No advice, information, or statement that we make should be treated as creating any warranty concerning the Products. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Products.
Similarly, the Protocol is provided "AS IS", at your own risk, and without warranties of any kind. Although we contributed to the initial code for the Protocol, we do not provide, own, or control the Protocol, which is run autonomously without any headcount by smart contracts deployed on various blockchains. Upgrades and modifications to the Protocol are generally managed in a community-driven way. No developer or entity involved in creating the Protocol will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of, the Protocol, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Products.
[](#no_refunds)
No Refunds
--------------------------
Any payments or financial transactions that you engage in with your cryptographic assets will be processed via automated smart contracts. Once executed, we have no control over these payments or transactions, nor do we have the ability to reverse any payments or transactions. We have no liability to you or to any third party for any claims or damages that may arise as a result of any payments or transactions that you engage in via the Products. Except as expressly provided for herein, we do not provide refunds for any transactions that you might make on or through the Products.
[](#limitation_of_liability)
Limitation of Liability
----------------------------------------------------
UNDER NO CIRCUMSTANCES SHALL WE OR ANY OF OUR OFFICERS, DIRECTORS, EMPLOYEES, CONTRACTORS, AGENTS, AFFILIATES, OR SUBSIDIARIES BE LIABLE TO YOU FOR ANY INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES, INCLUDING (BUT NOT LIMITED TO) DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA, OR OTHER INTANGIBLE PROPERTY, ARISING OUT OF OR RELATING TO ANY ACCESS OR USE OF THE PRODUCTS, NOR WILL WE BE RESPONSIBLE FOR ANY DAMAGE, LOSS, OR INJURY RESULTING FROM HACKING, TAMPERING, OR OTHER UNAUTHORIZED ACCESS OR USE OF THE Products OR THE INFORMATION CONTAINED WITHIN IT. WE ASSUME NO LIABILITY OR RESPONSIBILITY FOR ANY: (A) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT; (B) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM ANY ACCESS OR USE OF THE Products; © UNAUTHORIZED ACCESS OR USE OF ANY SECURE SERVER OR DATABASE IN OUR CONTROL, OR THE USE OF ANY INFORMATION OR DATA STORED THEREIN; (D) INTERRUPTION OR CESSATION OF FUNCTION RELATED TO THE Products; (E) BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE THAT MAY BE TRANSMITTED TO OR THROUGH THE Products; (F) ERRORS OR OMISSIONS IN, OR LOSS OR DAMAGE INCURRED AS A RESULT OF THE USE OF, ANY CONTENT MADE AVAILABLE THROUGH THE PRODUCTS; AND (G) THE DEFAMATORY, OFFENSIVE, OR ILLEGAL CONDUCT OF ANY THIRD PARTY.
[](#dispute_resolution)
Dispute Resolution
------------------------------------------
We will use our best efforts to resolve any potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us by sending an email to [\[email protected\]](/cdn-cgi/l/email-protection#fd91989a9c91bd988995988f948e9ed39e9290)
so that we can attempt to resolve it without resorting to formal dispute resolution. If we aren’t able to reach an informal resolution within sixty days of your email, then you and we both agree to resolve the potential dispute according to the process set forth below.
Any claim or controversy arising out of or relating to the Products, this Agreement, or any other acts or omissions for which you may contend that we are liable, including (but not limited to) any claim or controversy as to arbitrability ("Dispute"), shall be finally settled in accordance with the Arbitration Rules of the German Arbitration Institute (DIS) without recourse to the ordinary courts of law.
The arbitral tribunal shall be comprised of a sole arbitrator.
The seat of the arbitration is Munich, Germany.
The language of the arbitration shall be English.
The rules of law applicable to the merits shall be german law.
You understand that you are required to resolve all Disputes by binding arbitration. Unless we agree otherwise, the arbitrator may not consolidate your claims with those of any other party. Any judgment on the award rendered by the arbitrator may be entered in any court of competent jurisdiction.
[](#class_action_and_jury_trial_waiver)
Class Action and Jury Trial Waiver
--------------------------------------------------------------------------
You must bring any and all Disputes against us in your individual capacity and not as a plaintiff in or member of any purported class action, collective action, private attorney general action, or other representative proceeding. This provision applies to class arbitration. You and we both agree to waive the right to demand a trial by jury.
[](#governing_law)
Governing law
--------------------------------
You agree that the laws of Germany, without regard to principles of conflict of laws, govern this Agreement and any Dispute between you and us. You further agree that the Products shall be deemed to be based solely in Germany, and that although the Products may be available in other jurisdictions, its availability does not give rise to general or specific personal jurisdiction in any forum outside of Germany. You agree that the courts of Munich, Germany are the proper forum for any appeals of an arbitration award or for court proceedings in the event that this Agreement’s binding arbitration clause is found to be unenforceable.
[](#entire_agreement)
Entire Agreement
--------------------------------------
These terms constitute the entire agreement between you and us with respect to the subject matter hereof. This Agreement supersedes any and all prior or contemporaneous written and oral agreements, communications and other understandings (if any) relating to the subject matter of the terms.
[](#gas_fees)
Gas Fees
----------------------
Blockchain transactions require the payment of transaction fees to the appropriate network (“Gas Fees”). You will be solely responsible to pay the Gas Fees for any transaction that you initiate via the Products or the Protocol.
---
# The GIF sandbox - Etherisc Docs
The GIF sandbox
===============
The GIF sandbox is a place to experiment with the GIF framework. Running in a docker container, it contains a full deployment of the GIF in a ganache local blockchain instance, as well as a sample product which you can modify or extend.
For further information, follow the link:
* [The GIF sandbox - a place to learn and experiment](../sandbox/)
[← Basics of the GIF Framework](/learn/basics-gif)
---
# Privacy Policy for the websites and mobile apps of Etherisc GmbH - Etherisc Docs
Privacy Policy for the websites and mobile apps of Etherisc GmbH
================================================================
#### [](#data_protection)
Data protection
With this privacy policy we would like to inform you about how we process personal data. We are aware of the importance of the processing of personal data for the user and, accordingly, comply with all relevant legal requirements. The protection of your privacy is of utmost importance to us. That is why it is a matter of course for us to comply with the legal provisions on data protection.
[](#1_collection_processing_and_use_of_personal_information)
1\. Collection, processing and use of personal information
=======================================================================================================================
[](#1_1_personal_data)
1.1 Personal data
----------------------------------------
Personal data is all information about personal and factual circumstances of a particular or identifiable person. This includes information and information such as your name, address or other postal address, telephone number or your email address.
[](#1_2_legal_basis)
1.2 Legal basis
------------------------------------
The processing of your data is done on the following legal bases:
* With regard to data that you specify in forms etc., with your consent, Art. 6 para. 1 lit. a) GDPR
* in relation to the services you use, to carry out a contract with you, Art. 6 (1) lit. b) GDPR
* moreover, in particular for statistical data and online identifiers, on the basis of legitimate interests, Art. 6 (1) lit. f) GDPR (see below)
### [](#legitimate_interests)
Legitimate interests
When processing your data, we pursue the following legitimate interests:
\- improve the current user experience;
\- simplify it and make the landing page more informative;
\- get some statistics (how many users work with the applications).
[](#1_3_storage_time)
1.3 Storage time
--------------------------------------
We store your data,
\- if you have consented to the processing at the latest until you revoke your consent;
\- if we need the data for the execution of a contract, at most as long as the contractual relationship with you or legal storage periods (detailed information you can find in Section 1.5);
\- if we use the data on the basis of a legitimate interest, at most as long as your interest in deletion or anonymization does not prevail.
[](#1_4_uses)
1.4 Uses
----------------------
Personal data is collected by us only and only to the extent and for the purpose for which you provide us with the data.
We only use and store your personal data as part of our services for the following purposes, if you have expressly given us your consent:
1. Whitelisting of contributors prior to the Token Generating Event (TGE). The TGE has been finished 23rd July and we only store your data collected during the TGE;
2. Customer support (we use [Zendesk](https://www.zendesk.com/)
to process your requests);
3. Sending updates about the Decentralized Insurance Protocol Development (we use [Cleverreach](https://www.cleverreach.de/)
to send the newsletters);
4. Improve the current user experience, simplify it and make the landing page more informative (we use [Google Analytics](https://analytics.google.com/analytics/web/)
for these purposes).
[](#1_5_processing_overview)
1.5 Processing overview
----------------------------------------------------
Etherisc GmbH provided a service for registering within the TGE of the “Decentralized Insurance Foundation”. In this context, Etherisc performed an own KYC procedure or/and used service providers which offer a service for verifying identity documents (in particular passports, ID cards, driving licences) and matching these to an individual. The TGE registration is finished 23rd July. After this date Etherisc GmbH doesn’t collect the registration data but stores it.
Etherisc GmbH has commissioned IDnow GmbH to provide KYC services and KYC Spider AG to provide AML services in order to meet legal requirements (e.g. money laundering legislation, road traffic legislation) or to provide assurances of the identity of the end user. IDnow acts either as a contract data processor in accordance with §11 of the German Federal Data Protection Act (BDSG) resp. article 28 GDPR on the instructions of the customer or is itself the responsible body. KYC Spider acts as a contract data processor in accordance with article 10a Swiss Data Protection Act resp. article 28 GDPR.
Parts of the data collected by Etherisc GmbH and IDNow GmbH was used to perform Anti-money-laundering checks by KYC spider in Switzerland, especially e-mail address, first name, last name, place of residence, and date of birth. This data is then matched against a collection of international Anti-money-laundering databases. If no risk is found, the registration was completed. The data is deleted by KYC Spider after 90 days at the latest.
All the data collected by IDnow is used solely for the purposes of verifying identity documents and/or identifying the user and for fulfilling AML requirements. Processing of your personal data beyond the purpose for which the legal permission is granted will only be carried out with the explicit consent of the user. The data is transmitted to Etherisc GmbH and will be deleted on the IDnow servers after 90 days at the latest, unless Etherisc GmbH has previously issued a deletion request.
On the basis of statutory retention periods (e.g. in the context of the Money Laundering Act), the data can be stored by Etherisc GmbH or the “Decentralized Insurance Foundation” for the duration of the business relationship between Etherisc GmbH or the “Decentralized Insurance Foundation” and end-user and for up to five years after its termination.
[](#2_logfiles)
2\. Logfiles
============================
Every time you access our Internet pages, usage data is transmitted through the respective Internet browser and stored in log files, the so-called server log files. The records stored in this case contain the following data:
* Domain from which the user accesses the website
* Date and time of retrieval
* IP address of the accessing computer
* Website (s) that the user visits as part of the offer
* Transmitted amount of data, browser type and version
* Operating system used Name of the Internet service provider
* Message if the retrieval was successful
These logfile records are evaluated anonymously to improve the offering and make it more user- friendly, to find and fix bugs, and to control server load.
[](#3_cookies)
3\. Cookies
==========================
Cookies are small files that your browser places on your device in a designated directory. These cookies can be used to determine, for example, whether you have visited a website before. Most browsers accept cookies automatically. However, you can set your browser so that no cookies are stored or an explicit consent is required before saving a cookie. In addition, you can delete previously set cookies at any time. Please note that disabling cookies may result in restrictions on the use of our website.
We need the cookies for the following purposes: to improve the current user experience, simplify it and make the landing page more informative.
[](#4_web_analytics)
4\. Web analytics
======================================
We use - like almost every website operator - analysis tools in the form of tracking software to determine the frequency of use and the number of users of our website.
To optimize this website and our offer, we use Google Analytics, a web analytics service provided by Google Inc. ("Google"). Google Analytics uses so-called "cookies", text files that are stored on your computer and that allow an analysis of the use of the website by you. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. However, if IP anonymisation is activated on this website, your IP address will be shortened by Google beforehand within member states of the European Union or other parties to the Agreement on the European Economic Area. Only in exceptional cases will the full IP address be sent to a Google server in the US and shortened there. On behalf of the operator of this website, Google will use this information to evaluate your use of the website, to compile reports on the website activities for the website operators and to provide other services related to website activity and internet usage to the website operator. The IP address provided by Google Analytics as part of Google Analytics will not be merged with other Google data. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. to evaluate your use of the website to compile reports on the website activity for the website operators and to provide other services related to website activity and internet usage to the website operator. The IP address provided by Google Analytics as part of Google Analytics will not be merged with other Google data. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. to evaluate your use of the website to compile reports on the website activity for the website operators and to provide other services related to website activity and internet usage to the website operator. The IP address provided by Google Analytics as part of Google Analytics will not be merged with other Google data. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. to compile reports on the website activities for the website operators and to provide other services related to the website and internet usage to the website operator. The IP address provided by Google Analytics as part of Google Analytics will not be merged with other Google data. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. to compile reports on the website activities for the website operators and to provide other services related to the website and internet usage to the website operator. The IP address provided by Google Analytics as part of Google Analytics will not be merged with other Google data. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website. You can prevent the storage of cookies by a corresponding setting of your browser software; however, we point out that in this case you may not be able to fully use all functions of this website.
In addition, you may prevent the collection by Google of the data generated by the cookie and related to your use of the website (including your IP address) as well as the processing of this data by Google using the link [https://tools.google.com/dlpage/gaoptout?hl=de](https://tools.google.com/dlpage/gaoptout?hl=de)
. Download and install the available browser plugin. As an alternative to the browser add-on or within browsers on mobile devices, please click this link to prevent future detection by Google Analytics within this website (the opt-out only works in this browser and only for this domain). An opt-out cookie is stored on your device. If you delete your cookies in this browser, you must click this link again. For more information, see [https://tools.google.com/dlpage/gaoptout?hl=de](https://tools.google.com/dlpage/gaoptout?hl=de)
.
Please note that Google Analytics uses the code "gat.\_anonymizeIp ();" on this website. was extended to ensure the anonymous collection of IP addresses (so-called IP masking).
[](#5_rights_of_the_person_concerned)
5\. Rights of the person concerned
========================================================================
Right to information, correction, revocation, complaint, cancellation and blocking.
* You have the right to request information about whether and which personal data we process through you. You also have the right to request the correction of your personal data or its completion.
* In certain circumstances, you have the right to request that your personal information be deleted.
* In certain circumstances, you have the right to request that the processing of your personal data be restricted.
* You may withdraw your consent to the processing and use of your data in whole or in part at any time with future effect.
* You have the right to receive your personal information in a standard, structured and machine- readable format.
* If you have any questions, comments, complaints or requests for information in connection with our privacy policy and the processing of your personal data, you can contact our data protection officer in writing.
* You also have the right to complain to the relevant supervisory authority if you believe that the processing of your personal data violates the legal provisions.
[](#6_further_information_and_contacts)
6\. Further information and contacts
============================================================================
Please contact us as controller if you have any questions about this data protection declaration.
### [](#the_contact_address)
The contact address
Etherisc GmbH, Ruth-Drexel-Str. 154, DE-81927 München
[\[email protected\]](/cdn-cgi/l/email-protection#24474b4a504547506441504c41564d57470a474b49)
[https://etherisc.com/](https://etherisc.com/)
(Support button)
[](#8_status_of_this_privacy_policy)
8\. Status of this Privacy Policy
======================================================================
02/02/2024
We reserve the right to change this Privacy Policy at any time with future effect.
---
# FAQ Etherisc DIP staking - Etherisc Docs
FAQ Etherisc DIP staking
========================
[](#how_to_stake_dip)
How to stake DIP?
---------------------------------------
### [](#step_1_connect_your_wallet)
Step 1: Connect your wallet
Before staking, you must ensure you are connected with your wallet with our [Etherisc DIP staking app](https://staking.etherisc.com)
on the Ethereum mainnet and have a small amount of ETH to afford the network fee.
Caution: Please ensure you know how to use non-custodial wallets like Metamask before staking your tokens. As a rule of thumb, never give anyone your seed phrase or private key and never interact with non-official websites.
### [](#step_2_choose_a_bundle)
Step 2: Choose a bundle
Click the ‘Stake DIP’ button. You get a list of active bundles. Select a bundle by clicking on the 'SELECT’ button.
Alternatively, click 'STAKE' in the 'DIP staking' and 'My Stakes' areas on the right.
The bundles are single-asset pools and require DIP tokens. Stakers can acquire DIP tokens at several centralized and decentralized exchanges.
### [](#step_3_stake_your_dip_tokens)
Step 3: Stake your DIP tokens
Enter the desired amount of DIP tokens, read and agree to the terms and conditions by checking the box and clicking the button ‘STAKE.’
Note: You will be prompted to do an approved transaction each time.
Your deposit and rewards will be locked until the risk bundle expires. After the bundle’s lifetime ends, you must actively unstake the DIPs. There is no automatic transfer to your wallet.
[](#single_sided_double_sided_staking)
Single-sided / double-sided staking
--------------------------------------------------------------------------
In the first release of our Etherisc DIP staking app, we will offer single-sided staking only. You can only stake DIP in the Etherisc DIP staking app.
We will inform you immediately when double-sided staking is possible.
[](#ive_staked_tokens_can_i_stake_more)
I’ve staked tokens. Can I stake more?
-----------------------------------------------------------------------------
Of course! You can stake tokens as much as you like. You can reinvest in a bundle by clicking the 'My stakes' button or select another risk bundle by clicking the 'Stake DIP' button.
[](#is_there_a_minimum_stake_amount)
Is there a minimum stake amount?
---------------------------------------------------------------------
The minimum amount is 5.000 DIP tokens in the Etherisc DIP staking app.
[](#is_there_a_maximum_stake_amount)
Is there a maximum stake amount?
---------------------------------------------------------------------
There is no maximum stake amount.
[](#what_are_the_rewards_i_will_receive)
What are the rewards I will receive?
-----------------------------------------------------------------------------
The payout will be in DIP tokens. The reward rate is adjusted to market conditions. Please check the app for the current reward rate. The current reward rate applies to the payout.
[](#when_will_i_start_earning_rewards)
When will I start earning rewards?
-------------------------------------------------------------------------
From the moment you make a deposit, your passive income begins.
[](#when_will_i_receive_my_rewards)
When will I receive my rewards?
-------------------------------------------------------------------
You can claim your rewards at any time, at least after the end of the staking period. Just click the ‘CLAIM REWARDS’ button and your rewards will be sent to your wallet.
[](#can_i_also_add_my_rewards_to_my_total_staking_amount)
Can I also add my rewards to my total staking amount?
---------------------------------------------------------------------------------------------------------------
That does not work. Your rewards are always transferred to your wallet.
[](#is_there_a_minimum_lock_duration)
Is there a minimum lock duration?
-----------------------------------------------------------------------
The minimum lock duration depends on the bundle lifetime you staked your DIP tokens in.
[](#how_can_i_unstake_my_dip_tokens)
How can I unstake my DIP tokens?
---------------------------------------------------------------------
Just press the ‘Unstake DIP’ button. You will see all bundles in which unstaking is possible. The bundle needs to be expired or closed to unstake.
[](#what_is_restaking)
What is restaking?
-----------------------------------------
You can restake your DIP tokens when the risk bundle you have staked in is closed or expired. You can then restake your complete amount, i.e., all tokens and all rewards in a transaction, into a risk bundle where you haven’t staked DIP token yet.
[](#what_is_gasless_staking)
What is gasless staking?
-----------------------------------------------------
By checking the box, ‘I would like Etherisc to submit the transaction and pay fees on my behalf,’ you can set Etherisc to pay the fees. We cover the fees for the initial stake in a risk bundle that the current wallet has not yet staked in.
[](#what_is_gasless_restaking)
What is gasless restaking?
---------------------------------------------------------
Similar to gasless staking, you also have the choice of taking over the fees or Etherisc when you restake your DIP token.
| | |
| --- | --- |
| | Etherisc limits the gas fee. The maximum fee is adjusted to the current market conditions. You can see the current limit by hovering over the info button. The text that appears contains the current limit. Etherisc does not guarantee that the transaction will be executed immediately. |
[](#where_are_the_rewards_coming_from)
Where are the rewards coming from?
-------------------------------------------------------------------------
The Etherisc Foundation initially provided them.
[](#are_my_staked_dip_token_at_risk)
Are my staked DIP token at risk?
---------------------------------------------------------------------
No, the DIP tokens are not at risk. Even if there is a depeg, the DIP tokens are only used to unlock the capital in the risk bundles. In the case of a depeg, the payout comes from the USDT.
[](#can_i_stake_dip_token_on_its_own)
Can I stake DIP token on its own?
-----------------------------------------------------------------------
Yes sure. You can stake your DIP token without staking USDT.
[](#what_happens_to_my_staked_dip_tokens_if_the_owner_terminates_the_risk_bundle_before_the_end)
What happens to my staked DIP tokens if the owner terminates the risk bundle before the end?
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
You can leave your DIP token in the risk bundle until the end of the actual lifetime. You will continue to receive your reward.
[← Depeg Protection FAQ](/learn/depeg-faq)
[Basics of the GIF Framework →](/learn/basics-gif)
---
# Base - Etherisc Docs
Base
====
Contains the instance base contracts.
[](#contracts)
Contracts
------------------------
[← instance](/gif-next/3.x/api/instance)
[instance/module →](/gif-next/3.x/api/instance/module)
---
# GIF Next - Etherisc Docs
GIF Next
========
Documentation for the next version of the GIF framework smart contracts.
[](#coding_guidelines)
Coding guidelines
----------------------------------------
* If nothing else is specified, use the [OpenZeppeling Solidity coding guidelines](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/GUIDELINES.md#solidity-conventions)
and [Solidity style guide](https://docs.soliditylang.org/en/latest/style-guide.html)
.
* Functions within a contract are orders as follows: constructor, receive function (if exists), fallback function (if exists), external, public, internal, private. Within a grouping, place the view and pure functions last. (from [https://docs.soliditylang.org/en/latest/style-guide.html#order-of-functions](https://docs.soliditylang.org/en/latest/style-guide.html#order-of-functions)
)
* Do not use `require`. Always use custom errors.
* Put custom errors in the interface file (if it exists). Name the custom error `Error`. This helps to avoid duplicates. Example
interface IInstanceService {
error ErrorInstanceServiceRequestUnauhorized(address caller);
{...}
}
* Put events in the interface file (if it exists). Name the event `Log`. This helps to avoid duplicates. Example
event LogInstanceCloned(NftId clonedInstanceNftId, address owner, address caller);
* Do not use structs as event parameters.
* When creating a new contract file, use the same pragma and license (Apache-2.0) as the other contracts in the project.
* Remove dead code and commented code blocks, except if it is obvious that it will be relevant again within a reasonable amount of time. The code is not lost, its always accessible in the git history.
* Document all functions and events. See [this page for more information](howto-documentation)
.
* When copying code or other form of documentation, check the license and make sure that the code is compatible with the Apache-2.0 license. Always keep a reference the source in the comments!
* Document known limitations and shortcomings. If you cannot complete the code in time, add a TODO comment with a description of what is missing and create an issue for it.
* Use `TODO:` and `FIXME:` comments to mark code that needs to be fixed or improved.
* Include graphics and diagrams to explain complex concepts.
* Keep documentation current. If you change the code, update the documentation as well.
* Write meaningful commit messages and reference the issue number (`#262`) in the commit message.
* Use the Check-Effect-Interact pattern. See [here](https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html)
for more information.
* Ensure proper authorization of the contracts. See [this page](#authz.adoc)
for details.
[](#naming_conventions)
Naming conventions
------------------------------------------
* Function arguments and return types: If using custom data types, make the name include the type by appending the Type to the argument name, e.g. `function getInfo(NftId bundleNftId)` instead of `function getInfo(NftId bundleId)`. Background: Custom data types are lost when using the ABI or Typescript binding classes (e.g. instead of `NftID` a `uint96` is used), so the type needs to be included in the name to make it clear what the argument is without having to look at the documentation or checking the solidity source code.
* When naming a field or an attribute `id` and the context is not clear, call it `nftId` instead so its clear what type of id it is as there will be multiple ids for different kind of objects. Example: if you the function has a bundle nft id and a policy nft id as arguments, call them `bundleNftId` and `policyNftId` instead of `id` and `policyId`. In case of doubt, be a bit more verbose for the sake of clarity.
* When naming things, remember that the code will likely be used in Javascript/Typescript as well, so avoid names that are reserved in Javascript/Typescript. A list of reserved words in Javascript can be found \[here\]([https://www.w3schools.com/js/js\_reserved.asp](https://www.w3schools.com/js/js_reserved.asp)
) and a list of reserved words in Typescript can be found \[here\]([https://www.tektutorialshub.com/typescript/identifiers-keywords-in-typescript/](https://www.tektutorialshub.com/typescript/identifiers-keywords-in-typescript/)
).
* Name custom errors `Error`.
* Name events `Log`.
* The name of test methods must be unique. Stick to the following naming convention: `test___`. Example: `test_Product_calculatePremium` or `test_Product_underwrite_BalanceTooLow`.
[](#example_project)
Example project
------------------------------------
Find an example project for the GIF framework component smart contracts at [https://github.com/etherisc/gif-next-sandbox](https://github.com/etherisc/gif-next-sandbox)
[Architecture →](/gif-next/3.x/arch)
---
# Accounting - Etherisc Docs
Accounting
==========
Contains contracts related to accounting and financial operations.
[](#contracts)
Contracts
------------------------
### [](#AccountingService)
`AccountingService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/accounting/AccountingService.sol)
import "@etherisc/gif-next/contracts/accounting/AccountingService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`decreaseComponentFees(instanceStore, componentNftId, feeAmount)`\]
* \[`increaseProductFees(instanceStore, productNftId, feeAmount)`\]
* \[`increaseProductFeesForPool(instanceStore, productNftId, feeAmount)`\]
* \[`decreaseProductFees(instanceStore, productNftId, feeAmount)`\]
* \[`increaseDistributionBalance(instanceStore, distributionNftId, amount, feeAmount)`\]
* \[`decreaseDistributionBalance(instanceStore, distributionNftId, amount, feeAmount)`\]
* \[`increaseDistributorBalance(instanceStore, distributorNftId, amount, feeAmount)`\]
* \[`decreaseDistributorBalance(instanceStore, distributorNftId, amount, feeAmount)`\]
* \[`increasePoolBalance(instanceStore, poolNftId, amount, feeAmount)`\]
* \[`decreasePoolBalance(instanceStore, poolNftId, amount, feeAmount)`\]
* \[`increaseBundleBalance(instanceStore, bundleNftId, amount, feeAmount)`\]
* \[`decreaseBundleBalance(instanceStore, bundleNftId, amount, feeAmount)`\]
* \[`increaseBundleBalanceForPool(instanceStore, bundleNftId, amount, feeAmount)`\]
* \[`decreaseBundleBalanceForPool(instanceStore, bundleNftId, amount, feeAmount)`\]
* \[`_changeTargetBalance(increase, instanceStore, targetNftId, objectType, amount, feeAmount)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IAccountingService
* \[`LogAccountingServiceBalanceChanged(nftId, amount, feeAmount, increase, objectType)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#AccountingService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#AccountingService-decreaseComponentFees-contract-InstanceStore-NftId-Amount-)
`decreaseComponentFees(contract InstanceStore instanceStore, NftId componentNftId, Amount feeAmount)` external
#### [](#AccountingService-increaseProductFees-contract-InstanceStore-NftId-Amount-)
`increaseProductFees(contract InstanceStore instanceStore, NftId productNftId, Amount feeAmount)` external
#### [](#AccountingService-increaseProductFeesForPool-contract-InstanceStore-NftId-Amount-)
`increaseProductFeesForPool(contract InstanceStore instanceStore, NftId productNftId, Amount feeAmount)` external
#### [](#AccountingService-decreaseProductFees-contract-InstanceStore-NftId-Amount-)
`decreaseProductFees(contract InstanceStore instanceStore, NftId productNftId, Amount feeAmount)` external
#### [](#AccountingService-increaseDistributionBalance-contract-InstanceStore-NftId-Amount-Amount-)
`increaseDistributionBalance(contract InstanceStore instanceStore, NftId distributionNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-decreaseDistributionBalance-contract-InstanceStore-NftId-Amount-Amount-)
`decreaseDistributionBalance(contract InstanceStore instanceStore, NftId distributionNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-increaseDistributorBalance-contract-InstanceStore-NftId-Amount-Amount-)
`increaseDistributorBalance(contract InstanceStore instanceStore, NftId distributorNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-decreaseDistributorBalance-contract-InstanceStore-NftId-Amount-Amount-)
`decreaseDistributorBalance(contract InstanceStore instanceStore, NftId distributorNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-increasePoolBalance-contract-InstanceStore-NftId-Amount-Amount-)
`increasePoolBalance(contract InstanceStore instanceStore, NftId poolNftId, Amount amount, Amount feeAmount)` public
#### [](#AccountingService-decreasePoolBalance-contract-InstanceStore-NftId-Amount-Amount-)
`decreasePoolBalance(contract InstanceStore instanceStore, NftId poolNftId, Amount amount, Amount feeAmount)` public
#### [](#AccountingService-increaseBundleBalance-contract-InstanceStore-NftId-Amount-Amount-)
`increaseBundleBalance(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-decreaseBundleBalance-contract-InstanceStore-NftId-Amount-Amount-)
`decreaseBundleBalance(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-increaseBundleBalanceForPool-contract-InstanceStore-NftId-Amount-Amount-)
`increaseBundleBalanceForPool(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-decreaseBundleBalanceForPool-contract-InstanceStore-NftId-Amount-Amount-)
`decreaseBundleBalanceForPool(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount, Amount feeAmount)` external
#### [](#AccountingService-_changeTargetBalance-bool-contract-InstanceStore-NftId-ObjectType-Amount-Amount-)
`_changeTargetBalance(bool increase, contract InstanceStore instanceStore, NftId targetNftId, ObjectType objectType, Amount amount, Amount feeAmount)` internal
#### [](#AccountingService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#AccountingServiceManager)
`AccountingServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/accounting/AccountingServiceManager.sol)
import "@etherisc/gif-next/contracts/accounting/AccountingServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getAccountingService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#AccountingServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with service implementation
#### [](#AccountingServiceManager-getAccountingService--)
`getAccountingService() → contract AccountingService` external
[← Fire insurance example](/gif-next/3.x/example-fire)
[authorization →](/gif-next/3.x/api/authorization)
---
# Acknowledgements
- Etherisc Docs
Acknowledgements
===================
The ideas in this paper are a collaborative result of many talks and discussions, online and in person, with some brilliant minds of the crypto-economic space. The Etherisc team would like to say “thank you” especially to the following people, who added considerable value to the draft: Ron Bernstein, Jake Brukhman, Alexander Bulkin, Alex Felix, William Mougayar, Micah Zoltu, to the current team, consisting of Matthias Zimmermann, Jan Stockhausen, Michiel Berende, Hui Lin Chiew, Sebastian Schlitter, Peter Koch, Koenraad de Jonghe, Damian Groß, Felizitas Mussenbrock-Strauß, Lydia Mussenbrock and last but not least all those members of our telegram channel and discord server, who gave valuable feedback and criticism and encouraged us to follow our path.
[](#1_about_this_document)
1 About this Document
================================================
[](#history)
History
--------------------
As a result of the Nov/Dec 2016 Hackathon, the Etherisc team wrote a whitepaper, which was released to the public in its Version 0.3. Focus of the hackathon was the attempt to outline the core of a blockchain based reinsurance market.
Two years later, we released version 1.01 of the whitepaper for the DIP token sale which took place from June 23rd to July 25th, 2018. The 2018 whitepaper outlined the main features of the Etherisc ecosystem, and also important aspects of the DIP token. It was already clear that staking would emerge as the core token utility, however, a long way had to be gone to iron out the details.
We also had only a rough idea of what the insurance framework would look like. Immediately after the token sale, we started implementing the framework which was released as “GIF Framework” in 2019.
[](#the_elevator_pitch)
The Elevator pitch
------------------------------------------
Giant corporations dominate the multi-trillion-dollar insurance industry. The insurance industry developed into an indispensable part of the modern economy, whilst sometimes being inefficient, intransparent, expensive and with inferior customer experience. It has become a commonplace to say that insurance is boring and unreliable.
When customers need help the most, they can struggle in vain to get reimbursed by corporations whose profits too often depend on not paying.
_Etherisc has built a platform for decentralized insurance applications that can be used by anyone who wants to offer insurance. Large and small companies, non-profit groups, or _insurtech_ startups._
To foster open innovation in the insurance space Etherisc has open sourced its platform from the beginning. It is Etheriscs goal to support a growing ecosystem that is owned and managed by the community of all participants.
We want to create insurance products that are transparent, fair and accessible for both customers and investors.
Etherisc can thus become the most widely used insurance platform in the world, providing insurance coverage to millions of underserved customers.
The Etherisc platform is built around a technical, blockchain-based Framework called “GIF.” GIF is an acronym that stands for “Generic Insurance Framework.” It consists of open-source smart contracts that implement generic insurance product and policy lifecycle functions. Thus, GIF enables a wide range of insurance types. GIF runs on a blockchain and is multi-chain and multi-tenant capable.
The GIF is particularly suited to host parametric insurance products. Parametric insurance covers predefined loss events immediately when they occur, with predefined and deterministic payouts, rather than compensating for actual damage. Events such as flight delays, droughts, heavy rainfall, or damage caused by hurricanes are covered.
_In parametric insurance loss events (the risks) are defined as functions of underlying indices or parameters that meet the criteria defined by the insurance product._
The GIF is open source, so anybody can deploy their own GIF instance, modify the code, fork it etc. However, we believe that a flourishing platform needs more than just some lines of code.
Therefore, any GIF instance can optionally be registered in a global registry which is maintained by a DAO, in which all platform stakeholders participate in the governance. Registered GIF instances need to comply with a set of rules which ensure that customers can feel safe when they interact with a registered GIF instance. This is achieved by granting badges and certificates to compliant GIF instances.
In this system, the native DIP token (Decentralized Insurance Protocol) plays a central role. Every participant and stakeholder is required to stake a certain amount of DIP tokens. Therefore, the DIP token is a utility token, with staking being the central utility. Staking is needed both for deploying products, oracles and risk pools, but also for investing in those risk pools. Staking will also grant voting rights in the governance model.
[](#chapters)
Chapters
----------------------
This whitepaper is the attempt to structure the overall picture of decentralized insurance along the new insights. The document is structured in 4 main chapters:
**In chapter two**, we explain the fundamental facts about insurance and the disadvantages of traditional insurance. We highlight the advantages of blockchain and the decentralized model in insurance and explain the interplay between customers, users and companies.
**Chapter three** explains the Etherisc perspective on insurance, policies, and parametric insurance. We define the three pillars of the Etherisc ecosystem and get into the technical side of GIF (Generic Insurance Framework). We define the generic lifecycle of the GIF functions. At the end of the chapter, we introduce the GIF Monitor.
**Chapter four** explains the DIP token and how it is used in Etherisc staking. We describe our staking model, the interaction of the different corresponding risk pools and the functions of the different tokens. The chapter is concluded with the topic of credits rewards and payment losses.
**Chapter five** deals with EGM (Etherisc Governance Model). We define the five core values as respect, partnership, responsibility, trust and public goods. They were followed by the structure of EGM and the participants and their roles. Details about the topics of global staking pool and monetary policy then round off the whitepaper with the appendix.
The final chapter six contains a list of all abbreviations and definitions of the most important terms.
[](#2_analysis_of_basic_insurance_paradigms)
2 Analysis of basic insurance paradigms
====================================================================================
[](#2_1overview)
2.1 Overview
-----------------------------
To understand the approach, strategies and goals of (this) insurance, it’s important to look at a general definition of what insurance is and does:
_“Insurance is a means of protection from financial loss in which, in exchange for a fee called “premium”, a party agrees to guarantee another party compensation in the event of a certain loss, damage, or injury. It is a form of risk management, primarily used to hedge against the risk of a contingent or uncertain loss.”\[[1](#_footnotedef_1 "View footnote.")\
\]_
This can occur as a contract in the form of a financial protection policy. The insured is the policyholder, whereas the insurer is the insurance-providing company, the insurance carrier, or the underwriter.\[[2](#_footnotedef_2 "View footnote.")\
\]
Having analyzed the basic principles of insurance, such as the definition, and having developed a token system on top of these principles, we can now analyze insurance and break costs and capital flows down into three elements:
**Expected value of risk**
Which is simply the redistribution of capital according to the risks among the participants.
**Capital costs for tail risks**
As the name indicates, the capital in risk pools is exposed to a risk of loss and must be held in the risk pool for a certain period. The capital providers are compensated for this risk. This compensation is calculated based on the limitation period and the insured risk.
**Transaction costs**
Costs of administration of insurance policies, for example, gas fees of bookings on the blockchain, booking fees in case of payment in FIAT money, costs for oracles, etc.
We argue that traditional insurance companies dominate these building blocks and thus rule the insurance market. The GIF framework and the underlying blockchain technology offer the opportunity to replace the encrusted processes of traditional insurance companies with lean decentralized structures using standardized and automated lean protocols. Tokens thereby map the capital and revenue flows.
Our conclusion from this analysis is that we need two types of tokens. The first one - the “DIP Token” - supports the coordination and economical incentivization of actors in a decentralized insurance system.
The second type of token represents risks - this type is not a single token but a class of similar tokens, one for each risk pool, we call those “risk pool tokens”.
In a distributed environment with many participants, building products as a collaborative effort, the protocol token serves as glue, as collateral, and as representation of the material and immaterial value of the network, much as Ether serves as a means to secure the stability of the Ethereum Blockchain.
In Chapter 4.1, we detail the DIP protocol token. Chapter 6 shows a concrete example of the use of the token in an insurance context.
[](#2_2_principles_of_insurance)
2.2 Principles of insurance
------------------------------------------------------------
We explain the principle of insurance with an example. The example is of course simplified, and serves the sole purpose to explain the principle.
We consider homeowners insurance. For customers, insurance is about probabilities of losses, so it would be interesting to see what the probability of a damage is. A homeowners insurance typically covers a number of perils, including fire, natural disasters, water, and even falling objects.\[[3](#_footnotedef_3 "View footnote.")\
\]
But it is difficult to obtain real numbers, as insurance companies are not very transparent with their fundamental data.footnote:\[A quick market survey in Germany shows that you get a homeowners insurance for considerably less than 0.1% of the value. For simplicity, we’ll assume that the premium is 0.1% plain and we don’t take insurance taxes etc. into account.\
\
From the relation premium/value, we can easily estimate an upper bound for the probability. One of the most fundamental principles of insurance is that the expected losses should not surpass the collected premiums (“Risk loading” - cf. [http://www.wiley.com/legacy/wileychi/eoas/pdfs/TAP027-.pdf](http://www.wiley.com/legacy/wileychi/eoas/pdfs/TAP027-.pdf)\
). The expected losses are - simplified - number of policies multiplied with the probability of loss multiplied with the loss (which is equal to the value), and collected premiums are number of policies multiplied with premium per policy. It follows that the probability can be approximated by premium/value, which is lower than 0.1% in our market test.\]
We will assume that, for our example, the probability is 0.1%.
For our fictional example, let’s assume insurance had not been invented yet. In this fictional world, Alice owns a house. The house is worth $100K. The probability of a complete disaster is 0.1% per year (that is one devastating event in 1,000 years). Alice wants to ensure that she has access to enough funds to get a new house in the case of a disaster. So she decides to get a loan of $100K and has to pay redemption (also called principal) and interest rate.
Additionally, she pays an interest rate of maybe 1%, so she has yearly costs of $1,100 ($100,000 loan \* 1% interest rate plus $100 annual redemption = $1100.00).
Now we show how pooling risks in an insurance scheme reduces these costs drastically.
### [](#2_2_1_sharing_the_expected_value_of_risk)
2.2.1 Sharing the expected value of risk
Assume 100,000 homeowners are coming together in a pool. Again, everybody pays a $100 share; this amount is now called the “premium”. They collect a total of $10,000,000 in premiums. But now there is a difference to Alice, who takes care only for herself: because of the law of large numbers\[[4](#_footnotedef_4 "View footnote.")\
\], with a very high probability there will only be about 100 fires, causing a damage of about $10,000,000! And because the sum of all premiums is also $10,000,000, the whole damage can be paid out of the collected premiums, there is no need for every house owner to take on a loan. (Because premiums are collected at the beginning of the year, and all the houses “expected” to burn don’t all burn at the beginning of the year, but more or less are equally distributed over the year(s), there is a so called “float\[[5](#_footnotedef_5 "View footnote.")\
\]” of liquidity which can also generate a significant revenue. For simplicity, we won’t focus on this effect in this paper.
So the costs for each single house owner are now reduced from $1,100 to $100!
This difference asks for an economical explanation. Let’s have a closer look. First, if all house owners would follow Alice’s example, they would need a huge loan, from which only a tiny part of 0.1% would be needed on average. It is clear that providing unused liquidity is costly.
_Pooling of risks in insurance optimizes the use of capital, and the participants benefit from the reduced costs, not to speak of the difficulties to obtain a loan without collateralization!_
Second, if everybody only cares for himself, only a tiny fraction of participants are struck by disaster, and have the burden of actually paying back their loan. The others can pay back without loss, as long as they don’t need protection. In an insurance collective, we have solidarity: with the premiums, everybody pays for the damages of the others.
To summarize, the risk pool offers three advantages for the participants:
1. Building a large liquidity pool.
2. Guaranteed access to this liquidity in case of a damage.
3. Mutual subsidizing of damages.
Such a pool may be designed solely to benefit its’ participants, and to not make any “profit”. If the pool did generate profits, these profits could be distributed back to the participants, effectively reducing the premiums again to a level where no profits are generated. Such an insurance would have a loss ratio of 100%, because all premiums are used to pay the losses.
This is the very basic effect of risk transfer in insurance. Please note that the effect increases with the pool size.
But still, this is not the whole story.
### [](#2_2_2_sharing_the_tail_risks)
2.2.2 Sharing the tail risks
In some years, there are more fires, in other years, less. To account for these variations in damages, the whole pool has to raise some money, e.g. $10M, to cover the unlikely event of a burst of many fires in one particular year. And let’s suppose that the interest rate for this capital is even particularly high, e.g 20%. We will have total costs for this capital of $2M. The interest rate for the capital is a function of the risk and the riskless interest rate on the capital market; in an efficient market, the interest rate will compensate for the higher risk in comparison with a risk-free investment and will also contain a fair profit. So basically, this is where profits are generated for providing capital in an insurance structure.
The overall costs of $2M are distributed among all house owners, yielding an additional cost of $20 per house owner per year, which is added to the premium.
So after this, there is also a protection against “tail risks” or “black swan events”, at a cost of $20 per house owner. Again, the risk diversification effect increases with the pool size.
Overall, participants now pay $120 per year for their house insurance. The loss ratio is now reduced to 83% because of the capital costs of protecting the tail risks.\[[6](#_footnotedef_6 "View footnote.")\
\]
### [](#2_2_3_sharing_the_transaction_costs)
2.2.3 Sharing the transaction costs
To organize 100,000 people in a pool, a professional structure is needed. Otherwise, every single participant would have to coordinate, which would simply be impossible. The operation of this professional structure adds transaction costs to the premium. This is the reason why insurance companies have come into existence:
\_They provide a way to decrease transaction costs for the participants of the pool, creating an economy of scale and coordinating a huge number of participants and employees.\[[7](#_footnotedef_7 "View footnote.")\
\] \_
The effect is considerable and enables the modern form of insurance with huge customer bases and a capitalization which can cover even global catastrophic events like hurricanes and earthquakes. However, the remaining transaction costs are still considerable: a recent study by KPMG shows the impact on the loss ratio, which is about 66% in the average.\[[8](#_footnotedef_8 "View footnote.")\
\]
### [](#2_2_4_information_asymmetry)
2.2.4 Information asymmetry
Together with the reduction of transaction costs comes an asymmetry of information, which leads to a further increase of costs and to incredible profits for the big insurance companies.
_The unbounded collection of customer data and the exclusive exploitation of this data is a consequence of this imbalanced relationship._
It creates an “unfair competitive advantage” for existing companies: companies with big data vaults can offer better products, and thus further optimize their database.
One of the core goals of a decentralized insurance platform is the disruption of this circle, giving back to customers the ownership of their data.
### [](#2_2_5_summary)
2.2.5 Summary
The three elements described above; risk pooling, risk transfer, and efficient administration are necessary. You can’t have insurance without each of them.
For the purposes of this paper, I will call them:
1. expected value of the risk
2. capital costs for tail risks
3. transaction costs
As we have seen, a community may not wish to generate profit from the first element. The second element yields a risk fee for binding capital which depends on the structure of the particular risk: It is typically lower if the risks are granular and uncorrelated; it is typically higher if the risks are clustered or correlated. The third one depends on the complexity of the process. A simple and highly standardized insurance “product” has a smaller transaction complexity than a more complicated, non-standardized product. This will be reflected in lower transaction costs.
The three elements are completely independent of the underlying technology, economic environment or currencies. They are the atomic building blocks of every risk-sharing system.\[[9](#_footnotedef_9 "View footnote.")\
\]
As an additional aspect we have seen the information asymmetry which is inherent in the traditional insurance systems, and which is undesirable.
The distribution of expected value (element 1) and capital costs for tail risks among participants (element 2) is inevitable and not specific for a blockchain solution. Therefore, let’s focus on the third element.
_Utilizing blockchain technology, an arbitrary number of participants can coordinate on an economic task without the legal structure of a firm, with significant gains in efficiency and respective reduction in transaction costs._
Transaction costs also appear in another context: regulations, which are deemed necessary to protect customers in a context with built-in conflicts of interest. Regulations form a very effective “competitor” barrier to entry. While insurance companies often complain about the burdens of regulations, they actually don’t have much interest in reducing these burdens, as they discourage new competitors from entering the market.
[](#2_3_blockchain_helps_to_solve_issues_of_traditional_insurance)
2.3 Blockchain helps to solve issues of traditional insurance
--------------------------------------------------------------------------------------------------------------------------------
While the current insurance business has evolved over centuries, and is optimized in many aspects, we have seen that it has severe shortcomings to the disadvantage of customers. We will outline some properties of an alternative system, which remedies these shortcomings.
First, an alternative system should of course offer the basic ingredients of any insurance system: covering expected losses, covering tail risks, and covering necessary transaction costs. Obviously, we need ways to capitalize such a system, and we need a system to reduce transaction costs to a minimum. Transaction costs cannot be eliminated completely. But open markets have proven to be a solution for these challenges, and therefore, we propose a market-based approach with two components:
* an open marketplace for capitalization of risks
* an open marketplace for insurance related services
This is where blockchain comes into play:
_A_\_ decentralized solution on the _blockchain_ implements such open marketplaces in a way that is collusion resistant and has no single points of failure._\__
We can watch the emergence of many such marketplaces for different domains, like computation, file storage, exchange of assets; and insurance is just another domain in this respect.
More specific, blockchain helps to solve some of the main problems which pile up costs in traditional insurance companies:
1. Coordination (“managerial”) costs.
2. Conflict of interest between customers and company.
3. Information asymmetry between customers and company.
4. Restricted access to risk pool profits
5. Long time to market
6. Limited access to certain capital markets (e.g. crypto)
**Advantage 1:**
**Cheaper as coordination costs are low.** In traditional firms, you have two types of employees: the first group is doing the actual work, the second group is coordinating the whole system. The larger a company grows, the more energy flows in the second group (like a circle, the first group forms the rim of the circle, the second the area; the larger the circle, the less efficient are the processes, and the more energy flows into the coordination of the coordinators). Blockchain helps reduce these coordination costs. Instead of a posse of managers, “smart contracts”\[[10](#_footnotedef_10 "View footnote.")\
\] act as trustless hubs between the agents at the rim of the system, and thus eliminate most of the costs and inefficiency of management.
**Advantage 2:**
**More transparent / independent / trustworthy .** In a traditional insurance company, the company “owns” the whole process, including the tasks which tend to raise conflicts of interest between customer and company. A perfect example is claims management: The claims manager has the explicit goal of minimizing payouts for damages, because they are an employee of the insurance provider! Of course there is a guild of “independent” appraisers and experts, but who pays them?
Blockchain solves this conflict of interest, by enabling truly independent experts (who for example may be publicly ranked by their reputation for efficiency or fairness), and whose work is independent of the insurance provider, as well as transparent and auditable by the whole community.
The same is valid for another area, where the conflict of interest is (intentionally) not obvious; consider Product Design. An insurance company has a big advantage over customers, because they can design products in a way which perhaps unfairly maximizes revenues (sales) and minimizes payouts (expenses).
For example if a customer expects a payout from an insurance policy they bought for a particular “event” but the insurance company does not provide the payout because the company maintains that the policy bought doesn’t actually cover that “event”, the customer experience is severely degraded and trust is eroded between consumers and insurance providers.
**Advantage 3:**
**More transparent / fair through blockchain smart contracts.** Insurance companies collect data and information in huge private silos in proprietary ways, and the data is often not shared. This information asymmetry is a source of inefficiency and the origin of high transaction costs.
The experience of companies in analyzing this data is considered one of the key differentiators in the market. Decisions based on this data are not transparent and difficult to challenge due to the lack of insight into the evaluations.
In a blockchain environment, however, all fundamental data and the decisions based on this data are transparent and objectively validated.
**Advantage 4:**
**Democratised access.** The risk pools of traditional insurance companies are attractive investment instruments. However, they are not publicly accessible and the profits generated benefit only a small group of investors.
_Blockchain democratizes access to risk pools by tokenizing risks with "risk pool _tokens_."_
**Advantage 5:**
\*Flexibility and scalability \*Composability is the general ability of components of a system to be recombined into larger structures and for the output of one to be the input of another. In simple terms, the best example is Lego, where every piece can connect to every other piece. Within Crypto, composability is the ability of decentralized applications (dApps) and DAOs to effectively clone and integrate one another (syntactic composability), and for software components such as tokens and messages to be interoperable between them (morphological composability).
**Advantage 6:**
\*Blockchain enables more efficient collateral management. The creation and digitization of collateral tokens like stablecoins or similar assets and new financial primitives like staking facilitate new markets and possibilities.
[](#2_4_why_insurance_can_benefit_from_decentralization)
2.4 Why insurance can benefit from decentralization
------------------------------------------------------------------------------------------------------------
### [](#2_4_1_why_is_insurance_a_candidate_for_decentralization)
2.4.1 Why is insurance a candidate for decentralization?
As a multi-trillion dollar industry dominated by huge corporations, insurance is often confronted with obstacles such as strict regulations, and misalignments of company and consumer incentives, which led to the insurance world often being inefficient and expensive. The ultimate goal is to avoid cases like customers having to fight for reimbursement from companies whose profits often depend on avoiding paying out in a targeted manner.
Etherisc is building a platform for decentralized insurance applications. The platform can be used by corporates, large and small, not-for-profit groups and insurtech startups to provide better products and services. We aim to use blockchain technology to make insurance faster, cheaper and more transparent and democratize access to investing in insurance products.
_Blockchain can provide the means to disintermediate the market with a peer-to-peer risk platform that helps insurance return to its roots as society’s safety net._
We encourage new groups building their own bespoke insurance risk pools and services on the platform. Etherisc framework enables fully-compliant and licensed insurance products for the emerging blockchain economy. To offer an alternative to traditional monolithic insurance systems, we can identify some requirements and consequences for implementing a decentralized insurance protocol.
### [](#2_4_2_properties_of_decentralized_insurance)
2.4.2 Properties of decentralized insurance
1. The range of insurance is huge and far too complex to be covered by a single application. Therefore, we need a protocol and not just a (decentralized) application. Some tools are needed to incentivize participants to use it. Promoting "network effects"\[[11](#_footnotedef_11 "View footnote.")\
\] is one tool that can lead to a sustainable and growing user base.
A policy may cover a particular product, but a single policy will not generate the network effects to create multiple large pools of similar risks necessary to take advantage of the "law of large numbers."
2. A decentralized insurance protocol can partially or fully replace the traditional insurance business model. It does this through disaggregation of end-to-end processes, autonomous and automated smart contracts and procedures, a set of interaction rules for stakeholders and smart contracts . At the same time, a protocol allows for flexible extension and interpretation of the basic rules.
3. The development and operation of a protocol needs funding. Even if we can drastically reduce the coordination costs, there are still the costs for the initiation of the system - e.g. acquisition of licenses, development of smart contracts, audits, as well as costs for agents at the “rim” of the system which we cannot eliminate completely. Therefore we need a way to collect these costs from the ultimate customers and distribute them amongst these agents.
4. We also need a way to calculate and distribute the expected value of the risk and the capital costs for covering tail risks amongst the customers.
[](#2_5_protocol)
2.5 Protocol
------------------------------
### [](#2_5_1_owner_of_the_protocol_governance)
2.5.1 Owner of the protocol, governance
As an open standard, the protocol is a common good, it can be used and implemented by whoever likes it. We will take care that the entry barriers are as low as possible. However, for some portions of the protocol, a certification will be necessary, to reflect regulatory obligations and restrictions. We have founded a swiss based foundation as a legal body, which formally holds the IP rights of the protocol and ensures that the protocol can be used freely. We established a continuous, community-driven protocol improvement process similar to the EIP process for the Ethereum Platform.
The Etherisc Governance Model (EGM), its abstract and core values as well as other subtopics will be further elaborated in Chapter No.5.
### [](#2_5_2_outline_of_workflow_elements_of_the_protocol)
2.5.2 Outline of workflow elements of the protocol
* **Application for policy**
Process of offering a product and applying
* **Underwriting**
Process of accepting a policy
* **Collection of premiums**
Payment process, one-time and regular payments
* **Submitting of claims**
Process of submitting a claim, via oracle or manually
* **Claims assessment**
Process of assessing a claim, via oracle or manually. A claims verification process allows the system to determine which policies are legitimately claimed and to propagate agreed payments to claimants. In the case of parametric insurance, this process references data feeds about insurable events and is (fully) automated.
* **Identity Management & Privacy**
Process of KYC and AML, respecting privacy. This may involve private chains or off-chain storage of data.
* **Admission / Certification**
Admission of participants to offer products and perform parts of the protocol
* **Asset Management**
As funds flow in, we have to responsibly use funds which are not immediately needed.
### [](#2_6_community_of_customers_users_and_companies)
2.6 Community of customers, users and companies
The success of the platform will depend on a vivid community of users and companies. The token model reflects and supports this community. This community plays a central role in the realignment of incentives. Via tokens, customers can “own” their insurance. The community model facilitates the development of future mutuals and P2P-Insurance models.
_A community cannot be built from the outside, it has to grow from the inside._
However, experience shows that there are some success criteria for communities. Famous open source pioneer Pieter Hintjens, [http://hintjens.com/blog:10](http://hintjens.com/blog:10)
has drafted some which we consider to be helpful for an in-depth discussion:
* **Quality of mission**
A community can only grow by pursuing a worthwhile goal. The goal must be super-individual.
* **Freedom of access**
The community should not have barriers or walls, it should welcome those of goodwill and encourage participation.
* **Well-written rules**
If rules are necessary, they should be carefully written and obvious.
* **Strong neutral authority**
To resolve conflicts, a strong but neutral authority should be in place, which can be incorporated by a governance mechanism.
* **Proportional ownership**
"You own what you make"
* **Infinite spaces**
A single large project with many owners does not scale as well as a collection of many small projects, each with one or two owners. Communities grow best when people layer project upon project without limit.
* **Measurements of success**
In the community, your voice is as loud as the number of people using the project you “own.”
* **Tools and processes**
Much better tools means a faster, more efficient community.
* **Freedom to organize**
Let the community participants identify the problems, allocate the resources, and monitor success, precisely without top-down management.
* **Transparency**
Secrecy enables incompetence, and transparency promotes competence. The more public the organization’s work, the better.
* **Unstructures**
“Everyone owns what they make” and be prepared to move to a new home as and when needed.
* **Scalable participation**
You want no barriers at any point, but it must get harder and harder. This makes the community feel like a massive multiplayer game, where there’s always someone better than you, and you just have to try to catch up.
[](#3_gif_the_generic_insurance_framework)
3 GIF - the Generic Insurance Framework
==================================================================================
The GIF consists of building blocks that include the complete value chain: the insured, the insurer, the investor and the instance operator. First of all, you need insurance products that you can sell. The insurance products have a product owner who designs the products. The insurance products themselves are from smart contracts.
_Oracles are an essential part of the GIF for implementing parametric insurance. Oracles provide the necessary data, for example, flight or weather data, to the contracts in a GIF instance._
The risk pool is also a smart contract that keeps track of all details of the risk capital, the amounts paid in as policies and all the amounts paid out.
A GIF instance connects these individual roles and represents a complete executable entity defined by the GIF. Each instance consists of a blockchain’s operational set of GIF smart contracts. Different blockchains may run different instances.
[](#3_1_etherisc_basics_about_insurance)
3.1 Etherisc-basics about insurance
----------------------------------------------------------------------------
In the chapter '2.2 Principles of insurance', we used a practical example to illustrate how insurance is created and functions with the insured’s participation. In these chapters, we will explain and define insurance from the perspective of Etherisc.
#### [](#3_1_1_what_is_insurance)
3.1.1 What is insurance?
_Insurance is a means of protection against financial loss. It is a form of risk management whose primary purpose is to protect against the risk of possible or uncertain loss._
Insurance is a means of protection against financial loss. It is a form of risk management whose primary purpose is to protect against the risk of possible or uncertain loss. The loss associated with the risk may or may not be financial, but it must be reducible to financial terms.
An insurance company\[[12](#_footnotedef_12 "View footnote.")\
\] underwrites the risks of the insured. The insurance company can outsource all services, such as sales or data management, to other service providers. The only exception is the actual assumption of risk. This risk must always remain with the insurance company. Therefore, the company and their customers always need to have a proper accounting on which risks they cover and how it is collateralized.
_Via smart contracts, this can be done in a transparent and auditable way._
### [](#3_1_2_what_is_an_insurance_policy)
3.1.2 What is an insurance policy?
An insurance policy is a contract provided to the insured by the insurance company that sets out the conditions and circumstances under which the insurance company will make payouts to cover losses incurred by the insured due to recognized claims. In TradFi, this is typically a legal contract. In our context, a policy is simply a dataset stored on blockchain and manipulated via defined rules by a smart contract.
Let’s look at the lifecycle of a typical insurance policy. Such a lifecycle usually consists of the following chronologically listed sub-steps.
* The customer inquires about an insurance policy. They want to protect themselves against a specific risk by taking out an insurance policy.
* The insurance company examines the customer’s application.
* The application is accepted or rejected.
* In case of rejection, the customer is informed and no further activities occur.
* In case of acceptance, the contract comes to the “underwriter.” The acceptance of the application is called “underwriting.”
* The insurance company commits itself by the “underwriting” to take over the customer’s risk and transfer it to itself. It further undertakes to cover the loss if the insured event occurs.
* The customer, for his part, undertakes to pay the premium.
* Both declarations of obligation are documented in a contract. This contract is called the insurance policy.
* If a claim occurs, the customer reports it to the insurance company.
* The claim is checked by the insurance company and accepted or rejected.
* In case of acceptance, the agreed insurance sum is paid out. It is easy to see that the classic insurance business generates considerable bureaucracy and that many individual sub-steps require manual activities. For example, when a customer files a claim, the insurance company has to check the claim’s details manually. This involves work and, therefore, costs.
### [](#3_1_3_what_is_parametric_insurance)
3.1.3 What is parametric insurance?
Parametric insurance is an agreement between the insurance company and the insured that covers the occurrence of predefined events rather than manually reviewing and compensating for actual losses incurred.
Parametric insurance policies correspond to agreements between the insurance and the insured where the insurance approves payouts to the insured when predefined triggering events occur.
In parametric insurance, loss events (the risks) are defined as functions of underlying indices or parameters that meet the criteria defined by the insurance product. Example indices/parameters include rainfall amounts and wind speeds for insurance linked to weather conditions. In the case of flight delay insurance, the parameter/index can directly be derived from the difference between the actual arrival time and the scheduled arrival time of an insured flight.
_To make parametric insurance feasible and attractive to all involved parties, the underlying indices/parameters must be transparent, reliable and trusted._
Once such events occur, the insurance directly calculates and triggers a payout to the insured without an often costly claims acceptance process.
The big win of parametric insurance is its potential for efficiency and automation. Claims handling, one of the most complex and costly parts of the insurance business, can be reduced to a simple and fully automated process.
### [](#3_1_4_what_are_the_advantages_of_blockchain_in_insurance)
3.1.4 What are the advantages of blockchain in insurance?
There are several benefits that blockchain technology can provide to the insurance domain. Some of these benefits are directly related to the foundations of blockchain technology.
* Transparency and accountability for record keeping. Information regarding policies, claims and payouts may be stored on-chain. Once on the chain, they can neither be deleted nor changed without proper permission, and each time data is updated or adjusted, the original data is kept in the history. An entire audit trail is available and transparent for all data.
* Minimize friction and transaction costs for payment handling.
* Create new markets/opportunities by opening risk pools. The transparent pooling of large numbers of insurance policies of a particular type provides the opportunity to open up this market to a wider audience.
* These new markets also include the option to trade risks in small quantities, so called “Risk Pool Tokens.”
Blockchain technology can provide a lot of value, especially for parametric insurance.
* Providing this central data in a trusted way to the blockchain world will be managed through oracle services, making it very hard/too costly to inject manipulated index/parameter information into smart contracts implementing parametric insurance policies.
* Once the index/parameter feed is provided to policy contracts, parametric insurance will fully automate claims and payout handling.
* Immediate payouts. Running in a blockchain context and having automated claims/payout handling allows for near-real-time payouts.
[](#3_2_the_etherisc_model)
3.2 The Etherisc model
--------------------------------------------------
### [](#3_2_1_the_three_pillars_of_the_etherisc_ecosystem)
3.2.1 The three pillars of the Etherisc ecosystem

**Risk transfer market**
Raising capital to back the technical guarantees is done by investors. Investors will lock a certain amount of DIP tokens, also known as “staking.” The staked DIP tokens are a prerequisite to be then able to invest the actual risk capital in DIP or stablecoins.
The community of DIP token holders created the entire Etherisc ecosystem. Therefore, we will demand that parties who profit from the ecosystem own a share by holding and staking DIP tokens. This idea is borrowed from the space of cooperative enterprises. It reflects that the Etherisc ecosystem is a public good that needs to be protected from the [“tragedy of the commons.”](https://en.wikipedia.org/wiki/Tragedy_of_the_commons)
**Legal framework**
Insurance companies are highly regulated worldwide for good reasons, to protect customers and investors. A great deal of legislation has been enacted for this purpose in most countries. Concerning jurisdiction, a general distinction can be made between the American, European and Anglo-Saxon regions.
But even within these regions, each country has different legal and monetary frameworks. Etherisc engages with local regulators to help create an efficient regulatory environment for blockchain based insurance. Etherisc supports interested parties and helps to guide the coordination process with the relevant agencies and ministries.
The financial and organizational hurdles to establishing a new insurance company are high. For countries like Germany, Etherisc offers a new legal model where the legal claim is exchanged for a technical guarantee using blockchain and smart contracts. Thus, the provider — in this case Etherisc — is no longer subject to an insurance company’s legal and financial requirements. Still, for each project, product and jurisdiction, the legal framework has to be considered and the product owner is responsible for the proper implementation. The Etherisc team has accumulated a lot of experience in this field and is happy to share these insights with platform users.
**Technical framework**
Developed and maintained by Etherisc, the Generic Insurance Framework (GIF) allows to model, deploy and operate insurance products based on blockchain in a decentralized and transparent way.
Using the GIF, interested parties can quickly implement and securely operate their insurance products.
With the GIF, it is technically possible to model insurance policies individually.
[](#3_3_what_is_the_gif)
3.3 What is the GIF?
---------------------------------------------

GIF is an acronym and means generic insurance framework. At its core, it consists of a collection of open-source smart contracts that implement generic functions of the lifecycle of insurance products and policies.
Thus, GIF enables the modeling of a wide variety of insurance types.\_
Processing steps that run similarly in all products have been identified and made available as modules to design insurance products quickly and easily. Thus, only product-specific aspects, such as pricing, etc., need to be implemented for each product.
#### [](#3_3_1_gif_and_gif_instances)
3.3.1 GIF and GIF instances
To operate insurance products, including selling policies, collecting premiums, calculating trigger events and handling payouts, a complete execution environment is needed in addition to the smart contract collections that define products and policies.
This execution environment — called a GIF instance — may be seen as a comprehensive platform or marketplace in which GIF-based insurance products are managed and operated. Our goal is for a GIF instance to be used by many different and independent providers offering various insurance products. The figure below provides an overview of the stakeholder roles involved with a GIF instance.

[](#3_3_2_participants_on_the_platform)
3.3.2 Participants on the platform
--------------------------------------------------------------------------
**Insured/Customer**
The insured / customer is the policyholder who wants to transfer his risk to the risk pools. Third parties can offer payment gateways and integrations which remove the necessity to own cryptocurrency from the end customer.
**Investor**
Investors are interested in participating in risk pools to balance/diversify their risk portfolios. Investors provide collateral for risk pools in return for interest payments.
**Oracle owner**
One of the most promising applications of a decentralized insurance space is the way data is collected and managed. The oracle owner provides oracles that interface between the blockchain smart contracts and external data sources. In the case of flight delay insurance, the oracle informs the smart contract whether the flight landed in time, how much it was delayed or if it was completely canceled.
**Product owner**
The product owner designs and operates one or more products. This would be an insurance company or an MGA (managing general agent) in the traditional insurance industry. Due to the multi-client capability, a product owner can use all oracles located on the respective platform by the oracle owners.
**Risk pool keeper**
A risk pool keeper manages one or more risk pools.
_A risk pool is a smart contract that allocates (“pools”) several risks, represented by policy objects, to risk capital._
Risk pools collect collateral that risk investors invest. Losses are paid from the risk pool. Therefore, the capital in the pool is at (default) risk. Investors can top up their investments and also withdraw their funds.
**Instance operator**

Any complete deployment of a GIF framework is called a “GIF instance.” There will always be at least one complete instance of the GIF operated by the Etherisc project, but in principle, anybody can deploy a new GIF instance. The instance operator is the crucial role that operates a specific GIF instance.
The primary tasks of the instance operator are the administration of products and oracles and a few other basic actions. Any GIF instance is multi-client capable, which means that any number of product owners and oracle providers can be operated and administered on one GIF instance.
The instance operator is represented by an Ethereum address. The instance operator can be a natural person owning the private key of that address or a smart contract — either a multisig or a DAO structure. This enables an entirely decentralized operation of any GIF instance. One address can, of course, manage several independent GIF instances.
It is the declared goal of the Etherisc Project that GIF instances are controlled in a decentralized way - either by multisig or by DAOs with their own governance structure - and that they are controlled by the platform’s stakeholders (customers, product owners, oracle owners and risk pool keepers). In Chapter 5 we discuss how the ecosystem can incentivize this development.
[](#3_4_generic_lifecycle_functions_in_gif)
3.4 Generic lifecycle functions in GIF
----------------------------------------------------------------------------------
### [](#3_4_1_concept_of_components)
3.4.1 Concept of components
Each GIF instance manages different components. A component is a specific smart contract with a certain core functionality. The components can represent different core objects.
The core objects are:
* Products
* Oracles
* Risk pools
All components and thus the objects they contain can assume identical states and have the same life cycle but can differ significantly in terms of lifespan.
### [](#3_4_2_component_roles_and_lifecycle)
3.4.2 Component roles and lifecycle
Two roles can determine the life cycle of a component.
**Component owner**
A Component owner can be an oracle owner, a product owner, or a risk pool keeper, depending on which core object he manages.
**Instance operator**
The instance operator runs one or more GIF instances.

**A component in the GIF is always in one of the following states:**
* Created
* Proposed
* Declined
* Active
* Paused
* Suspended
* Archived
The transition between these states and the roles which those can be triggered by are described in the above diagram. The lifecycle of a component starts with its development and deployment on the blockchain. The component owner can implement their specific requirements in the component’s smart contract or use the generic functionality of the GIF components. In the next step, the component is registered, approved and activated by the instance operator in the GIF instance. The instance operator can also decline a component. The component is then deleted.
In the event of approval, the instance operator continues to check the technical and procedural details. The instance operator can also outsource the verification to an independent audit.
_Another condition is that the component owner must contribute a certain amount of DIP tokens to be allowed to operate in the GIF instance._
If the component is active, it can be used until it is set to either suspended or paused. The difference between suspended and paused is that only the instance operator can suspend a component or resume it from suspended to active. The component owner can set a component to paused, the component owner and the instance operator can unpause the component. If the component is inactivated (pause, suspended) and not reactivated (resume, unpause), it is not deleted but archived.
For each type of component (products, oracles, risk pools) we provide sample implementations which can be used as a starting point.
### [](#3_4_3_policy_lifecycle)
3.4.3 Policy lifecycle

Independent of the specific product, each policy processed on the GIF instance has a lifecycle. Typically, a policy undergoes several state changes during the lifecycle. While any product designer could implement his own lifecycle (in our terminology, the life cycle is called “PolicyFlow”), the GIF offers a default lifecycle which should be sufficient for most use cases. This generic life cycle is called “PolicyFlowDefault.”
**The “PolicyFlowDefault” lifecycle offers the following functions:**
* newApplication (to generate and store a new application from a customer)
* underwrite (to sign an application and create a new policy)
* decline (to reject an application)
* newClaim (to generate and store a new claim in case of loss)
* confirmClaim (to confirm a claim and create a payout)
* declineClaim (to reject a claim)
* payout (to confirm and initiate a payout)
### [](#3_4_4_payments)
3.4.4 Payments
The GIF instance is agnostic to the way payments are made. Pure crypto payments can be made directly to the product contract, while fiat payments need a fiat gateway and an external banking or credit card infrastructure. The core team can request information on how to implement fiat gateways.
[](#3_5_introducing_the_gif_monitor)
3.5 Introducing the GIF monitor
--------------------------------------------------------------------
The GIF system is entirely transparent for blockchain experts, but it can be difficult for non-blockchain experts to understand.
_That’s why we developed the GIF monitor to give everyone an overview of what’s happening on the blockchain of a GIF instance._
### [](#3_5_1_what_is_the_gif_monitor)
3.5.1 What is the GIF monitor?
The GIF monitor provides a structured overview of all generic building blocks available in the GIF framework for creating and operating an insurance product. You can view all events and business transactions of the complete instance.
The GIF monitor provides all this information transparently and in real-time online. The information is read from the blockchain and the GIF framework.
### [](#3_5_2_menu_items)
3.5.2 Menu items
The URL [https://gif-monitor.etherisc.com/](https://gif-monitor.etherisc.com/)
takes you to the ‘Home’ area of the GIF monitor. In the menu bar, you can choose from the following menu items.
In the ‘Home’ area you can click directly on the menu items in the menu bar and then select the corresponding menu item in the drop-down menu.
**Core**
The ‘Core’ area is by far the most extensive area. It displays the available GIF instances, the GIF core contracts per instance and the events of these core contracts. The core area shows the complete core contracts that each user can use.
Here you find the blockchains the instances use, such as xDai or Ethereum. By clicking on an instance, you will get detailed information like the instance ID, name, name of the blockchain, chain ID and status (active or not). Each instance is identified by its registry address. GIF is multi-chain capable and can run on all significant Ethereum-similar blockchains.
In this section you will find all 14 GIF core (smart) contracts. Each core contract provides essential functionality to a GIF Instance.
You can click on the contract name for all GIF core contracts to get to the contract details. Here you will see on which instance you are, the instance ID, the address on the blockchain, the name of the core contract, and the detailed contract functionality as described by its contract application binary (ABI) interface.
Here the contract events of the GIF core contracts are displayed.
Contract events are emitted by smart contracts during code execution and permanently stored on the chain. Events are primarily used to document significant changes in the data of the smart contracts, for example the change of status.
**Oracles**
The available oracles are displayed in the ‘Oracle’ area of the GIF monitor.
On this page, you will find all oracles available on the platform. Here you can view all input and callback formats as a product owner. In addition, the appropriate oracle can be requested from the Oracle owners.
By clicking on an oracle, the GIF monitor displays the details. Of course, individual oracles can also be implemented on request.
**Products**
In the ‘Products’ area, all products are listed that have been created in the framework. By clicking on a product, the details are displayed.
**Policies**
In the ‘policies’ area you can find information on every phase of the life cycle of a policy. Starting with information about the product, metadata, application, policy, claim and payout. Depending on the policy’s life cycle, more or fewer information blocks are displayed.
[](#4_tokenizing_insurance)
4 Tokenizing Insurance
==================================================
You can tokenize almost anything. Some things make less sense than others. We are convinced insurance is an increasingly hot topic around tokenization.
[](#4_1_the_dip_token)
4.1 The DIP Token
----------------------------------------
The acronym “DIP” stands for the “Decentralized Insurance Protocol” and the “Decentralized Insurance Platform”. DIP is the native token of Etherisc issued by the 'Decentralized Insurance Foundation' (DIF) based in Zug/Switzerland.
During the Etherisc DIP TGE (Token Generating Event), DIP tokens have been created on the public Ethereum mainnet. We preferred using this term over “ICO'' or “token sale.”
**Quick facts about the Etherisc DIP TGE**
* **Hardcap:** 30 Million USD
* **Total Supply:** 1 Billion (10^9)DIP
* **Tokens distributed to early investors and during TGE:** 300M DIP (= 30% of total supply)
* **TGE price:** 1 DIP = 0,10 USD
* **Only registered contributors** were able to participate in the Etherisc DIP TGE.
Participants (not customers) need tokens to join the platform’s "ecosystem." As a rule of thumb, everybody who wants to use the platform to earn money, will need to own and stake a certain number of DIP tokens. These DIP tokens remain in the ownership of the participant, and will be reimbursed if the participant intends to leave the platform - albeit with a certain notice period.
Depending on the service offered, a different number of tokens are required to use the platform or offer services on the platform. Simple services require a small number of tokens, while complex or critical services require more tokens. The amount of tokens that must be provided as stake depends on the potential damage caused by participant misconduct or violation of the platform terms. The staking of DIP tokens is different from the staking of assets in risk pools, which we will discuss below.
Staked DIP tokens can be “slashed” in case of bad behavior, e.g. violation of certain terms or requirements. The slashing rules will be published on the Etherisc website.
In the future, these rules and parameters will be the basis for controlling the platform. The DIP token serves as collateral and a representation of the network’s tangible and intangible value similar to the way financial resources serve to secure operating resources in a cooperative.
[](#4_2_the_etherisc_staking_model)
4.2 The Etherisc Staking Model
------------------------------------------------------------------
_Staking is still in beta - please expect that the Etherisc Staking Model may undergo substantial changes in the near future!_
In the Etherisc ecosystem, staking comes in **two different flavors:**
1. The first type of staking is staking of DIP tokens in a “Global Staking Pool”. The first type of staking ensures that participants who earn money using the platform have “skin in the game”, and also ensures that participants are economically incentivized to behave compliant to the platform rules.
2. The second type of staking is staking of crypto assets, typically stablecoins, in risk pools. These assets carry the insurance risk.
### [](#4_2_1_staking_for_risk_pools)
4.2.1 Staking for Risk Pools
When you buy an insurance policy, you expect a payout in the event of a claim. To ensure that there is always enough liquidity to start or continue selling policies and to service all payouts, we plan to set up a system with two corresponding risk pools.
The two corresponding risk pools will collect premiums for all policies sold and additional liquidity provided by investors. Each well-designed risk pool is subject to an actuarial model for the insured risk and thus determines a certain probability of default for each policy.
We define staking in the decentralized insurance context as:
\_"The process of attracting and binding capital from investors to specific risk pools to cover their tail risks." \_
Net premiums (after deduction of costs) from the purchase of policies are paid into the risk pool, and claims are covered from the funds of the risk pool. An investor chooses an investment option based on risk tolerance and portfolio structure.
Alternatively, the investor selects his investment according to ethical aspects such as environmental friendliness, climate neutrality, or social commitment. If necessary, he accepts a lower profit to offer insurance to small farmers, for example. We will always encourage the implementation of green & fair products on the GIF!
### [](#4_2_2_trustless_risk_pools)
4.2.2 Trustless Risk Pools
For a trustless risk pool to function, methods must be implemented that technically and transparently guarantee that the interests of both the insured and investors are met. For the insured, this means that we can prove that the risk pool will always be able to fulfill claims.
For investors, this means they receive a fair share of the profits made and can decide for which risks they will engage with their funds. This results in the need for the system to run entirely on the blockchain. On blockchain, computation is expensive, so we need to keep these calculations efficient. To achieve this goal, we plan to implement "epochs" into our risk pools. The duration of an epoch will depend on the product. For each epoch, all policies sold will be treated the same. This step reduces the complexity massively.
### [](#4_2_3_the_basic_idea_of_risk_pools_and_rewards_in_insurance)
4.2.3 The basic idea of risk pools and rewards in insurance
The core economic process of insurance, the transfer of risk between insureds and investors, is implemented in the GIF framework through risk pools.
While the standard risk pool template includes all the core functions for processing premiums, claims, deposits, payouts, and returns, the template leaves maximum flexibility for risk pool keepers to design their pool’s economic model to appeal to insureds, product owners, and investors.
### [](#4_2_4_core_functions_of_a_risk_pool)
4.2.4 Core functions of a risk pool
* Receive premiums in the form of native tokens or stable coins.
* Receive investment deposits in stable coins or tokens as specified by the risk pool keeper and the product owner.
* Manage investment deposits. An investor must have insight into the status of his investment at any time.
* Payout claims in case of loss.
* Processing investment withdrawals. This mechanism is designed so that the risk capital can be paid out only when it no longer serves as a security of concluded policies.
* Process profit distribution. A significant part of the paid premiums is distributed as profit to the investors depending on the investment amount, the period of the deposit and the risk taken.
* Autonomous control of risk pool parameters. The size of risk pools depends on the demand for the underlying product. We will provide mechanisms that allow autonomous control of risk pool parameters.
[](#4_3_implementation_of_risk_pools_in_the_gif)
4.3 Implementation of Risk Pools in the GIF
--------------------------------------------------------------------------------------------
The standard risk pools will initially consist of a primary risk pool (PRP). Optionally, secondary risk pools (SRP) can be created. This combination of two risk pools provides complete flexibility for insurance products and investors.
### [](#4_3_1_primary_risk_pools_prp)
4.3.1 Primary Risk Pools (PRP)
The primary risk pools (PRP) will receive the net premiums (i.e. gross premiums minus costs) paid by insurers in stablecoins (e.g. USDC, in this example, or xDai at Flight Delay). in exchange for assets staked by the investor The PRP will generate risk pool NFTs.
An investor will not transfer his DIP token directly into the PRP but into the SRP. The deposited DIP tokens are collected and transferred to the PRP at the end of an epoch, and the PRP generates a new risk pool NFT; the owner is the SRP. The investor receives the equivalent value of his deposited DIP tokens in risk pool tokens (RPT) minted by the SRP.
The global staking pool will span all primary risk pools of a GIF instance. Comparable to reinsurance, the pool steps in if, for example, black swan events lead to the insolvency of a primary risk pool, then the parachute pool steps in. Investors can also stake their tokens and stable coins in the global staking pool.

### [](#4_3_2_risk_pool_token)
4.3.2 Risk pool token
If the investor stakes assets in the primary risk pool, he receives a risk pool NFT as a receipt. While NFTs are tradeable in principle, we expect the risk pool NFTs to be illiquid. To facilitate trading of risks, we will introduce fungible risk pool tokens (RPT) via so-called “Secondary Risk Pools”. A secondary risk pool will acquire the risk pool NFTs of the primary risk pool and fractionalize it. Investors can invest in a secondary risk pool and will receive fungible (ERC-20) risk pool tokens in proportion to his share in the secondary risk pool. New risk pool tokens are minted when new capital is deposited into the pool. For each pool, specific RPT are minted.
### [](#4_3_3_risk_pool_nft)
4.3.3 Risk pool NFT
The NFTs are linked to a specific PRP and cover risks of individual insurance policies. The NFTs remain in the SRP and the RPTs in the investors' wallets. When all policies linked to an NFT are expired and all associated claims have been paid out the investor can withdraw all assets associated with the NFT.
### [](#4_3_4_why_epochs)
4.3.4 Why Epochs?
We want investors to deposit and terminate as quickly and efficiently as possible. But the protection of other investors and policyholders is also essential to us. So we have found a compromise that benefits all parties, the Epochs.Epochs massively reduce computational complexity, a limiting factor in smart contracts due to blocking gas limits. The epoch concept can execute every transaction with a fixed gas cap.
### [](#4_3_5_single_sideddouble_sidedmulti_sided_staking)
4.3.5 Single-sided/double-sided/multi-sided staking
In the first release of our risk pool, we will offer single-sided staking only (the risk is taken by a stablecoin only). However, you need to stake a certain amount of DIP tokens in the Global Staking Pool, in relation to the capital invested. So only when you have staked the base amount in DIP tokens can you contribute risk capital in the form stablecoins. In the future, investors will be able to stake different assets - not only stablecoins - depending on the requirements of the risk pool keeper in the risk pools.
### [](#4_3_6_credit_rewards_and_payment_losses)
4.3.6 Credit rewards and payment losses
The standard offered by the generic insurance framework is simple. Premiums are added to the risk pool (after deducting costs) and increase the value of the risk pool tokens. Payouts are paid from the pool and decrease the value of the risk pool tokens.
In the standard implementation, profits initially remain in the pool. Profits are realized the moment capital can be withdrawn from the pool.
Investors receive their premiums in the epoch in which the contract is concluded. The premiums paid by policyholders are credited proportionately in the ratio of personal risk capital / total risk capital. Any refunds in the event of a claim are shared proportionally by all risk capital providers who have contributed to the premiums since the policy’s inception.
So if you have two investors, investor 1 has DIP 100,000 staked, investor 2 has DIP 50,000 staked. Insurance is taken out with a premium of USDC 30. Investor 1 receives the equivalent of 20 USDC through the price gain of his RPT, Investor 2 receives the equivalent of 10 USDC. The USDC remain in the PRP.
If a claim is then made at USDC 90 on that policy, the USDC 90 will be paid out of the PRP. Investor 1 loses the equivalent of 60 USDC, Investor 2 loses the equivalent of 30 USDC.
[](#5_etherisc_governance_model_egm)
5 Etherisc Governance Model (EGM)
======================================================================
[](#5_1_abstract)
5.1 Abstract
------------------------------
1. The purpose of the Etherisc Governance Model (EGM) is to create an effective self-regulatory mechanism for the Etherisc ecosystem. Etherisc considers a baseline of rules and procedures as necessary to ensure that:
1. The platform operates in a way that is consistent with the rules and recommendations of the Decentralized Insurance Platform (DIP) protocol.
2. Participants of the platform conduct business in the interest of the good of the commons, while safeguarding the interests of customers and investors.
3. Market integrity is preserved, meaning no market abuse and all platform participants have equal access to accurate and transparent information.
2. Consistent with a decentralized infrastructure, regulation should be carried out by the community rather than a sole entity. Additionally, rules need to be enforceable to incentivise compliance. For rules to be enforceable, there needs to be an element of staking.
3. Beyond a smooth-functioning ecosystem being an end in itself, the EGM will be instrumental to strengthening confidence in the Etherisc decentralized insurance platform and support growth and massive adoption.
[](#5_2_core_values)
5.2 Core Values
------------------------------------
Any system of rules requires a set of underlying principles and “values”. Both the set and the meaning of these values is necessarily to a certain extent fuzzy and cannot be fully captured by any formal definition.
Some people would e.g. emphasize other values not listed here, or put it in different words. However, these rules have been proven to be helpful in other contexts which rely on decentralization and collaboration.
They serve as general guidelines to derive more precisely defined rules and requirements.
1. **Respect**
Each platform user, actor, stakeholder should respect and value diversity. We promote inclusiveness and treat others with tact, courtesy and respect. We abstain from and actively discourage discrimination in all forms.
2. **Collaboration**
The Decentralized Insurance Platform is based on strong, voluntary partnerships. The Platform will always encourage partnerships and cooperation. Each participant should be able to benefit from evolving partnerships.
3. **Responsibility**
Each participant shall act fully on his/her own responsibility, while the platform will provide any means to support this. All participants acknowledge their joint responsibility for the operations and development of the platform as a whole.
4. **Trust**
The platform encourages trustful behavior and will provide a safe environment for all participants. Each participant is committed to compliant behavior. Transparency is an important element in trust-building, therefore we encourage transparency as much as possible, without violating the justified needs for protection of each participant of the platform.
5. **Public good / Commons**
The platform as a whole serves the public good. It is a “commons”\[[13](#_footnotedef_13 "View footnote.")\
\] in the sense of Elinor Ostrom and operated by the community of all participants. Therefore, the governance rules for the platform are based on the eight rules for successful commons, coined by E. Ostrom. In chapter 5, we discuss how the “eight rules” are implemented in the EGM and DIP Protocol.
[](#5_3_high_level_structure_of_the_egm)
5.3 High Level Structure of the EGM
----------------------------------------------------------------------------
In the image below a number of actors/participants are mentioned, the names mentioned are written as an example and it may be that other actors and/or blockchains are added. In this image the following players are mentioned.

| Name | Short description |
| --- | --- |
| Decentralized Insurance Foundation | Development and promotion of the DIP protocol, funding of the development of the Generic Insurance Framework (GIF) |
| Kleros | Decentralized arbitration service and token curated registry |
| DAOstack | Software stack for DAOs including a library of governance protocols and interfaces for creating and managing DAOs |
| Mainnet | Example blockchain |
| Gnosis chain | Example blockchain |
| Avalanche | Example blockchain |
| Polygon | Example blockchain |
1. The four defining aspects of the EGM are as follows:
1. Platform participants as the topmost authority
2. The Decentralized Insurance Foundation as the non-profit, neutral link to the real-world institutions and legal systems
3. Certification of GIF instances as a market signaling mechanism to incentivise high standard of work
4. Dispute resolution via an independent arbitration board
2. The participants of the platform - be it insureds, product builders, or investors - are the topmost authority of the platform. Their stake is represented by governance tokens (vDIP), which are minted against staking DIP tokens in a governance contract. Governance tokens (vDIP) are used for decision making in all DAOs involved in the platform.
3. While the participants of the platform are represented by addresses on blockchain protocols, we need a link to the real world connecting the on-chain infrastructure with legal entities in the real world.
4. In the real world (“IRL”), the topmost authority is the not-for-profit Decentralized Insurance Foundation (DIF), based in Zug, Switzerland, and regulated according to Swiss Law.
5. The purpose of the DIF is defined in the notarial deed of the Foundation and cannot be changed:
_“The Foundation’s purpose is promoting and developing new technologies and applications, especially in the fields of new open and decentralized software architectures mainly in the insurance field. A dominating but not exclusive focus is set on the promotion and development of the so-called DIP-protocol and the related technologies, as well as the promotion and support of applications using the DIP-protocol.”_
1. Therefore, the only purpose of the Foundation is to serve the community of participants in building and using the DIP protocol.
2. The DIF is committed to strict neutrality. Therefore, the DIF will never engage in disputes between participants. For dispute resolution, the DIP Platform will use existing mechanisms like e.g. the Kleros arbitration board.
3. The DIF is formally represented by the Foundation Council.
4. The main task of the DIF in the context of the technical DIP Protocol is the certification of GIF Instances on the different blockchains. On each blockchain, there can be multiple GIF Instances. The rules for certification will be published. The rules should be such that, if possible, there is no ambiguity in interpretation and that people with basic technical understanding and common sense can make a decision whether a particular GIF Instance meets the requirements. Requirements include technical stability (like contract audits) and soundness, as well as legal compliance. Certified GIF Instances are registered in a Token Curated Registry. The concrete rules for certification of GIF Instances are currently work in progress.
5. Certification has no specific consequences - it’s just signaling “this GIF Instance has undergone thorough scrutiny and due diligence and it implements the rules and recommendations of the DIP Protocol”. Thus, we expect that a certification will act as a strong differentiator in the market and non-certification will essentially be a “red flag” for both customers and investors. This is how self-regulation works. However, in the future, other parties outside the DIP ecosystem could link access to certain services to valid certificates.
6. Each GIF Instance is operated by an Instance Operator. An instance operator can be represented by an EOA (externally owned address), a multisig, or a DAO. It is recommended that the Instance Operator is represented by a DAO, the members of which are the stakeholders of this GIF Instance.
7. Each GIF Instance may send a delegate in the Advisory Board of the DIF. The advisory board shall interact with the Foundation Council and represent the interests of the GIF Instances and its stakeholders with the Foundation Council. The advisory board and its decision-making processes are implemented as a DAO.
8. Each GIF Instance (or the DAO representing it) can implement governance rules on a more granular level, e.g. rules to decide which products may be listed on the instance and which not, as long as these rules are in accordance with our core values and the other rules of the platform.
9. Each GIF Instance needs to implement rules which ensure that the instance is able to participate in the funding of the EGM and the DIP protocol in general.
10. Disputes are resolved via an arbitration board. Possible disputes include e.g. registration of a GIF Instance in the TCR, or disputes in relation of insurance claims which cannot be resolved via smart contract logic (e.g. oracle malfunction).
[](#5_4_funding_of_the_egm_and_the_dip_protocol)
5.4 Funding of the EGM and the DIP Protocol
--------------------------------------------------------------------------------------------
1. The infrastructure to maintain the EGM, as well as the development and maintenance of DIP protocol (especially the development and maintenance of the GIF Framework) requires funding.
2. The funding is intended to only cover costs, to be self-sustaining and not profit-oriented.
3. Each GIF Instance will therefore be required to:
1. Stake a defined amount of DIP tokens in a governance staking contract
2. Pay a regular fee to cover the operational cost of the EGM
4. The required amount of stakes and fees are calculated based on the economic volume which is transacted on the particular instance. The exact scheme will be published in time.
5. In case of violation of rules, sanctions of different severity can be applied to misbehaving participants:
1. Financial penalties for misbehaving members
2. Slashing of staked DIP tokens
3. Exclusion of participants from a GIF Instance
4. Exclusion of a GIF Instance from the Token Curated Registry.
6. Part of the fees paid will be burned to create a slight deflationary effect on the DIP token.
[](#5_5_global_staking_pool)
5.5 Global Staking Pool
----------------------------------------------------
1. The DIF will maintain a global staking pool (GSP). The GSP will be deployed on the Ethereum Mainnet.
2. The GSP has the following objectives:
1. Provide an economic incentive for well-behavior
2. Provide a “sink” which will bind DIP tokens
3. Ensure that participants which profit from the Etherisc ecosystem, have “skin in the game” and aligned interests with the whole system.
3. Participants in the Etherisc ecosystem are expected to stake and lock a certain amount of DIP tokens in the GSP:
1. GIF Instance operators need to stake and lock tokens for each certified GIF Instance
2. Product owners need to stake and lock tokens for each product deployed and approved on a certified GIF Instance.
3. Oracle providers need to stake and lock tokens for each oracle deployed and approved on a certified GIF Instance.
4. Risk Pool Keepers need to stake and lock tokens for each risk pool deployed and approved on a certified GIF Instance.
5. Staking in the GSP is independent from staking in Risk Pools. Investors can stake in Risk Pools without having staked in the GSP, and the rules defined in this chapter do not apply to staking investors.
4. The amount to be staked and locked for each group of participants will be published on the Etherisc Website.
5. The amount to be staked and locked will correlate with the economic value which is created by the participant. The exact KPIs to be considered and the formulas to calculate the amount of DIP tokens to be staked will be published on the Etherisc website.
6. Tokens staked in the GSP can be locked by the stakers for different purposes:
1. For a GIF Instance (necessary for operation of a GIF Instance)
2. For a product (necessary for operation of a product)
3. For an oracle (necessary for operation of an oracle)
4. For a risk pool (necessary for operation of a risk pool)
5. For specific governance purposes (optional, to participate in specific governance decisions)
7. For each purpose, there is a “Lock Manager” who has the power to lock or unlock tokens. Initially, the lock managers are controlled by a multisig owned by the Foundation Council of the Decentralized Insurance Foundation. After a testing period, the control on the lock managers may be transferred to the DAO associated with the Decentralized Insurance Foundation.
8. Each participant who has staked and locked DIP tokens will be granted general voting rights in the Etherisc Governance Model. For specific purposes, there may be the requirement to additional stake and lock tokens in a governance lock manager. For each governance decision, the voting rights are calculated on a snapshot of the GSP at a certain block height.
9. Voting is performed byhttps://snapshot.org/#/\[ Snapshot voting\] using a strategy which reads the locked tokens out of the GSP at a certain block height.
10. The code of the GSP is published in the [global staking repo](https://github.com/etherisc/global-staking)
in the etherisc github.
[](#5_6_monetary_policy_of_the_dif)
5.6 Monetary policy of the DIF
------------------------------------------------------------------
1. As a major holder of DIP tokens (about 60% of the total supply of DIP tokens), the DIF is obligated to protect the interests of the DIP token holders. The treasury of the DIF is not counted in the circulating supply of DIP tokens.
2. The DIF may allocate grants or provide DIP tokens to incentivize the development and use of the DIP protocol. These grants and incentives will increase the circulating supply and could therefore lead to a dilution of the value of the DIP token. However, the DIF will always take care that grants and incentives are always in relation to the value created, so that the DIP token in total does not experience unnecessary dilution.
[](#5_7_appendix_eight_rules_for_successful_commons_and_how_they_are_implemented_in_the_dip_protocol)
5.7 Appendix: Eight Rules for successful commons and how they are implemented in the DIP Protocol
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Commons need to have clearly defined boundaries. In particular, who is entitled to access to what? Unless there’s a specified community of benefit, it becomes a free for all, and that’s not how commons work. The “boundaries” are implemented by the token curated registry for the GIF Instances, and the registries for products, oracles and risk pools in the GIF Instances itself.
2. Rules should fit local circumstances. There is no one-size-fits-all approach to common resource management. Rules should be dictated by local people and local ecological needs. The rules are always created on the lowest possible level. E.g. the top-level rules only govern which GIF Instances are certified. More granular rules are implemented on lower levels and they can be different for different GIF Instances, according to their needs.
3. Participatory decision-making is vital. There are all kinds of ways to make it happen, but people will be more likely to follow the rules if they had a hand in writing them. Involve as many people as possible in decision-making. Participation is implemented by the DAOs which govern the GIF Instances. Each GIF Instance is a member of the Advisory Board of the DIF and can represent their interests there.
4. Commons must be monitored. Once rules have been set, communities need a way of checking that people are keeping them. Commons don’t run on good will, but on accountability. The monitoring happens on two levels: The top level is given by the DIF, the Token Curated Registry of GIF Instances and the Arbitration Board. On a lower level, the monitoring is given by the DAOs governing the individual GIF Instances.
5. Sanctions for those who abuse the commons should be graduated. Ostrom observed that the commons that worked best didn’t just ban people who broke the rules. That tended to create resentment. Instead, they had systems of warnings and fines, as well as informal reputational consequences in the community. There are different methods of sanctioning, each with a different level of severity, see chapter 3.
6. Conflict resolution should be easily accessible. When issues come up, resolving them should be informal, cheap and straightforward. That means that anyone can take their problems for mediation, and nobody is shut out. Problems are solved rather than ignoring them because nobody wants to pay legal fees. This is implemented by the arbitration board which offers dispute resolution on every level.
7. Commons need the right to organize. Your commons rules won’t count for anything if a higher local authority doesn’t recognise them as legitimate. This is implemented by the written rules which govern the DIF and which in turn govern the DAOs representing the different GIF Instances.
8. Commons work best when nested within larger networks. Some things can be managed locally, but some might need wider regional cooperation – for example an irrigation network might depend on a river that others also draw on upstream. This is implemented by the hierarchical structure, the top of which is a legal foundation recognized by Swiss law.
[](#glossary_and_abbreviations)
Glossary and abbreviations
==========================================================
[](#glossary)
Glossary
----------------------
| Notion | Explanation / Definition |
| --- | --- |
| Black swan event | A rare but catastrophic event/ An event that comes as a surprise, has a major effect, and is often inappropriately rationalized after the fact with the benefit of hindsight |
| Collateralization | The process of securing a loan with a valuable asset/ The use of a valuable asset as collateral to secure a loan |
| Component owner | A component owner manages one or more components |
| Core object | |
| Decentralized insurance | Insurance which is run by a decentralized network |
| DIP token | Please have a look in the abbreviations |
| Ecosystem | |
| Etherisc framework | |
| Etherisc platform | Set of participants, stakeholders, rules, techniques, protocols, software system, smart contracts, which make up Etherisc as a whole |
| Float of liquidity | The average amount of liquidity which is not needed for claims |
| Generic Insurance Framework (GIF) | A library of modular, reusable, generic and secure smart contracts written in Solidity |
| GIF instance | Each complete deployment of a GIF is a GIF instance. It is autonomous and fully functional. Each GIF instance is a library of modular, reusable and secure smart contracts written in Solidity |
| Governance token | Governance token fall under the category of utility tokens. Our governance DIP token gives owners the right to vote on issues that determine the further development and operation of a GIF instance, risk pool, etc. |
| Instance operator | The instance operator is the crucial role that operates a specific GIF instance. The primary tasks of the instance operator are the administration of products and oracles and a few other basic actions |
| Insurance | A means of protection from financial loss/ A form of risk management, primarily used to hedge against the risk of a contingent or uncertain loss\[[14](#_footnotedef_14 "View footnote.")
\] |
| Investor | Investors bring in risk capital in risk pools or risk bundles in return for intest payments |
| Long tail risks | High implausible risks represented by the “long tail” of the risk distribution curve |
| Oracle owner | An oracle owner runs one or more oracles in one or more GIF instances |
| P2P-insurance models | A small group of individuals with common interest who combine their premiums to insure against risks |
| Parametric insurance | Insurance where the claims process is data-driven |
| Premium | Amount of money to purchase an protection policy. (insurance deleted) |
| Product owner | A product owner manages one or more products |
| Protected | The policyholder. He transfers his risk to the risk pools or risk bundles |
| Protocol token | A token which secures or enables a protocol |
| Risk bundle fragment investor | Small investors teaming up to run a risk bundle |
| Risk bundle NFT | When a risk bundle owner creates a risk bundle, an NFT is created analog to the risk pool NFT that secures and documents the ownership of the risk bundle. Thus, the risk bundle owner has proof that it is his risk bundle and can sell the bundle |
| Risk bundle owner | A risk bundle owner manages one or more risk bundles |
| Risk fee | The return on risk capital in the risk bundles and risk pools |
| Risk pool | A smart contract that collects funds that are used to compensate for insurance claims |
| Risk pool keeper | A risk pool keeper manages one or more risk pools |
| Risk pool NFT | When a risk pool keeper creates a risk pool, an NFT is created that secures and documents the ownership of the risk pool. Thus, the risk pool keeper has the proof that it is his risk pool and thanks to the NFT, risk pools are tradable |
| Risk pool token | A class of similar tokens, one for each risk pool, which represent risks |
| Risk sharing system | Risk sharing is sharing an uncertain outcome, and thus the risk of the outcome, between two or more parties to cover the potential loss from an uncertain event |
| Smart contract | A smart contract is a self-executing program on the blockchain that automates the actions required in an agreement or contract. Once completed, the transactions are trackable and irreversible |
| Stable coin | A cryptocurrency designed to have a relatively stable price, typically through being pegged to a commodity or currency or having its supply regulated by an algorithm |
| Staking | The process of investors locking a certain amount of DIP tokens to raise capital backing the technical guarantees |
| The good of the commons | |
| Tragedy of the commons | A social and political problem in which each individual is incentivized to act in a way that will ultimately be harmful to all individuals. According to Elinor Ostrom, this problem can be solved |
| Transaction costs | Costs to perform an economic transaction (not to be confused with transaction fees) |
| Transaction fees | The amount of gas you have to pay for the transfer of your token |
| | |
| | |
[](#abbreviations)
Abbreviations
--------------------------------
| Acronyms & Abbrevations | Explanation / Definition |
| --- | --- |
| NFT | Non fungible token |
| dAPP | Decentralized application |
| DAO | Decentralized autonomous organization |
| DIF | Decentralized insurance foundation |
| GIF | Generic insurance framework |
| DIP token | Decentralized insurance protocol token |
| EOA | Externally owned address |
| EGM | Etherisc governance model |
| P2P | Peer-to-peer |
| KPI | Key performance indicator |
* * *
[1](#_footnoteref_1)
. [https://en.wikipedia.org/wiki/Insurance](https://en.wikipedia.org/wiki/Insurance)
[2](#_footnoteref_2)
. [https://paytm.com/blog/insurance/what-is-insurance-definition-benefits-and-types/](https://paytm.com/blog/insurance/what-is-insurance-definition-benefits-and-types/)
[3](#_footnoteref_3)
. Allstate.com: What Perils Are Typically Covered By A Homeowners Insurance Policy?
[4](#_footnoteref_4)
. [https://en.wikipedia.org/wiki/Law\_of\_large\_numbers](https://en.wikipedia.org/wiki/Law_of_large_numbers)
[5](#_footnoteref_5)
. [http://www.npr.org/sections/money/2010/03/warren\_buffett\_explains\_the\_ge.html](http://www.npr.org/sections/money/2010/03/warren_buffett_explains_the_ge.html)
[6](#_footnoteref_6)
. $100 for covering the risk against $120 premium ⇒ 100/120 loss ratio = 83%
[7](#_footnoteref_7)
. The downside of this is the fact that inefficiencies tend to hide in the organization. The bigger the organization, the fewer the people doing real work (people at the “rim” of the organization) and the more people are needed in the center to organize the people at the rim (the “management”). Furthermore, to limit internal inefficiencies, companies need a plethora of control mechanisms (that’s the old style) or complicated incentive systems (that’s the more modern way)
[8](#_footnoteref_8)
. [https://assets.kpmg.com/content/dam/kpmg/au/pdf/2016/general-insurance-industry-review-2016.pdf](https://assets.kpmg.com/content/dam/kpmg/au/pdf/2016/general-insurance-industry-review-2016.pdf)
[9](#_footnoteref_9)
. There is a fourth element - reinsurance. The purpose of reinsurance is to reduce the cost of risk diversification by categorizing and securitizing different risks. Reinsurance and “wholesale” risk transfer enabled by reinsurance adds another layer of complexity, and therefore we won’t discuss reinsurance in this paper.
[10](#_footnoteref_10)
. Some blockchains, like Ethereum (which we use), enable programs (called “smart contracts”) that are uncensorable, immutable, and permanent. These smart contracts can interact with each other to perform a wide variety of actions, including financial and escrow transactions. This makes possible direct and transparent interactions between two parties who may be and may remain anonymous, that previously required a third-party intermediary to be effective. The term was originally coined by Nick Szabo, but in a slightly different meaning. Note: The above definition was thankfully supplied by Ron Bernstein, who was not successful in finding the original author - please contact us if you are the author.
[11](#_footnoteref_11)
. Network effect is described as the effect that one user of a good or service has on the value of that product to other people. The classical example is the telephone: the more people use it, the more valuable the telephone is for all.
[12](#_footnoteref_12)
. We use the term “company” here for easier reading. Of course, in DeFi/blockchain applications, a “company” can also be a DAO or a simple blockchain address (EOA)!
[13](#_footnoteref_13)
. [https://en.wikipedia.org/wiki/Elinor\_Ostrom](https://en.wikipedia.org/wiki/Elinor_Ostrom)
; see also [https://www.onthecommons.org/magazine/elinor-ostroms-8-principles-managing-commmons](https://www.onthecommons.org/magazine/elinor-ostroms-8-principles-managing-commmons)
[14](#_footnoteref_14)
. [https://blog.etherisc.com/basics-about-the-gif-framework-68127be1ce2a](https://blog.etherisc.com/basics-about-the-gif-framework-68127be1ce2a)
---
# Remerciements
- Etherisc Docs
Remerciements
================
Les idées contenues dans ce document résultent de nombreuses discussions, en ligne et en personne, avec de brillants esprits du monde crypto-économique. L’équipe Etherisc tient à remercier tout particulièrement les personnes suivantes, qui ont apporté une valeur ajoutée considérable au projet : Ron Bernstein, Jake Brukhman, Alexander Bulkin, Alex Felix, William Mougayar, Micah Zoltu, à l’équipe actuelle, composée de Matthias Zimmermann, Jan Stockhausen, Michiel Berende, Hui Lin Chiew, Sebastian Schlitter, Peter Koch, Koenraad de Jonghe, Damian Groß, Felizitas Mussenbrock-Strauß, Lydia Mussenbrock et enfin tous les membres de notre canal telegram et de notre serveur discord qui nous ont fait part de leurs commentaires et critiques et nous ont encouragés à poursuivre notre voie.
[](#1_a_propos)
1 A propos
==========================
[](#histoire)
Histoire
----------------------
À la suite du hackathon de nov/déc 2016, l’équipe d’Etherisc a rédigé un livre blanc, qui a été rendu public dans sa version 0.3. Le but de ce hackathon était d’esquisser le cœur d’un marché d’assurance basé sur la blockchain.
Deux ans plus tard, nous avons publié la version 1.01 du livre blanc à l’occasion de la vente de tokens DIP ayant eût lieu du 23 juin au 25 juillet 2018. Le livre blanc de 2018 présentait les principales caractéristiques de l’écosystème, ainsi que quelques aspects importants du DIP token. Même s’il apparaissait que le token allait principalement servir au staking, beaucoup de détails devaient encore être réglés.
Nous n’avions également qu’une idée approximative de ce à quoi ressemblerait la structure de l’assurance. Immédiatement après la vente de token, nous avions commencé à mettre en œuvre la structure qui fût publié sous le nom de "GIF" (Generic Insurance Framework) en 2019.
[](#the_elevator_pitch)
The elevator pitch
------------------------------------------
Quelques grandes sociétés dominent le secteur de l’assurance. Ce secteur (pesant plusieurs milliards de dollars) s’est développé au point de devenir indispensable à notre économie moderne. Il peut pourtant se montrer inefficace, opaque, coûteux tout en offrant une expérience client de basse qualité. Affirmer que le secteur de l’assurance est ennuyeux et peu fiable est un lieu commun.
Lorsque les clients ont besoin d’aide, ils peuvent se battre en vain pour être remboursés par des sociétés dont les profits dépendent trop souvent du non-remboursement.
_Etherisc a construit une plateforme d’applications d’assurance décentralisée qui peut être utilisée par quiconque souhaitant proposer une assurance : grandes et petites entreprises, groupes à but non lucratif ou encore startups insurtech._
Dès le départ, afin d’encourager l’innovation dans le secteur des assurances, Etherisc a rendu son code source public. L’objectif d’Etherisc est de soutenir un écosystème en pleine croissance détenu et géré par la communauté d’utilisateurs.
Nous voulons créer des produits d’assurance qui soient transparents, équitables et accessibles tant pour les clients que pour les investisseurs.
Etherisc peut ainsi devenir la plateforme d’assurance la plus utilisée au monde, offrant une couverture à des millions de clients mal desservis.
La plateforme Etherisc est construite autour d’une architecture technique, basée sur la blockchain, appelée "GIF". GIF est un acronyme qui signifie "Generic Insurance Framework". Il se compose de smart contracts open-source qui mettent en œuvre des fonctions génériques de produits d’assurance et de cycle de vie des polices. Ainsi, le GIF développe un large panel d’assurances. Le GIF fonctionne sur une blockchain et peut fonctionner avec plusieurs blockchains et plusieurs occupants.
_Le GIF est conçu pour accueillir des produits d’assurance paramétrique. L’assurance paramétrique couvre des sinistres prédéfinis dès qu’ils se produisent, avec des paiements prédéfinis, plutôt que de compenser les dommages réels. Des événements tels que les retards de vols, les sécheresses, les fortes pluies ou les dommages causés par les ouragans sont couverts._
Dans l’assurance paramétrique, les sinistres (les risques) sont définis par des fonctions d’indices ou de paramètres sous-jacents qui répondent aux critères définis par le produit d’assurance.
Le GIF est open source, ce qui signifie que n’importe qui peut déployer sa propre instance GIF, modifier le code, etc. Cependant, nous pensons qu’une plateforme florissante a besoin de plus que quelques lignes de code.
Par conséquent, toute instance GIF pourrait éventuellement être enregistrée dans un registre mondial qui est maintenu par une DAO, dans laquelle toutes les parties prenantes de la platform participeraient à la gouvernance. Les instances GIF enregistrées devraient se conformer à un ensemble de règles garantissant que les clients se sentent en sécurité lorsqu’ils interagissent avec une instance GIF enregistrée. Pour ce faire, des badges et des certificats seraient attribués aux instances GIF conformes.
Dans ce système, le natif DIP token (Decentralized Insurance Protocol) joue un rôle central. Chaque participant et chaque partie prenante est tenu de miser un certain nombre de DIP token. Par conséquent, le DIP token est un token utilitaire, dont le staking est l’utilité centrale. Le staking est nécessaire à la fois pour déployer des produits, des oracles et des risk pools, mais aussi pour investir dans ces risk pools. Le staking accordera également des droits de vote dans le modèle de gouvernance.
[](#chapitres)
Chapitres
------------------------
Ce livre blanc est une tentative de structuration de l’image globale de l’assurance décentralisée en fonction des nouvelles perspectives. Le document est structuré en 4 chapitres principaux :
**Dans le chapitre deux**, nous exposons des données fondamentales et des inconvénients de l’assurance traditionnelle. Nous soulignons les avantages de la blockchain et du modèle décentralisé dans l’assurance et expliquons l’interaction entre clients, utilisateurs et entreprises.
**Le chapitre trois** présente la vision d’Etherisc de l’assurance, des polices et de l’assurance paramétrique. Nous définissons les trois piliers de l’écosystème Etherisc et abordons l’aspect technique du GIF (Generic Insurance Framework). Nous définissons le cycle de vie générique des fonctions GIF. A la fin du chapitre, nous présentons le GIF Monitor.
**Le chapitre quatre** présente le DIP token et la manière dont il est utilisé dans le staking d’Etherisc. Nous décrivons notre modèle de staking, l’interaction des différentes risk pools correspondants et les fonctions des différents token. Le chapitre se conclut sur le sujet des récompenses en crédits et des pertes de paiement.
**Le chapitre cinq** traite de l’EGM (Etherisc Governance Model). Le respect, le partenariat, la responsabilité, la confiance et les biens publics sont nos cinq valeurs cardinales. Nous traiterons ensuite de la structure de l’EGM, des participants et de leurs rôles. Des détails sur les sujets du global staking pool et de la politique monétaire complètent ensuite le livre blanc avec l’annexe.
**Le sixième** et dernier chapitre contient une liste de toutes les abréviations et définitions des termes les plus importants.
[](#2_analyse_des_paradigmes_de_base_de_lassurance)
2 Analyse des paradigmes de base de l’assurance
===================================================================================================
[](#2_1_aperçu)
2.1 Aperçu
--------------------------
Pour comprendre l’approche, les stratégies et les objectifs de (cette) assurance, il est important de se pencher sur une définition générale de ce qu’est et de ce que fait l’assurance :
_"L’assurance est un moyen de protection contre les pertes financières dans lequel, en échange d’un droit appelé "prime", une partie accepte de garantir à une autre partie une indemnisation en cas de perte, de dommage ou de préjudice certain. C’est une forme de gestion des risques, principalement utilisée pour se couvrir contre le risque d’une perte éventuelle ou incertaine."\[[1](#_footnotedef_1 "View footnote.")\
\]_
Il peut s’agir d’un contrat sous forme d’une police de protection financière. L’assuré est le titulaire de la police, tandis que l’assureur est la compagnie d’assurance.\[[2](#_footnotedef_2 "View footnote.")\
\]
Après avoir analysé les principes de base de l’assurance, comme la définition, et avoir développé un système de token sur la base de ces principes, nous pouvons maintenant analyser l’assurance et décomposer les coûts et les flux de capitaux en trois éléments :
**Valeur attendue du risque**
Qui est simplement la redistribution du capital en fonction des risques entre les participants.
**Coûts en capital pour les risques extrêmes**
Comme son nom l’indique, le capital des risk pools est exposé à un risque de perte et doit être conservé dans la pool de risques pendant une certaine période. Les fournisseurs de capital sont indemnisés pour ce risque. Cette compensation est calculée en fonction de la période de limitation et du risque assuré.
**Coûts de transaction**
Frais d’administration des polices d’assurance, par exemple, frais de gaz des réservations sur la blockchain, frais de réservation en cas de paiement en monnaie FIAT, frais pour les oracles, etc.
Nous soutenons que les compagnies d’assurance traditionnelles dominent ces blocs de construction et régissent ainsi le marché de l’assurance. Le GIF et la technologie blockchain sous-jacente offrent la possibilité de remplacer les processus ancrés des compagnies d’assurance traditionnelles par des structures décentralisées allégées utilisant des protocoles allégés standardisés et automatisés. Les token cartographient ainsi les flux de capitaux et de revenus.
La conclusion de cette analyse est que nous avons besoin de deux types de token. Le premier - le "DIP Token" - soutient la coordination et l’incitation économique des acteurs dans un système d’assurance décentralisé.
Le second type de token représente les risques - il ne s’agit pas d’un token unique mais d’une classe de token similaires, un pour chaque pool de risques, que nous appelons "token de pool de risques".
Dans un environnement distribué où de nombreux participants construisent des produits en collaboration, le protocol token sert de colle, de collatéral et de représentation de la valeur matérielle et immatérielle du réseau, tout comme l’Ether sert à garantir la stabilité de la blockchain Ethereum.
Au chapitre 4.1, nous détaillons le token du protocole DIP. Le chapitre 6 présente un exemple concret de l’utilisation du token dans un contexte d’assurance.
[](#2_2_principes_de_lassurance)
2.2 Principes de l’assurance
-------------------------------------------------------------
Nous allons expliquer le principe de l’assurance à l’aide d’un exemple. L’exemple est bien sûr simplifié et a pour seul but d’expliquer le principe.
Considérons l’assurance des propriétaires. Pour les clients, l’assurance concerne les probabilités de pertes, il serait donc intéressant de voir quelle est la probabilité d’un dommage. Une assurance habitation couvre généralement un certain nombre de dommages, notamment le feu, les catastrophes naturelles, l’eau et même la chute d’objets.\[[3](#_footnotedef_3 "View footnote.")\
\]
Mais il est difficile d’obtenir des statistiques réelles, car les compagnies d’assurance ne sont pas très transparentes sur ces données.footnote:\[A quick market survey in Germany shows that you get a homeowners insurance for considerably less than 0.1% of the value. For simplicity, we’ll assume that the premium is 0.1% plain and we don’t take insurance taxes etc. into account.\
\
From the relation premium/value, we can easily estimate an upper bound for the probability. One of the most fundamental principles of insurance is that the expected losses should not surpass the collected premiums (“Risk loading” - cf. [http://www.wiley.com/legacy/wileychi/eoas/pdfs/TAP027-.pdf](http://www.wiley.com/legacy/wileychi/eoas/pdfs/TAP027-.pdf)\
). The expected losses are - simplified - number of policies multiplied with the probability of loss multiplied with the loss (which is equal to the value), and collected premiums are number of policies multiplied with premium per policy. It follows that the probability can be approximated by premium/value, which is lower than 0.1% in our market test.\]
Nous supposerons que, concernant notre exemple, la probabilité de sinistre est de 0,1 %.
Dans notre exemple fictif, supposons que l’assurance n’ait pas encore été inventée. Dans ce monde fictif, Alice possède une maison. La maison vaut 100 000 dollars. La probabilité d’une catastrophe complète est de 0,1 % par an (soit un événement dévastateur sur 1 000 ans). Alice veut s’assurer qu’elle a accès à suffisamment de fonds pour acquérir une nouvelle maison en cas de catastrophe. Elle décide donc d’obtenir un prêt de 100 000 dollars et doit payer le remboursement (également appelé principal) et le taux d’intérêt.
En outre, elle paie un taux d’intérêt d’environ 1 %, ce qui représente un coût annuel de 1 100 $ (prêt de 100 000 $ \* taux d’intérêt de 1 % plus remboursement annuel de 100 $ = 1 100 $).
Nous allons maintenant voir comment la mise en commun des risques dans le frameworkd’un régime d’assurance réduit considérablement ces coûts.
### [](#2_2_1_partager_la_valeur_attendue_du_risque)
2.2.1 Partager la valeur attendue du risque
Supposons que 100.000 propriétaires de maison se regroupent dans une pool. Là encore, chacun paie une part de 100 $ ; ce montant est maintenant appelé "prime". Ils perçoivent un total de 10 000 000 $ en primes. Mais il y a maintenant une différence pour Alice, qui ne s’occupe que d’elle-même : en raison de la loi des grands nombres\[[4](#_footnotedef_4 "View footnote.")\
\], avec une très forte probabilité, il n’y aura qu’une centaine d’incendies, causant un dommage d’environ 10 000 000 $ ! Et comme la somme de toutes les primes est également de 10 000 000 $, l’ensemble des dommages peut être payé avec les primes collectées, sans que chaque propriétaire de maison ait besoin de contracter un prêt. (Étant donné que les primes sont collectées au début de l’année et que toutes les maisons dont l’incendie est "prévu" ne brûlent pas toutes au début de l’année, mais sont plus ou moins réparties de manière égale sur l’année ou les années, il existe ce que l’on appelle un "flottant\[[5](#_footnotedef_5 "View footnote.")\
\]" de liquidité qui peut également générer un revenu important. Pour des raisons de simplicité, nous ne nous concentrerons pas sur cet effet dans cet article.
Ainsi, les coûts pour chaque propriétaire de maison individuelle sont maintenant réduits de 1 100 $ à 100 $ !
Cette différence demande une explication économique. Examinons-la de plus près. Tout d’abord, si tous les propriétaires de maison suivaient l’exemple d’Alice, ils auraient besoin d’un prêt énorme, dont seule une infime partie de 0,1 % serait nécessaire en moyenne. Il est clair que fournir des liquidités inutilisées est coûteux.
_La mutualisation des risques dans l’assurance optimise l’utilisation du capital, et les participants bénéficient d’une réduction des coûts, tout en évitant les difficultés conséquentes à l’obtention d’un prêt sans garantie !_
Deuxièmement, si chacun ne se préoccupe que de lui-même, seule une infime partie des participants est frappée par la catastrophe et a la charge de rembourser réellement son prêt. Les autres peuvent rembourser sans perte, tant qu’ils n’ont pas besoin de protection. Dans une assurance collective, nous bénéficions de la solidarité : avec les primes, chacun paie pour les dommages des autres.
En résumé, une pool de risques offre trois avantages aux participants :
1. Construire une grande réserve de liquidités.
2. Accès garanti à ces liquidités en cas de sinistre.
3. Subventionnement mutuel des dommages.
Une telle pool peut être conçue dans le seul but de bénéficier à ses participants et de ne réaliser aucun "profit". Si la pool génère des bénéfices, ceux-ci pourraient être redistribués aux participants, ce qui aurait pour effet de réduire à nouveau les primes à un niveau où aucun bénéfice n’est généré. Une telle assurance aurait un ratio de pertes de 100 %, car toutes les primes sont utilisées pour payer les pertes.
Il s’agit de l’effet de base du transfert de risques. Veuillez noter que l’effet augmente avec la taille de la pool.
Mais ce n’est pas tout.
### [](#2_2_2_partager_les_risques_résiduels)
2.2.2 Partager les risques résiduels
Selon les années, le nombre d’incendies varie. Pour tenir compte de ces variations, l’ensemble de la pool doit réunir un certain montant, par exemple 10 millions de dollars, pour couvrir le cas peu probable d’une explosion du nombre d’incendies au cours d’une année donnée. Supposons même que le taux d’intérêt pour ce capital soit particulièrement élevé, par exemple 20%. Le coût total de ce capital sera de 2 millions de dollars. Le taux d’intérêt pour le capital est une fonction du risque et du taux d’intérêt sans risque sur le marché des capitaux ; dans un marché efficace, le taux d’intérêt compensera le risque plus élevé par rapport à un investissement sans risque et contiendra également un bénéfice équitable. Grossièrement, c’est là que sont générés les bénéfices pour l’apport de capital dans une structure d’assurance.
Les coûts globaux de 2 millions de dollars seraient alors répartis entre tous les propriétaires de maisons, ce qui entraînerait un coût supplémentaire de 20 dollars par propriétaire de maison et par an ajouté à la prime.
Désormais, une protection contre les "risques résiduels" ou "black swan events" est également assurée, à un coût de 20 dollars par propriétaire de maison. Là encore, l’effet de diversification des risques augmente avec la taille de la pool.
Globalement, les participants paient maintenant 120 dollars par an pour leur assurance habitation. Le rapport sinistres-primes est alors réduit à 83 % en raison des coûts liés à la protection des risques extrêmes.\[[6](#_footnotedef_6 "View footnote.")\
\]
### [](#2_2_3_partage_des_coûts_de_transaction)
2.2.3 Partage des coûts de transaction
Pour inclure 100 000 personnes dans une pool, une structure professionnelle est nécessaire. Sinon, chaque participant devrait se coordonner, ce qui serait tout simplement impossible. Le fonctionnement de cette structure professionnelle ajoute des coûts de transaction à la prime. Il s’agit en fait de la raison d’être des compagnies d’assurance :
_Elles permettent de réduire les coûts de transaction pour les participants à la pool, en créant une économie d’échelle et en coordonnant un très grand nombre de participants et d’employés.\[[7](#_footnotedef_7 "View footnote.")\
\]_
L’effet est considérable et permet la forme moderne d’assurance avec d’énormes quantités de clients et une capitalisation qui peut même couvrir des catastrophes mondiales comme les ouragans ou les tremblements de terre. Cependant, les coûts de transaction restants sont encore considérables : une étude récente de KPMG montre que l’impact sur le taux de sinistres est d’environ 66% en moyenne.
### [](#2_2_4_asymétrie_de_linformation)
2.2.4 Asymétrie de l’information
La réduction des coûts de transaction s’accompagne d’une asymétrie de l’information, qui conduit à une nouvelle augmentation des coûts et à des profits incroyables pour les grandes compagnies d’assurance.
_La collecte illimitée de données sur les clients et l’exploitation exclusive de ces données sont une conséquence de cette relation déséquilibrée._
Elle crée un "avantage concurrentiel déloyal" pour les entreprises existantes : les entreprises disposant d’importantes bases de données peuvent proposer de meilleurs produits, et donc optimiser encore davantage leurs bases de données. L’un des objectifs fondamentaux d’une plateforme d’assurance décentralisée est de perturber ce système, en rendant aux clients la propriété de leurs données.\[[8](#_footnotedef_8 "View footnote.")\
\]
### [](#2_2_5_résumé)
2.2.5 Résumé
Les trois éléments décrits précédemment, à savoir la mutualisation des risques, le transfert des risques et une administration efficace, sont nécessaires. Il ne peut y avoir d’assurance sans chacun de ces éléments.
Pour les besoins de ce papier, je les appellerai:
1. valeur attendue du risque
2. coûts du capital pour les risques résiduels
3. coûts de transaction
Comme vu précédemment, une communauté peut ne pas souhaiter générer de profit à partir du premier élément. Le deuxième élément donne lieu à des frais de risque pour le capital attribué dépendant de la structure du risque particulier : Ils sont généralement plus faibles si les risques sont individuels et non corrélés ; généralement plus élevés si les risques sont groupés ou corrélés. Le troisième dépend de la complexité du processus. Un "produit" d’assurance simple et hautement standardisé présente une complexité de transaction moindre qu’un produit plus compliqué et non standardisé. Cela se traduira par des coûts de transaction plus faibles.
Ces trois éléments sont totalement indépendants de la technologie, de l’environnement économique ou des monnaies sous-jacentes. Ils sont les éléments constitutifs basiques de tout système de partage des risques.\[[9](#_footnotedef_9 "View footnote.")\
\]
L’asymétrie de l’information, inhérente aux systèmes d’assurance traditionnels, constitue un autre aspect non souhaitable.
La répartition de la valeur attendue (élément 1) et des coûts en capital pour les risques extrêmes entre les participants (élément 2) est inévitable et n’est pas spécifique à une solution blockchain. Par conséquent, concentrons-nous sur le troisième élément.
_En \_\_utilisant la technologie blockchain, un nombre arbitraire de participants peut se coordonner sur une tâche économique sans la structure juridique d’une entreprise, avec des gains d’efficacité significatifs et une réduction des coûts de transaction._
Les coûts de transaction sont également dû à un autre élément : les réglementations, qui sont jugées nécessaires pour protéger les clients dans un contexte de conflits d’intérêts. Les réglementations constituent une barrière à l’entrée très efficace pour les "concurrents". Alors que les compagnies d’assurance se plaignent souvent du poids des réglementations, elles n’ont en réalité pas grand intérêt à réduire ces charges, car elles découragent les nouveaux concurrents d’entrer sur le marché.
[](#2_3la_blockchain_aide_à_résoudre_les_problèmes_de_lassurance_traditionnelle)
2.3 La blockchain aide à résoudre les problèmes de l’assurance traditionnelle
--------------------------------------------------------------------------------------------------------------------------------------------------------------
Bien que le secteur actuel de l’assurance ait évolué au fil des siècles et qu’il soit optimisé à bien des égards, nous avons constaté qu’il présente de graves lacunes au détriment des clients. Nous décrirons certaines propriétés d’un système alternatif, qui pallie à ces défauts.
Tout d’abord, un système alternatif devrait bien sûr offrir les ingrédients de base de tout système d’assurance : couverture des pertes attendues, couverture des risques extrêmes et couverture des coûts de transaction nécessaires. Il est évident que nous devons apporter de la capitalisation à un tel système et que nous avons besoin d’un système pour réduire les coûts de transaction au minimum. Les coûts de transaction ne peuvent pas être complètement éliminés. Mais les marchés ouverts se sont avérés être une solution à ces défis, et par conséquent, nous proposons une approche basée sur le marché avec deux composantes :
* un marché ouvert pour la capitalisation des risques
* un marché ouvert pour les services liés à l’assurance
C’est là que la blockchain entre en jeu :
\_Une solution décentralisée sur la blockchain met en œuvre ces marchés ouverts d’une manière qui résiste à la collusion et ne présente aucun point de défaillance unique. \_
Nous pouvons observer l’émergence de nombreuses places de marché de ce type pour différents domaines, comme le calcul, le stockage de fichiers, l’échange d’actifs ; et l’assurance n’est qu’un autre domaine à cet égard.
Plus précisément, la blockchain permet de résoudre certains des principaux problèmes qui font grimper les coûts dans les compagnies d’assurance traditionnelles :
1. Coûts de coordination ("de gestion").
2. Conflit d’intérêts entre les clients et l’entreprise.
3. Asymétrie d’information entre les clients et l’entreprise.
4. Accès restreint aux bénéfices des risk pools
5. Délai de commercialisation long
6. Accès limité à certains marchés de capitaux (par ex. crypto)
**Avantage 1 :**
**Moins cher car les coûts de coordination sont faibles.** Dans les entreprises traditionnelles, vous avez deux types d’employés : le premier groupe effectue le travail réel, le second groupe coordonne l’ensemble du système. Plus une entreprise grandit, plus l’énergie circule dans le second groupe (comme dans un cercle, le premier groupe forme le bord du cercle, le second la surface ; plus le cercle est grand, moins les processus sont efficaces, et plus l’énergie circule dans la coordination des coordinateurs). La blockchain permet de réduire ces coûts de coordination. Au lieu d’une troupe de gestionnaires, les "smart contracts"\[[10](#_footnotedef_10 "View footnote.")\
\] agissent comme des plaques tournantes entre les agents au bord du système, et éliminent ainsi la plupart des coûts et de l’inefficacité de la gestion.
**Avantage 2 :**
**Plus transparent / indépendant / digne de confiance**. Dans une compagnie d’assurance traditionnelle, la compagnie "possède" l’ensemble du processus, y compris les tâches qui ont tendance à soulever des conflits d’intérêts entre le client et la compagnie. La gestion des sinistres en est un parfait exemple : Le gestionnaire de sinistres a pour objectif explicite de minimiser les paiements pour les dommages, car il est un employé du fournisseur d’assurance ! Bien sûr, il existe une guilde d’évaluateurs et d’experts "indépendants", mais qui les paie ?
La blockchain résout ce conflit d’intérêts en permettant l’intervention d’experts véritablement indépendants (qui peuvent par exemple être classés publiquement en fonction de leur réputation d’efficacité ou d’équité), et dont le travail est indépendant du fournisseur d’assurance, ainsi que transparent et vérifiable par l’ensemble de la communauté.
Il en va de même dans un autre domaine, où le conflit d’intérêts n’est (intentionnellement) pas évident ; considérons la conception de produits. Une compagnie d’assurance a un avantage considérable sur ses clients, car elle peut concevoir des produits d’une manière qui, peut-être injustement, maximise les revenus (ventes) et minimise les paiements (dépenses).
Par exemple, si un client attend le remboursement d’une police d’assurance qu’il a souscrite pour un "événement" particulier, mais que la compagnie d’assurance ne le lui verse pas parce qu’elle maintient que la police souscrite ne couvre pas réellement cet "événement", l’expérience du client est gravement compromise et la confiance entre les consommateurs et les compagnies d’assurance est érodée.
**Avantage 3 :**
**Plus transparent / équitable grâce aux smart contracts de la blockchain**. Les compagnies d’assurance traditionnelles collectent des données et des informations dans d’énormes bases de données privées, et les données ne sont rarement partagées. Cette asymétrie d’information est une source d’inefficacité et à l’origine de coûts de transaction élevés.
L’expérience des entreprises dans l’analyse de ces données est considérée comme l’un des principaux facteurs de différenciation sur le marché. Les décisions fondées sur ces données ne sont pas transparentes et difficiles à contester en raison du manque de visibilité des évaluations.
Dans un environnement basé sur la blockchain, cependant, toutes les données fondamentales et les décisions basées sur ces données sont transparentes et validées objectivement.
**Avantage 4 :**
**Accès démocratisé**. Les risk pools des compagnies d’assurance traditionnelles sont des instruments d’investissement intéressants. Cependant, ils ne sont pas accessibles au public et les bénéfices générés ne profitent qu’à un petit groupe d’investisseurs.
_La blockchain démocratise l’accès aux risk pools en symbolisant les risques avec les "risk pool tokens,"_
La blockchain démocratise l’accès aux risk pools en symbolisant les risques avec les "risk pool tokens,".
**Avantage 5 :**
**Flexibilité et évolutivité.** La composabilité est la capacité générale des components d’un système à être recombinés en structures plus grandes et à ce que la sortie de l’un soit l’entrée d’un autre. En termes simples, le meilleur exemple est le Lego, où chaque pièce peut être connectée à toutes les autres. Dans le domaine de la cryptographie, la composabilité est la capacité des applications décentralisées (dApps) et des DAO à se cloner et à s’intégrer efficacement les unes aux autres (composabilité syntaxique), et la capacité des components logiciels tels que les token et les messages à être interopérables entre eux (composabilité morphologique).
**Avantage 6 :**
**La blockchain permet une gestion plus efficace des garanties**. La création et la numérisation de token de garantie comme les stablecoins ou des actifs similaires et de nouvelles primitives financières comme le staking facilitent l’émergence de nouveaux marchés et de nouvelles possibilités.
[](#2_4pourquoi_lassurance_peut_elle_bénéficier_de_la_décentralisation)
2.4 Pourquoi l’assurance peut-elle bénéficier de la décentralisation
--------------------------------------------------------------------------------------------------------------------------------------------
### [](#2_4_1_pourquoi_lassurance_est_elle_un_candidat_à_la_décentralisation)
2.4.1 Pourquoi l’assurance est-elle un candidat à la décentralisation ?
En tant qu’industrie de plusieurs milliards de dollars dominée par d’énormes sociétés, l’assurance est souvent confrontée à des obstacles tels que des réglementations strictes et des déséquilibres entre les incitations des entreprises et celles des consommateurs, qui font que le monde de l’assurance est souvent inefficace et coûteux. L’objectif ultime est d’éviter que les clients aient à se battre pour être remboursés par des compagnies dont les profits dépendent souvent de l’absence voulue de paiement.
Etherisc construit une plateforme pour des applications d’assurance décentralisées. La plateforme peut être utilisée par des entreprises, grandes et petites, des groupes à but non lucratif et des startups insurtech pour fournir de meilleurs produits et services. Nous souhaitons utiliser la technologie blockchain pour rendre l’assurance plus réactive, moins chère et plus transparente et ainsi démocratiser l’accès à l’investissement dans les produits d’assurance.
_La blockchain peut fournir les moyens de supprimer les intermédiaires du marché grâce à une plateforme pair à pair, permettant ainsi à l’assurance de revenir à ses racines de filet de sécurité sociétal._
Nous incitons les nouveaux groupes à construire leurs propres risk pools et services d’assurance personnalisé sur la plateforme Etherisc. Le GIF permet de développer des polices d’assurance conformes et adaptées à l’économie émergente de la blockchain. Pour offrir une alternative aux systèmes d’assurance monolithiques traditionnels, nous pouvons identifier certaines nécessités et conséquences de la mise en œuvre d’un protocole d’assurance décentralisé.
### [](#2_4_2_propriétés_de_lassurance_décentralisée)
2.4.2 Propriétés de l’assurance décentralisée
1. L’éventail des assurances est immense et bien trop complexe pour être couvert par une seule application. Par conséquent, nous avons besoin d’un protocole et pas seulement d’une application (décentralisée). Certains outils sont nécessaires pour inciter les participants à l’utiliser. La promotion des “network effects"\[[11](#_footnotedef_11 "View footnote.")\
\] est un outil qui peut conduire à une base d’utilisateurs durable et croissante. Une police peut couvrir un produit particulier, mais une seule police ne générera pas les effets de réseau pour créer plusieurs grandes risk pools similaires nécessaires afin de tirer parti de la "loi des grands nombres."
2. Un protocole d’assurance décentralisé peut remplacer partiellement ou totalement le modèle économique traditionnel de l’assurance. Il y parvient grâce à l’atomisation des processus, à des procédures et des smart contracts autonomes et automatisés, à un ensemble de règles d’interaction entre les parties prenantes et à des smart contracts. Parallèlement,, un protocole permet une extension et une interprétation flexibles des règles de base.
3. Le développement et le fonctionnement d’un protocole nécessitent un financement. Même s’il est possible de réduire considérablement les coûts de coordination, les coûts de lancement du système persistent - par exemple, l’acquisition de licences, le développement de smart contracts, les audits, ainsi que les coûts pour les agents en "périphérie" du système que nous ne pouvons pas éliminer complètement. Nous devons donc trouver un moyen de collecter ces coûts auprès des clients finaux et de les répartir entre ces agents.
4. Nous avons également besoin d’un moyen de calculer et de répartir entre les clients la valeur attendue du risque et les coûts en capital pour couvrir les risques extrêmes.
[](#2_5_protocole)
2.5 Protocole
--------------------------------
### [](#2_5_1_propriétaire_du_protocole_gouvernance)
2.5.1 Propriétaire du protocole, gouvernance
En tant que structure ouverte, le protocole est un bien commun, il peut être utilisé et mis en œuvre par quiconque le souhaite. Nous veillerons à ce que les barrières à l’entrée soient aussi faibles que possible. Cependant, pour certaines parties du protocole, une certification sera nécessaire, afin de refléter les obligations et restrictions réglementaires. Nous avons créé une fondation basée en Suisse servant d’organe juridique. Cette fondation détient officiellement les droits de propriété intellectuelle du protocole et garantit que le protocole puisse être utilisé librement. Nous avons établi un processus d’amélioration continue du protocole, piloté par la communauté, similaire au processus EIP pour la plateforme Ethereum.
Le modèle de gouvernance Etherisc (EGM), son résumé et ses valeurs fondamentales, ainsi que d’autres sous-thèmes, seront développés au chapitre 5.
### [](#2_5_2_schéma_des_dynamiques_de_travail_du_protocole)
2.5.2 Schéma des dynamiques de travail du protocole
* **Demande d’adhésion à une police**
Processus d’offre d’un produit et de demande d’adhésion
* **Souscription**
Processus d’acceptation d’une politique
* **Collecte des primes**
Processus de paiement, paiements ponctuels et réguliers
* **Soumission des demandes de remboursement**
Processus de soumission d’une demande de remboursement, via oracle ou manuellement
* **Évaluation des sinistres**
Processus d’évaluation d’un sinistre, via un oracle ou manuellement. Un processus de vérification des sinistres permet au système de déterminer quelles polices sont légitimement réclamées et d’effectuer les paiements convenus aux demandeurs. Dans le cas de l’assurance paramétrique, ce processus fait référence à des flux de données sur les événements assurables et est (entièrement) automatisé.
* Gestion de l’identité et confidentialité Processus de KYC et AML, dans le respect de la vie privée. Cela peut impliquer des blockchains privées ou le stockage de données hors off-chain.
* **Admission / Certification**
Admission des participants à offrir des produits et à exécuter certaines parties du protocole
* **Gestion des actifs**
Au fur et à mesure que les fonds affluent, nous devons utiliser de manière responsable les fonds qui ne sont pas immédiatement nécessaires
[](#2_6communauté_de_clients_dutilisateurs_et_dentreprises)
2.6 Communauté de clients, d’utilisateurs et d’entreprises
----------------------------------------------------------------------------------------------------------------------
Le succès de la plateforme dépendra d’une communauté active d’utilisateurs et d’entreprises. Le modèle du token représente et maintient cette communauté, qui joue un rôle central dans la gestion des mesures incitatives. Grâce aux token, les clients peuvent "posséder" leur assurance. Ce modèle communautaire facilite le développement des futures mutuelles et des modèles d’assurance de pair à pair.
\_Une communauté ne peut pas être construite de l’extérieur, elle doit se développer de l’intérieur. \_
Cependant, l’expérience montre qu’il existe certains critères de réussite pour les communautés. Le célèbre pionnier de l’open source [Pieter Hintjens](http://hintjens.wikidot.com/blog:10)
, en a exposé quelques-uns que nous considérons comme utiles pour une discussion approfondie :
* **Qualité de la mission**
Une communauté ne peut se développer qu’en poursuivant un objectif valable. Ce but doit être supra-individuel.
* **Liberté d’accès**
La communauté ne doit pas avoir de barrières ou de murs, elle doit accueillir les personnes de bonne volonté et encourager la participation. **\*Des règles claires**
Si des règles sont nécessaires, elles doivent être soigneusement rédigées et évidentes.
* **Une autorité forte et neutre**
Pour résoudre les conflits, une autorité forte mais neutre doit être mise en place. Un mécanisme de gouvernance peut être intégré à cette autorité.
* **La propriété proportionnelle**
"Vous possédez ce que vous fabriquez"
* **Des espaces infinis**
Un grand projet unique avec de nombreux propriétaires ne se développe pas aussi bien qu’une quantité de nombreux petits projets, chacun avec un ou deux propriétaires. Les communautés se développent mieux lorsque les membres superposent projet sur projet sans limite.
* **Mesure du succès**
Au sein de la communauté, votre voix est aussi forte que le nombre de personnes qui utilisent le projet que vous "possédez".
* **Outils et processus**
De meilleurs outils signifient une communauté plus rapide et plus efficace.
* **Liberté d’organisation**
Les participants de la communauté identifient les problèmes, allouent les ressources et contrôlent le résultat, sans gestion descendante.
* **Transparence**
Le secret favorise l’émergence de l’incompétence, la transparence favorise la compétence. Plus le travail de l’organisation est public, mieux c’est.
* **Absence de structures**
"Chacun est propriétaire de ce qu’il fabrique" et soyez prêt à changer de domicile en cas de besoin.
* **Participation évolutive**
Il ne faut imposer aucune barrière à n’importe quel moment, mais il faut que ce soit de plus en plus difficile. Cela donne à la communauté l’impression d’être un jeu massivement multijoueur, où il y a toujours quelqu’un de meilleur que vous, et où vous n’avez qu’à essayer de le rattraper.
[](#3_gif_le_generic_insurance_framework)
3 GIF - Le Generic Insurance Framework
================================================================================
Le GIF est constitué de blocs de construction intégrant la chaîne de valeur complète : l’assuré, l’assureur, l’investisseur et l’opérateur de l’instance. Tout d’abord, vous avez besoin de produits d’assurance que vous pouvez vendre. Les produits d’assurance ont un product owner qui conçoit les produits. Les produits d’assurance eux-mêmes sont issus de smart contracts.
_Les Oracles sont une partie essentielle du GIF pour la mise en œuvre de l’assurance paramétrique. Les Oracles fournissent les données nécessaires, par exemple les données de vol ou les données météorologiques, aux contrats d’une instance GIF._
La pool de risque est également un smart contract gardant la trace de tous les détails du capital-risque, des montants versés en tant que polices et de toutes les sommes versées.
Une instance GIF relie ces rôles individuels et représente une entité exécutable complète définie par le GIF. Chaque instance est constituée de l’ensemble opérationnel de smart contracts GIF d’une blockchain. Différentes blockchains peuvent exécuter différentes instances.
[](#3_1_etherisc_les_bases_de_lassurance)
3.1 Etherisc - les bases de l’assurance
---------------------------------------------------------------------------------
Dans le chapitre "2.2 Principes de l’assurance", nous avons utilisé un exemple pratique pour illustrer la manière dont l’assurance est développée et fonctionne avec la participation de l’assuré. Dans ces chapitres, nous allons expliquer et définir l’assurance du point de vue d’Etherisc.
### [](#3_1_1_quest_ce_que_lassurance)
3.1.1 Qu’est-ce que l’assurance ?
_L’assurance est un moyen de protection contre les pertes financières. Il s’agit d’une forme de gestion des risques dont le but premier est de se protéger contre le risque de perte possible ou incertaine._
L’assurance est un moyen de protection contre les pertes financières. Il s’agit d’une forme de gestion des risques dont le but premier est de se protéger contre le risque de perte possible ou incertaine. La perte associée au risque peut être financière ou non, mais elle doit pouvoir être entendue en termes financiers.
Une compagnie d’assurance\[[12](#_footnotedef_12 "View footnote.")\
\] garantit les risques de l’assuré. Elle peut externaliser tous les services, tels que la vente ou la gestion des données, à d’autres prestataires de services. Seule la prise en charge effective du risque ne peut pas être déléguée. Ce risque doit toujours être assumé par la compagnie d’assurance. Par conséquent, la compagnie et ses clients doivent toujours avoir une comptabilité correcte des risques qu’ils couvrent et de la manière dont ils sont garantis.
_Grâce aux smart contracts, cela peut se faire de manière transparente et vérifiable._
### [](#3_1_2_quest_ce_quune_police_dassurance)
3.1.2 Qu’est-ce qu’une police d’assurance ?
Une police d’assurance est un contrat fourni à l’assuré par la compagnie d’assurance définissant les conditions et les circonstances dans lesquelles la compagnie d’assurance garantira les pertes subies par l’assuré en raison de sinistres reconnus. Dans la finance traditionnelle, il s’agit généralement d’un contrat juridique. Ici, une police est simplement un ensemble de données stocké sur la blockchain et manipulé via des règles définies par un smart contract.
Examinons le cycle de vie d’une police d’assurance type. Ce cycle de vie se compose généralement des sous-étapes suivantes, classées par ordre chronologique.
* Le client se renseigne sur une police d’assurance. Il veut se protéger contre un risque spécifique en souscrivant à une police d’assurance.
* La compagnie d’assurance examine la demande du client.
* La demande est acceptée ou rejetée.
* En cas de rejet, le client est informé et aucune autre activité n’est entreprise.
* En cas d’acceptation, le contrat revient au "souscripteur". L’acceptation de la proposition est appelée "souscription".
* La compagnie d’assurance s’engage par la "souscription" à prendre en charge le risque du client et à le supporter. Elle s’engage en outre à couvrir le sinistre si l’événement assuré se produit.
* Le client, quant à lui, s’engage à payer la prime.
* Les deux déclarations d’obligation sont consignées dans un contrat. Ce contrat est appelé police d’assurance.
* Si un sinistre survient, le client le signale à la compagnie d’assurance.
* La demande est vérifiée par la compagnie d’assurance. Elle est alors acceptée ou rejetée.
* En cas d’acceptation, la somme d’assurance convenue est versée.
Il est facile de constater que le secteur classique des assurances génère une bureaucratie considérable et que de nombreuses sous-étapes nécessitent des activités manuelles. Par exemple, lorsqu’un client dépose une demande d’indemnisation, la compagnie d’assurance doit vérifier manuellement les détails de la demande. Cela implique du travail et, par conséquent, des coûts.
### [](#3_1_2_quest_ce_que_lassurance_paramétrique)
3.1.2 Qu’est-ce que l’assurance paramétrique ?
L’assurance paramétrique est un accord entre la compagnie d’assurance et l’assuré qui couvre la survenance d’événements prédéfinis plutôt que d’examiner et d’indemniser manuellement les pertes réellement subies.
Les polices d’assurance paramétriques correspondent à des accords entre l’assurance et l’assuré dans lesquels l’assurance approuve les paiements à l’assuré lorsque des événements déclencheurs prédéfinis se produisent.
Dans l’assurance paramétrique, les sinistres (les risques) sont définis comme des fonctions d’indices ou de paramètres sous-jacents répondant aux critères définis par la police d’assurance. Par exemple, la quantité de pluie ou la vitesse du vent sont des paramètres pouvant être pris en compte dans un contrat d’assurance lié aux conditions météorologiques. Dans le cas d’une assurance portant sur les retards de vol, le paramètre pourrait être la différence entre l’heure d’arrivée réelle et l’heure d’arrivée prévue d’un vol assuré.
_Pour que l’assurance paramétrique soit réalisable et attrayante, les paramètres sous-jacents doivent être transparents, fiables et dignes de confiance._
Lorsque de tels événements se produisent, l’assurance calcule et déclenche directement le versement d’une indemnité à l’assuré sans passer par une procédure d’acceptation des demandes d’indemnisation souvent coûteuse.
Le potentiel d’efficacité et d’automatisation constitue le grand avantage de l’assurance paramétrique. La gestion des sinistres, l’une des parties les plus complexes et les plus coûteuses de l’activité d’assurance, peut être réduite à un processus simple et entièrement automatisé.
### [](#3_1_3_quels_sont_les_avantages_de_la_blockchain_dans_lassurance)
3.1.3 Quels sont les avantages de la blockchain dans l’assurance ?
La technologie de la blockchain peut améliorer le domaine de l’assurance sur plusieurs points. Certains de ces avantages sont directement liés aux fondements de cette technologie.
* Transparence et responsabilité quant à la tenue des dossiers. Les informations concernant les polices, les sinistres et les paiements peuvent être stockées sur la blockchain. Une fois stockée, elles ne peuvent être ni supprimées ni modifiées sans autorisation spécifique, et chaque fois que les données sont mises à jour ou ajustées, les données originales sont conservées dans l’historique. Une piste d’audit complète est disponible et transparente pour toutes les données.
* Réduire au minimum les frictions et les coûts de transaction pour le traitement des paiements.
* Créer de nouveaux marchés/opportunités en ouvrant les risk pools. La transparente mise en commun d’un grand nombre de polices d’assurance d’un type particulier offre la possibilité d’ouvrir ce marché à un public plus large.
* Ces nouveaux marchés offrent également la possibilité d’échanger des risques en petites quantités, appelées "risk pool token."
La technologie de la blockchain peut apporter beaucoup de valeur, notamment pour l’assurance paramétrique.
* La fourniture de ces données centrales de manière fiable à l’écosystème sera gérée par des services d’oracle, ce qui rendra très difficile et trop coûteux l’injection d’informations manipulées dans les smart contracts mettant en œuvre des polices d’assurance paramétriques.
* Une fois que l’alimentation en paramètres sera fournie aux contrats d’assurance, l’assurance paramétrique automatisera entièrement le traitement des sinistres et des paiements.
* Paiements immédiats. Le fait de fonctionner via la blockchain et de disposer d’un traitement automatisé des réclamations et des paiements permet d’effectuer des paiements quasiment en temps réel.
[](#3_2_le_modèle_etherisc)
3.2 Le modèle Etherisc
--------------------------------------------------
### [](#3_2_1_les_trois_piliers_de_lécosystème_etherisc)
3.2.1 Les trois piliers de l’écosystème Etherisc

**Marché du transfert de risques**
La levée de fonds pour soutenir les garanties techniques est effectuée par les investisseurs. Les investisseurs bloquent une certaine quantité de DIP token, également appelée "staking". Ces DIP token loqués sont une condition préalable pour pouvoir ensuite investir le capital-risque réel en DIP ou en stablecoins.
La communauté des détenteurs de DIP token a créé l’ensemble de l’écosystème Etherisc. Par conséquent, nous demandons que les parties qui profitent de l’écosystème Mettent en jeu des DIP token. Cette idée est empruntée à l’espace des entreprises coopératives. Elle reflète le fait que l’écosystème Etherisc est un bien public qui doit être protégé de la ["tragedy of the commons.”](https://en.wikipedia.org/wiki/Tragedy_of_the_commons)
**Legal framework**
Les compagnies d’assurance sont fortement réglementées dans le monde entier pour de bonnes raisons, afin de protéger les clients et les investisseurs. Un grand nombre de lois ont été adoptées à cette fin dans la plupart des pays. En ce qui concerne la juridiction, une distinction générale peut être faite entre les régions américaine, européenne et anglo-saxonne.
Mais même au sein de ces régions, chaque pays a son framework juridique et monétaire propre. Etherisc s’engage auprès des régulateurs locaux pour aider à créer un environnement réglementaire efficace concernant l’assurance basée sur la blockchain. Etherisc soutient les parties intéressées et aide à guider le processus de coordination avec les agences et les ministères concernés.
Les obstacles financiers et organisationnels à la création d’une nouvelle compagnie d’assurance sont élevés. Pour des pays comme l’Allemagne, Etherisc propose un nouveau modèle juridique où la créance légale est échangée contre une garantie technique en utilisant la blockchain et les smart contracts. Ainsi, le prestataire - dans ce cas Etherisc - n’est plus soumis aux exigences juridiques et financières d’une compagnie d’assurance. Malgré tout, pour chaque projet, produit et juridiction, le framework juridique doit être pris en compte et le product owner est responsable de sa bonne mise en œuvre. L’équipe d’Etherisc a accumulé beaucoup d’expérience dans ce domaine et est heureuse de partager ces connaissances avec les utilisateurs de la plateforme.
**Technical framework**
Développé et maintenu par Etherisc, le Generic Insurance Framework (GIF) permet de modéliser, déployer et exploiter des produits d’assurance basés sur la blockchain de manière décentralisée et transparente.
Grâce au GIF, les parties intéressées peuvent rapidement mettre en œuvre et exploiter en toute sécurité leurs produits d’assurance.
Avec le GIF, il est techniquement possible de modéliser des polices d’assurance individuelles.
[](#3_3_quest_ce_que_le_gif)
3.3 Qu’est-ce que le GIF ?
-------------------------------------------------------

GIF est un acronyme qui signifie "generic insurance framework". Il consiste essentiellement en une collection de smart contracts, dont le code source est libre d’accès; mettant en œuvre des fonctions génériques du cycle de vie des produits et des polices d’assurance.
_Ainsi, le GIF permet de modéliser une grande variété de types d’assurance._
Les étapes de traitement qui se déroulent de manière similaire dans tous les produits ont été identifiées et mises à disposition sous forme de modules pour concevoir rapidement et facilement des produits d’assurance. Ainsi, seuls les aspects spécifiques au produit, tels que la tarification, etc., doivent être implémentés pour chaque produit.
### [](#3_3_1_gif_et_instances_gif)
3.3.1 GIF et instances GIF
Pour exploiter les produits d’assurance, y compris la vente de polices, la collecte des primes, le calcul des événements déclencheurs et le traitement des paiements, un système d’exécution complet est nécessaire en plus des collections de smart contracts qui définissent les produits et les polices.
Cet environnement d’exécution - appelé instance GIF - peut être considéré comme une plateforme ou une place de marché complète dans laquelle les produits d’assurance basés sur le GIF sont gérés et exploités. Notre objectif est que le GIF soit utilisé par de nombreux fournisseurs différents et indépendants offrant divers produits d’assurance. La figure ci-dessous donne un aperçu des rôles des parties prenantes impliquées dans une instance GIF.

### [](#3_3_2_les_participants_sur_la_platform)
3.3.2 Les participants sur la platform
**Assuré/Client**
L’assuré/client est le titulaire de la police qui souhaite transférer son risque aux risk pools. Les tiers peuvent proposer des passerelles de paiement et des intégrations qui suppriment la nécessité de posséder des crypto-monnaies pour le client final.
**Investor**
Les investisseurs souhaitent participer aux risk pools pour équilibrer/diversifier leurs portefeuilles de risques. Les investisseurs fournissent des garanties pour les risk pools en échange de paiements d’intérêts.
**Oracle Owner**
L’une des applications les plus prometteuses d’un espace d’assurance décentralisé est la façon dont les données sont collectées et gérées. Le oracle owner fournit des oracles qui font l’interface entre les smart contracts de la blockchain et les sources de données externes. Dans le cas d’une assurance contre les retards de vol, l’oracle informe le smart contract si le vol a atterri à temps, de combien il a été retardé ou s’il a été complètement annulé.
**Product owner**
Le product owner conçoit et exploite un ou plusieurs produits. Il s’agit d’une compagnie d’assurance ou d’un AGG (agent général de gestion) dans le secteur traditionnel de l’assurance. Grâce à la capacité multi-client, un product owner peut utiliser tous les oracles situés sur les plateformes respectives des oracle owners.
**Risk pool keeper**
Un risk pool keeper gère une ou plusieurs risk pools.
_Une pool de risques est un smart contract qui regroupe plusieurs risques, représentés par des objets de politique, au capital-risque._
Les risk pools collectent les garanties apportées par les fournisseurs de capital. Les pertes sont payées à partir de la pool de risques. Par conséquent, le capital dans la pool est risqué (risque de pertes défaut). Les investisseurs peuvent compléter leurs investissements et également retirer leurs fonds.
**Instance operator**

Tout déploiement complet d’une structure GIF est appelé "instance GIF". Il y aura toujours au moins une instance GIF complète exploitée par le projet Etherisc, mais en principe, n’importe qui peut déployer une nouvelle instance GIF. L’opérateur d’instance est le maillon crucial faisant fonctionner une instance GIF spécifique.
Les principales tâches de l’opérateur d’instance sont l’administration des produits et des oracles ainsi que quelques autres actions basiques. Toute instance GIF est capable de gérer plusieurs clients, ce qui signifie que plusieurs product owner et de fournisseurs d’oracles peuvent être exploités et administrés sur une instance GIF.
L’opérateur d’instance est représenté par une adresse Ethereum. L’opérateur de l’instance peut être une personne physique possédant la clé privée de cette adresse ou un smart contract - soit une structure multisig ou DAO. Ceci permet le fonctionnement entièrement décentralisé de toute instance GIF. Une adresse peut, bien entendu, gérer plusieurs instances GIF indépendantes.
Le contrôle décentralisées des instances gif est l’objectif déclaré du projet Etherisc - soit par multisig, soit par des DAO avec leur propre structure de gouvernance - elles doivent également être contrôlées par les parties prenantes de la plateforme (clients, product owner, oracle owner et gardiens du pool de risques). Au chapitre 5, nous examinons la manière dont l’écosystème peut encourager ce développement.
[](#3_4_fonctions_génériques_du_cycle_de_vie_dans_le_gif)
3.4 Fonctions génériques du cycle de vie dans le GIF
--------------------------------------------------------------------------------------------------------------
### [](#3_4_1_concept_de_components)
3.4.1 Concept de components
Chaque instance de GIF gère différents components. Un composant est un smart contract spécifique doté d’une certaine fonctionnalité de base. Les components peuvent représenter différents objets de base.
Les objets principaux sont :
* Products
* Oracles
* Risk pools
Tous les components, et donc les objets qu’ils contiennent, peuvent prendre des états identiques et avoir le même cycle de vie, mais peuvent différer considérablement en termes de durée de vie.
### [](#3_4_2_rôles_et_cycle_de_vie_des_components)
3.4.2 Rôles et cycle de vie des components
Deux rôles peuvent déterminer le cycle de vie d’un composant.
**Component owner**
Le component owner peut être le oracle owner, product owner ou risk pool keeper, selon l’objet central qu’il gère.
**Instance Operator**
L’instance operator exécute une ou plusieurs instances GIF.

**Un component du GIF est toujours dans l’un des états suivants :**
* Created (Créé)
* Proposed (Proposé)
* Declined (Refusé)
* Active (Actif)
* Paused (En pause)
* Suspended(Suspendu)
* Afchived (Archivé)
La transition entre ces états et les rôles par lesquels ils peuvent être déclenchés sont décrits dans le diagramme ci-dessus. Le cycle de vie d’un composant commence par son développement et son déploiement sur la blockchain. Le component owner peut mettre en œuvre ses exigences spécifiques dans le smart contract du composant ou utiliser la fonctionnalité générique des components GIF. À l’étape suivante, le composant est enregistré, approuvé et activé par l’opérateur d’instance dans l’instance GIF. L’opérateur d’instance peut également refuser un composant. Le composant est ensuite supprimé.
En cas d’approbation, l’opérateur de l’instance continue à vérifier les détails techniques et procéduraux. L’opérateur de l’instance peut également confier la vérification à un audit indépendant.
_Une autre condition impose au component owner de posséder un certain montant de DIP token pour être autorisé à fonctionner dans l’instance GIF._
Si le composant est actif, il peut être utilisé jusqu’à ce qu’il soit suspendu ou mis en pause. Seul l’opérateur de l’instance peut suspendre un composant ou faire cesser la suspension alors que la mise en pause d’un composant ou la réactivation de ce composant peuvent être effectués par le component owner ou l’opérateur d’instance. Si le composant est inactivé (en pause, suspendu) et non réactivé (cessation pause ou suspension), il n’est pas supprimé mais archivé.
Pour chaque type de composant (produits, oracles, risk pools), nous fournissons des exemples d’implémentation qui peuvent être utilisés comme point de départ.
### [](#3_4_3_cycle_de_vie_de_la_police)
3.4.3 Cycle de vie de la police

Indépendamment du produit spécifique, chaque police traitée sur l’instance GIF a un cycle de vie. En général, une police subit plusieurs changements d’état au cours de son cycle de vie. Bien que tout concepteur de produit puisse mettre en œuvre son propre cycle de vie (dans notre terminologie, le cycle de vie est appelé "PolicyFlow"), le GIF offre un cycle de vie par défaut qui devrait être suffisant pour la plupart des cas d’utilisation. Ce cycle de vie générique est appelé "PolicyFlowDefault".
**Le cycle de vie "PolicyFlowDefault" offre les fonctions suivantes :**
* newApplication (pour générer et stocker une nouvelle application d’un client)
* souscrire (pour signer une proposition et créer une nouvelle police)
* refuser (rejeter une demande)
* newClaim (pour générer et stocker un nouveau sinistre en cas de perte)
* confirmClaim (pour confirmer une demande et créer un paiement)
* declineClaim (pour rejeter une demande)
* payout (pour confirmer et initier un dédommagement)
### [](#3_4_4_paiements)
3.4.4 Paiements
L’instance GIF est indifférente à la manière dont les paiements sont effectués. Les paiements en crypto peuvent être effectués directement sur le contrat du produit, tandis que les paiements en fiat nécessitent une passerelle fiat et une infrastructure bancaire ou de carte de crédit externe. L’équipe centrale peut demander des informations sur la façon de mettre en œuvre les passerelles fiat.
[](#3_5présentation_du_moniteur_gif)
3.5 Présentation du moniteur GIF
---------------------------------------------------------------------
Le système GIF est entièrement transparent pour les experts en blockchain, mais il peut être difficile à comprendre pour les non experts en blockchain.
_C’est pourquoi nous avons développé le moniteur GIF pour donner à chacun un aperçu de ce qui se passe sur la blockchain d’une instance GIF._
### [](#3_5_1_quest_ce_que_le_moniteur_gif)
3.5.1 Qu’est-ce que le moniteur GIF ?
Le moniteur GIF fournit une vue d’ensemble structurée de tous les blocs de construction génériques disponibles dans le GIF pour créer et exploiter un produit d’assurance. Vous pouvez visualiser tous les événements et toutes les transactions commerciales de l’instance complète.
Le moniteur GIF fournit toutes ces informations de manière transparente et en temps réel en ligne. Les informations sont lues à partir de la blockchain et du GIF.
### [](#3_5_2_éléments_de_menu)
3.5.2 Éléments de menu
L’URL [https://gif-monitor.etherisc.com/](https://gif-monitor.etherisc.com/)
vous amène à la zone d’accueil du moniteur GIF. Dans la barre de menu, vous pouvez choisir parmi les éléments de menu suivants.
Dans la zone "Accueil", vous pouvez cliquer directement sur les éléments de menu de la barre de menu, puis sélectionner l’élément de menu correspondant dans le menu déroulant.
**Core**
La zone "Core" est de loin la plus étendue. Elle affiche les instances GIF disponibles, les contrats de base GIF par instance et les événements de ces contrats de base. La zone "Core" affiche l’ensemble des contrats de base que chaque utilisateur peut utiliser.
Vous trouverez ici les blockchains utilisées par les instances, telles que xDai ou Ethereum. En cliquant sur une instance, vous obtiendrez des informations détaillées comme l’ID de l’instance, le nom, le nom de la blockchain, l’ID de la blockchain et le statut (actif ou non). Chaque instance est identifiée par son adresse de registre. GIF est capable de fonctionner sur plusieurs blockchains et peut s’exécuter sur toutes les principales blockchains similaires à Ethereum.
Dans cette section, vous trouverez les 14 contrats principaux (intelligents) du GIF. Chaque contrat de base fournit des fonctionnalités essentielles à une Instance GIF.
Vous pouvez cliquer sur le nom du contrat pour tous les contrats principaux du GIF afin d’accéder aux détails du contrat. Vous y verrez l’instance dans laquelle vous vous trouvez, l’ID de l’instance, l’adresse sur la blockchain, le nom du contrat principal et la fonctionnalité détaillée du contrat telle que décrite par l’interface ABI (Application Binary) du contrat.
Les événements contractuels des contrats principaux du GIF sont affichés ici.
Les événements contractuels sont émis par les smart contract pendant l’exécution du code et stockés de façon permanente sur la chaîne. Les événements sont principalement utilisés pour documenter les changements significatifs dans les données des smart contracts, par exemple le changement de statut.
**Oracles**
Les oracles disponibles sont affichés dans la zone "Oracle" du moniteur GIF.
Sur cette page, vous trouverez tous les oracles disponibles sur la plateforme. Vous pouvez consulter toutes les entrées et rappel dont disposent les product owner. De plus, l’oracle concerné peut être sollicité aux oracle owner.
En cliquant sur un oracle, le moniteur GIF affiche les détails.
Bien entendu, des oracles individuels peuvent également être ajoutés sur demande.
**Products**
Dans la zone "Produits", tous les produits qui ont été créés dans le framework sont répertoriés. En cliquant sur un produit, les détails s’affichent.
**Polices**
Dans le domaine des "polices", vous trouverez des informations sur chaque phase du cycle de vie d’une police. Cela commence par des informations sur le produit, les métadonnées, la proposition, la police, le sinistre et le paiement. En fonction du cycle de vie de la police, plus ou moins de blocs d’informations sont affichés.
[](#4_assurance_par_token)
4 Assurance par token
================================================
Vous pouvez tokeniser presque tout. Certaines choses ont moins de sens que d’autres. Nous sommes convaincus que l’assurance est un sujet de plus en plus brûlant autour de la tokenisation.
[](#4_1le_dip_token)
4.1 Le DIP token
-------------------------------------
L’acronyme "DIP" signifie "Decentralized Insurance Protocol" et "Decentralized Insurance Platform". Le DIP est le token natif d’Etherisc émis par la "Decentralized Insurance Foundation" (DIF) basée à Zug/Suisse.
Au cours de l’Etherisc DIP TGE (Token Generating Event), des DIP token ont été créés sur le réseau principal public Ethereum. Nous avons préféré utiliser ce terme plutôt que "ICO" ou "vente des token".
**Quelques faits sur l’Etherisc DIP TGE:**
* **Hardcap :** 30 millions USD
* **Approvisionnement total :** 1 milliard (10^9)DIP
* **token distribués aux premiers investisseurs et pendant la TGE :** 300M DIP (= 30% de l’offre totale)
* **Prix TGE :** 1 DIP = 0,10 USD
* **Seuls les contributeurs enregistrés** ont pu participer au TGE Etherisc DIP
Les participants (et non les clients) ont besoin de token pour rejoindre l'"écosystème" de la plateforme. En règle générale, toute personne qui souhaite utiliser la plateforme pour gagner de l’argent devra posséder et mettre en jeu un certain nombre de DIP token. Ces DIP token restent la propriété du participant et lui seront remboursés s’il a l’intention de quitter la plateforme, moyennant un certain délai de préavis.
En fonction du service offert, un nombre différent de token est nécessaire pour utiliser la plateforme ou offrir des services sur la plateforme. Les services simples nécessitent un petit nombre de token, tandis que les services complexes ou critiques nécessitent davantage de token. La quantité de token qui doit être fournie comme enjeu dépend du dommage potentiel causé par la mauvaise conduite du participant ou la violation des conditions de la plateforme. La mise en jeu des DIP token est différente de la mise en jeu des actifs dans les risk pools, dont nous parlerons plus loin.
Les DIP token mis en jeu peuvent être " confisqués " en cas de mauvais comportement, par exemple en cas de violation de certaines conditions ou exigences. Les règles d’annulation seront publiées sur le site d’Etherisc.
À l’avenir, ces règles et paramètres serviront de base au contrôle de la plateforme. Le DIP token sert de garantie et de représentation de la valeur matérielle et immatérielle du réseau, comme les ressources financières servent à garantir les ressources opérationnelles d’une coopérative.
[](#4_2le_modèle_de_staking_etherisc)
4.2 Le modèle de staking Etherisc
-----------------------------------------------------------------------
Le staking est encore en version bêta - attendez-vous à ce que le modèle de staking Etherisc subisse des changements substantiels dans un avenir proche !\_
Dans l’écosystème Etherisc, le staking se présente sous **deux formes différentes :**
1. Le premier type de staking consiste à staker des DIP token dans un "pool de staking global". Le premier type de staking garantit que les participants qui gagnent de l’argent en utilisant la platform “jouent leur peau”, et garantit également que les participants sont économiquement incités à se comporter conformément aux règles de la platform.
2. Le deuxième type de staking consiste à staker des actifs cryptographiques, généralement des stablecoins, dans des risk pools. Ces actifs portent le risque de l’assurance.
### [](#4_2_1_staking_pour_les_risk_pools)
4.2.1 Staking pour les risk pools
Lorsque vous souscrivez une police d’assurance, vous attendez un paiement en cas de sinistre. Pour garantir qu’il y ait toujours assez de liquidités pour commencer ou continuer à vendre des polices et pour effectuer tous les paiements, nous prévoyons de mettre en place un système avec deux risk pools correspondantes.
Les deux risk pools correspondantes collecteront les primes pour toutes les polices vendues et les liquidités supplémentaires fournies par les investisseurs. Chaque risk pool bien conçue est soumise à un modèle actuariel pour le risque assuré et détermine ainsi une certaine probabilité de défaut pour chaque police.
Nous définissons le staking dans le contexte de l’assurance décentralisée comme suit :
_"Le processus consistant à attirer et à lier le capital des investisseurs à des risk pools spécifiques pour couvrir leurs risques extrêmes."_
Les primes nettes (après déduction des coûts) provenant de l’achat de polices sont versées dans la risk pool, et les sinistres sont couverts par les fonds de la risk pool. L’investisseur choisit une option de placement en fonction de sa tolérance au risque et de la structure de son portefeuille.
Il peut aussi choisir son investissement en fonction d’aspects éthiques tels que le respect de l’environnement, la neutralité climatique ou l’engagement social. Si nécessaire, il accepte un bénéfice moindre pour offrir une assurance aux petits agriculteurs, par exemple. Nous encouragerons toujours la mise en place de produits verts et équitables sur le GIF !
### [](#4_2_2_risk_pools_ne_nécessitant_pas_de_confiance)
4.2.2 Risk pools ne nécessitant pas de confiance
Pour qu’une risk pool sans confiance fonctionne, il faut mettre en œuvre des méthodes qui garantissent, de manière technique et transparente, que les intérêts des assurés et des investisseurs soient respectés. Pour l’assuré, cela signifie que nous pouvons prouver que la risk pool de risques sera toujours en mesure d’honorer ses demandes.
Pour les investisseurs, cela signifie qu’ils reçoivent une part équitable des bénéfices réalisés et qu’ils peuvent décider des risques auxquels ils exposent leurs fonds. Il devient donc nécessaire pour le système de fonctionner entièrement sur la blockchain. Sur la blockchain, le calcul est coûteux, nous devons donc faire en sorte que ces calculs soient efficaces. Pour atteindre cet objectif, nous prévoyons de mettre en place des "périodes" dans nos risk pools. La durée d’une période dépendra du produit. Pour chaque période, toutes les polices vendues seront traitées de la même manière. Cette étape réduit massivement la complexité.
4.2.3 L’idée de base des risk pools et des récompenses dans l’assurance
Le processus économique central de l’assurance, le transfert du risque entre les assurés et les investisseurs, est mis en œuvre dans le GIF par le biais de risk pools.
Bien que le modèle standard de risk pool comprenne toutes les fonctions de base pour le traitement des primes, des sinistres, des dépôts, des paiements et des retours, le modèle laisse un maximum de flexibilité aux risk pool keepers pour concevoir leur modèle économique afin d’attirer les assurés, les product owner et les investisseurs.
### [](#4_2_4_fonctions_essentielles_dune_risk_pool)
4.2.4 Fonctions essentielles d’une risk pool
* Recevez des primes sous forme de tokens natifs ou stables.
* Recevoir des dépôts d’investissement en token ou stable coins, conformément aux spécifications du risk pool keeper et du product owner.
* Gérer les dépôts d’investissement. Un investisseur doit pouvoir connaître à tout moment l’état de son investissement.
* Remboursement des sinistres en cas de perte.
* Traitement des retraits d’investissement. Ce mécanisme est conçu de manière à ce que le capital-risque ne puisse être versé que lorsqu’il ne sert plus de garantie des contrats conclus.
* Processus de distribution des bénéfices. Une partie importante des primes versées est distribuée sous forme de bénéfices aux investisseurs en fonction du montant de l’investissement, de la période de dépôt et du risque pris.
* Contrôle autonome des paramètres des risk pools. La taille des risk pools dépend de la demande pour le produit sous-jacent. Nous fournirons des mécanismes permettant un contrôle autonome des paramètres des risk pools.
[](#4_3mise_en_œuvre_des_risk_pools_dans_le_gif)
4.3 Mise en œuvre des risk pools dans le GIF
---------------------------------------------------------------------------------------------
Les risk pools standards seront initialement constituées d’une primary risk pool (PRP). Des secondary risk pools (SRP) peuvent être créées en option. Cette combinaison de deux risk pools offre une flexibilité totale pour les produits d’assurance et les investisseurs.
### [](#4_3_1_primary_risk_pool_prp)
4.3.1 Primary risk pool (PRP)
Les primary risk pool (PRP) recevront les primes nettes (c’est-à-dire les primes brutes moins les coûts) payées par les assureurs en monnaies stables (par exemple USDC, dans cet exemple, ou xDai à Flight Delay) en échange des actifs mis en jeu par l’investisseur. Le PRP générera des NFT de pool de risque.
Un investisseur ne transfère pas son DIP token directement dans le PRP mais dans le SRP. Les DIP token déposés sont collectés et transférés au PRP à la fin d’une époque, et le PRP génère un nouveau risk pool NFT ; le propriétaire est le SRP. L’investisseur reçoit la valeur équivalente de sesDIP token déposés en risk pool tokens (RPT) frappés par le PRP.
La global staking pool couvrira tous les risk pools primaires d’une instance GIF. Comparable à la réassurance, elle intervient si, par exemple, des black swan events entraînent l’insolvabilité d’une primary risk pool. Les investisseurs peuvent également mettre en jeu leurs token et leurs pièces stables dans la global staking pool.

### [](#4_3_2_risk_pool_token_rpt)
4.3.2 Risk Pool Token (RPT)
Si l’investisseur place des actifs dans la primary risk pool, il reçoit un risk pool NFT faisant office de reçu. Alors que les NFT sont en principe négociables, nous prévoyons que les risk pool NFT ne seront pas liquides. Pour faciliter l’échange de risques, nous introduirons des trisk pool token (RPT) via des "secondary risk pools". Une secondary risk pool acquerra les NFTs du pool de risques primaire et les fractionnera. Les investisseurs peuvent investir dans une secondary risk pool et recevront des RPT (ERC-20) proportionnellement à leur part dans la secondary risk pool. De nouveaux RPT sont frappés lorsque de nouveaux capitaux sont déposés dans la risk pool. Pour chaque risk pool, des RPT spécifiques sont frappés.
### [](#4_3_3_risk_pool_nft)
4.3.3 Risk pool NFT
Les NFT sont liés à un PRP spécifique et couvrent les risques des polices d’assurance individuelles. Les NFT restent dans le SRP et les RPT dans les portefeuilles des investisseurs. Lorsque toutes les polices liées à un NFT sont expirées et que tous les sinistres associés ont été payés, l’investisseur peut retirer tous les actifs associés au NFT.
### [](#4_3_4_pourquoi_des_périodes)
4.3.4 Pourquoi des périodes ?
Nous voulons que les investisseurs déposent et résilient leurs contrats aussi rapidement et efficacement que possible. Mais la protection des autres investisseurs et des assurés est également essentielle pour nous. Nous avons donc trouvé un compromis qui profite à toutes les parties, les périodes (Epochs).Les périodes réduisent massivement la complexité de calcul, un facteur limitant dans les smart contracts en raison des limites blocantes de gaz. Le concept de période permet d’exécuter chaque transaction avec un plafond de gaz fixe.
### [](#4_3_5_staking_sur_une_seule_facedouble_facemultiple_face)
4.3.5 Staking sur une seule face/double face/multiple face
Dans la première version de notre risk pool, nous proposerons uniquement le staking unilatéral (le risque est pris par un seul stablecoin). Cependant, vous devez miser un certain montant de DIP token dans la global staking pool par rapport au capital investi. Ce n’est donc que lorsque vous avez misé le montant de base en DIP token que vous pouvez apporter du capital-risque sous forme de stablecoins. À l’avenir, les investisseurs pourront miser différents actifs - pas seulement des stablecoins - en fonction des exigences du détenteur de la risk pool.
### [](#4_3_6_récompenses_en_crédit_et_pertes_de_paiement)
4.3.6 Récompenses en crédit et pertes de paiement
La norme offerte par le framework de l’assurance générique est simple. Les primes sont ajoutées à la risk pool (après déduction des coûts) et augmentent la valeur des token de ladite risk pool. Les paiements sont effectués à partir de la risk pool et diminuent la valeur desdits token.
Lors d’une mise en œuvre standard, les bénéfices restent initialement dans la risk pool. Les bénéfices sont réalisés au moment où le capital peut être retiré de la risk pool.
Les investisseurs reçoivent leurs primes lors de la conclusion du contrat. Les primes versées par les assurés sont créditées proportionnellement dans le rapport capital risque personnel / capital risque total. Les remboursements éventuels en cas de sinistre sont répartis proportionnellement entre tous les fournisseurs de capital-risque qui ont contribué aux primes depuis le début du contrat.
Ainsi, si vous avez deux investisseurs, l’investisseur 1 à 100.000 DIP, l’investisseur 2 à 50.000 DIP. Une assurance est souscrite avec une prime de 30 USDC. L’investisseur 1 reçoit l’équivalent de 20 USDC grâce au gain de prix de son RPT, l’investisseur 2 reçoit l’équivalent de 10 USDC. Les USDC restent dans le PRP.
Si une demande d’indemnisation est ensuite présentée à hauteur de 90 USDC sur cette police, les 90 USDC seront payés à partir du PRP. L’investisseur 1 perd l’équivalent de 60 USDC, l’investisseur 2 perd l’équivalent de 30 USDC.
[](#5_modèle_de_gouvernance_etherisc_egm)
5 Modèle de gouvernance Etherisc (EGM)
================================================================================
[](#5_1résumé)
5.1 Résumé
-------------------------
1. L’objectif du modèle de gouvernance Etherisc (EGM) est de créer un mécanisme d’autorégulation efficace pour l’écosystème Etherisc. Etherisc considère qu’un socle de règles et de procédures est nécessaire pour garantir que :
1. La plateforme fonctionne d’une manière conforme aux règles et recommandations du protocole de la Plateforme d’assurance décentralisée (DIP).
2. Les participants à la plateforme mènent leurs activités dans l’intérêt du bien commun, tout en préservant les intérêts des clients et des investisseurs.
3. L’intégrité du marché est préservée, ce qui signifie qu’il n’y a pas d’abus de marché et que tous les participants à la plateforme ont un accès égal à des informations précises et transparentes.
2. Conformément à une infrastructure décentralisée, la réglementation doit être assurée par la communauté plutôt que par une seule entité. De plus, les règles doivent être applicables afin d’inciter à leur respect. Pour que les règles soient applicables, il faut qu’il y ait un élément de staking.
3. Au-delà du bon fonctionnement de l’écosystème, qui est une fin en soi, l’EGM contribuera à renforcer la confiance dans le système d’assurance décentralisé Etherisc et à soutenir sa croissance et son adoption massive.
[](#5_2valeurs_fondamentales)
5.2 Valeurs fondamentales
-------------------------------------------------------
Tout système de règles nécessite un ensemble de principes et de "valeurs" sous-jacent. L’ensemble et la signification de ces valeurs sont nécessairement, dans une certaine mesure, flous et ne peuvent être entièrement saisis par une définition formelle.
Certaines personnes pourraient, par exemple, mettre l’accent sur d’autres valeurs qui ne figurent pas dans cette liste, ou les formuler différemment. Cependant, ces règles se sont avérées utiles dans d’autres contextes reposant sur la décentralisation et la collaboration.
Ces valeurs servent de lignes directrices générales dont dérivent des règles et des exigences plus précises.
1. **Respect**
Chaque utilisateur de la plateforme, acteur, partie prenante doit respecter et valoriser la diversité. Nous encourageons l’inclusion et traitons les autres avec tact, courtoisie et respect. Nous nous abstenons et décourageons activement la discrimination sous toutes ses formes.
2. **Collaboration**
La platform d’assurance décentralisée est basée sur des partenariats solides et volontaires. La plateforme encouragera toujours les partenariats et la coopération. Chaque participant doit pouvoir bénéficier de l’évolution des partenariats.
3. **Responsabilité**
Chaque participant agit sous son entière responsabilité, tandis que la platform fournira tous les moyens nécessaires à cet effet. Tous les participants reconnaissent leur responsabilité commune pour le fonctionnement et le développement de la platform dans son ensemble.
4. **Confiance**
La platform encourage les comportements de confiance et offre un environnement sûr à tous les participants. Chaque participant s’engage à adopter un comportement conforme. La transparence est un élément important pour établir la confiance, c’est pourquoi nous encourageons la transparence autant que possible, sans violer les besoins justifiés de protection de chaque participant de la plateforme.
5. **Bien public / Commons**
La plateforme dans son ensemble sert le bien public. Il s’agit d’un "bien commun"\[[13](#_footnotedef_13 "View footnote.")\
\] au sens d’Elinor Ostrom, exploité par la communauté de tous les participants. Par conséquent, les règles de gouvernance de la platform sont basées sur les huit règles pour des biens communs réussis, inventées par E. Ostrom. Dans le chapitre 5, nous discutons de la manière dont les "huit règles" sont mises en œuvre dans l’EGM et le protocole DIP.
### [](#5_3structure_de_haut_niveau_de_legm)
5.3 Structure de haut niveau de l’EGM
Dans l’image ci-dessous, un certain nombre d’acteurs/participants sont mentionnés, les noms mentionnés sont écrits à titre d’exemple et il se peut que d’autres acteurs et/ou blockchain soient ajoutés. Dans cette image, les acteurs suivants sont mentionnés.

| Name | Short description |
| --- | --- |
| Decentralized Insurance Foundation | Development and promotion of the DIP protocol, funding of the development of the Generic Insurance Framework (GIF) |
| Kleros | Decentralized arbitration service and token curated registry |
| DAOstack | Software stack for DAOs including a library of governance protocols and interfaces for creating and managing DAOs |
| Mainnet | Example blockchain |
| Gnosis chain | Example blockchain |
| Avalanche | Example blockchain |
| Polygon | Example blockchain |
1. Les quatre aspects qui définissent l’EGM sont les suivants :
1. Les participants à la plateforme forment l’autorité suprême
2. La Fondation d’assurance décentralisée constitue un lien neutre et sans but lucratif avec les institutions et les systèmes juridiques du monde réel.
3. La certification des instances GIF est un mécanisme de signalisation du marché pour inciter à un niveau de travail élevé.
4. Le règlement des litiges a lieu via un conseil d’arbitrage indépendant
2. Les participants à la plateforme - qu’il s’agisse d’assurés, de créateurs de produits ou d’investisseurs - constituent l’autorité suprême de la plateforme. Leur participation est représentée par des token de gouvernance (vDIP), qui sont frappés contre la mise en jeu de DIP token dans un contrat de gouvernance. Les token de gouvernance (vDIP) sont utilisés pour la prise de décision dans toutes les DAO impliquées dans la plateforme.
3. Alors que les participants de la plateforme sont représentés par des adresses sur les protocoles de la blockchain, nous avons besoin d’un lien avec le monde réel reliant l’infrastructure on-chain aux entités juridiques du monde réel.
4. Dans le monde réel ("IRL"), l’autorité suprême est la Fondation d’assurance décentralisée (DIF) à but non lucratif, basée à Zoug, en Suisse, et régie par le droit suisse.
5. L’objet du DIF est défini dans l’acte notarié de la Fondation et ne peut être modifié :
_“L’objectif de la Fondation est de promouvoir et de développer de nouvelles technologies et applications, notamment dans les domaines des nouvelles architectures logicielles ouvertes et décentralisées principalement dans le domaine des assurances. Un accent dominant, mais non exclusif, est mis sur la promotion et le développement du protocole DIP et des technologies associées, ainsi que sur la promotion et le soutien des applications utilisant le protocole DIP”_
1. Par conséquent, le seul but de la Fondation est de servir la communauté des participants à la construction et à l’utilisation du protocole DIP.
2. Le DIF s’engage à une stricte neutralité. Par conséquent, le DIF ne s’engagera jamais dans des litiges entre participants. Pour le règlement des différends, la plateforme DIP utilisera les mécanismes existants, comme par exemple le conseil d’arbitrage de Kleros.
3. Le DIF est officiellement représenté par le Conseil de fondation.
4. La tâche principale du DIF dans le framework du protocole technique DIP est la certification des Instances GIF sur les différentes blockchains. Sur chaque blockchain, il peut y avoir plusieurs Instances GIF. Les règles de certification seront publiées.
Les règles doivent être telles que, si possible, sans ambiguïté dans leur interprétation. Les personnes ayant une compréhension technique de base et du bon sens doivent pouvoir décider si une Instance GIF particulière répond aux exigences.
Les exigences comprennent la stabilité technique (comme les audits de contrat) et la solidité, ainsi que la conformité juridique. Les Instances GIF certifiées sont enregistrées dans un registre (Token Curated Registry; TCR).
Les règles concrètes de certification des Instances GIF sont actuellement en cours d’élaboration.
5. La certification n’a aucune conséquence spécifique - elle signale simplement que "cette Instance GIF a fait l’objet d’un examen approfondi et d’une diligence raisonnable et qu’elle met en œuvre les règles et recommandations du protocole DIP". Ainsi, nous nous attendons à ce qu’une certification soit un facteur de différenciation fort sur le marché et que la non-certification soit essentiellement un "drapeau rouge" pour les clients et les investisseurs. C’est ainsi que fonctionne l’autorégulation. Toutefois, à l’avenir, d’autres parties extérieures à l’écosystème du DIP pourraient lier l’accès à certains services à des certificats valides.
6. Chaque Instance GIF est gérée par un Opérateur d’Instance. Un opérateur d’instance peut être représenté par une EOA (adresse appartenant à l’extérieur), un multisig ou un DAO. Il est recommandé que l’opérateur d’instance soit représenté par un DAO, dont les membres sont les parties prenantes de cette Instance GIF.
7. Chaque Instance GIF peut envoyer un délégué dans le Conseil consultatif du DIF. Le conseil consultatif interagit avec le conseil de fondation et représente les intérêts des Instances GIF et de ses parties prenantes auprès du conseil de fondation. Le conseil consultatif et ses processus de décision sont mis en œuvre en tant que DAO.
8. Chaque instance GIF (ou le DAO qui la représente) peut mettre en œuvre des règles de gouvernance à un niveau plus granulaire, par exemple des règles pour décider quels produits peuvent être listés sur l’instance et lesquels ne le peuvent pas, tant que ces règles sont conformes à nos valeurs fondamentales et aux autres règles de la plateforme.
9. Chaque Instance GIF doit mettre en œuvre des règles qui garantissent que l’instance est en mesure de participer au financement de l’EGM et du protocole DIP en général.
10. Les litiges sont résolus par un conseil d’arbitrage. Parmi les litiges possibles, citons par exemple l’enregistrement d’une instance GIF dans le RCT, ou les litiges liés à des demandes d’indemnisation qui ne peuvent être résolus par la logique des smart contracts (par exemple, un dysfonctionnement de l’oracle).
[](#5_4financement_de_legm_et_du_protocole_dip)
5.4 Financement de l’EGM et du protocole DIP
--------------------------------------------------------------------------------------------
1. L’infrastructure nécessaire au maintien de l’EGM, ainsi que le développement et la maintenance du protocole DIP (notamment le développement et la maintenance du GIF framework) nécessitent un financement.
2. Le financement est destiné à couvrir uniquement les coûts, à être autonome et à ne pas avoir de but lucratif.
3. Chaque Instance GIF devra donc :
1. Miser un montant défini de DIP token dans un contrat de staking de gouvernance.
2. Payer une cotisation régulière pour couvrir les coûts opérationnels de l’EGM.
4. Le montant requis des enjeux et des frais est calculé sur la base du volume économique qui est négocié sur l’instance particulière. Le schéma exact sera publié en temps voulu.
5. En cas de violation des règles, des sanctions de gravité différente peuvent être appliquées aux participants qui se comportent mal :
1. Sanctions financières pour les membres qui se comportent mal
2. Réduction des DIP token mis en jeu
3. Exclusion de participants d’une Instance GIF
4. Exclusion d’une Instance GIF du Registre des Tokens.
6. Une partie des frais payés sera brûlée pour créer un léger effet déflationniste sur le DIP token.
[](#5_5global_staking_pool)
5.5 Global staking pool
---------------------------------------------------
1. Le DIF gérera une global staking pool (GSP). Le GSP sera déployé sur le Mainnet d’Ethereum.
2. Le GSP a les objectifs suivants :
1. Fournir une incitation économique au bon comportement
2. Fournir un "puits" qui liera les DIP token
3. Veiller à ce que les participants qui profitent de l’écosystème Etherisc “jouent leur peau” et des intérêts alignés avec l’ensemble du système.
3. Les participants à l’écosystème Etherisc sont censés mettre en jeu et bloquer une certaine quantité de DIP token dans le GSP :
1. Les opérateurs d’Instance GIF doivent mettre en jeu et verrouiller des token pour chaque Instance GIF certifiée.
2. Les product owner doivent mettre en jeu et verrouiller des token pour chaque produit déployé et approuvé sur une Instance GIF certifiée.
3. Les fournisseurs Oracle doivent mettre en jeu et verrouiller les token pour chaque oracle déployé et approuvé sur une Instance GIF certifiée.
4. Les gardiens de risk pools doivent mettre en jeu et verrouiller les token pour chaque risk pool déployée et approuvée sur une Instance GIF certifiée.
5. Le staking dans le GSP est indépendant du staking dans les risk pools. Les investisseurs peuvent investir dans les risk pools sans avoir misé sur le GSP, et les règles définies dans ce chapitre ne leur sont pas appliquées.
4. Le montant à miser et à bloquer pour chaque groupe de participants sera publié sur le site Web d’Etherisc.
5. Le montant à miser et à bloquer sera en corrélation avec la valeur économique créée par le participant. Les KPIs exacts à prendre en compte et les formules de calcul du montant de DIP token à miser seront publiés sur le site d’Etherisc.
6. Les token mis en jeu dans le GSP peuvent être verrouillés par les metteurs en jeu à différentes fins :
1. Pour une Instance GIF (nécessaire pour le fonctionnement d’une Instance GIF)
2. Pour un produit (nécessaire au fonctionnement d’un produit)
3. Pour un oracle (nécessaire au fonctionnement d’un oracle)
4. Pour une risk pool de risques (nécessaire au fonctionnement d’une risk pool)
5. À des fins spécifiques de gouvernance (facultatif, pour participer à des décisions spécifiques de gouvernance)
7. Pour atteindre chaque objectif, un "Lock Manager" a le pouvoir de verrouiller ou de déverrouiller les token. Initialement, les gestionnaires de verrouillage sont contrôlés par un multisig appartenant au Conseil de fondation de la Fondation d’assurance décentralisée. Après une période de test, le contrôle sur les gestionnaires de verrouillage peut être transféré à la DAO associée à la Fondation d’assurance décentralisée.
8. Chaque participant qui a placé et verrouillé des DIP token se verra accorder des droits de vote généraux dans le modèle de gouvernance Etherisc. À des fins spécifiques, il peut être nécessaire de placer et de verrouiller des jtoken supplémentaires dans un gestionnaire de verrouillage de gouvernance. Pour chaque décision de gouvernance, les droits de vote sont calculés sur un snapshot du GSP à une certaine hauteur de bloc.
9. Le vote est effectué par Snapshot en utilisant une stratégie qui lit les tokens verrouillés dans le GSP à une certaine hauteur de bloc.
10. Le code du GSP est publié dans le global staking repo du github d’etherisc.
[](#5_6politique_monétaire_du_dif)
5.6 Politique monétaire du DIF
-----------------------------------------------------------------
1. En tant que principal détenteur de DIP token (environ 60 % de l’offre totale de DIP token), le DIF est tenu de protéger les intérêts des détenteurs de DIP token. La trésorerie du DIF n’est pas comptabilisée dans l’offre en circulation des DIP token.
2. Le DIF peut allouer des subventions ou fournir des DIP token pour encourager le développement et l’utilisation du protocole DIP. Ces subventions et incitations augmenteront l’offre en circulation et pourraient donc conduire à une dilution de la valeur du DIP token. Cependant, le DIF veillera toujours à ce que les subventions et les incitations soient toujours en rapport avec la valeur créée, afin que le DIP token dans son ensemble ne subisse pas de dilution inutile.
[](#5_7annexe_huit_règles_pour_des_biens_communs_réussis_et_comment_appliquer_ces_règles_dans_le_protocole_du_dip)
5.7 Annexe : Huit règles pour des biens communs réussis et comment appliquer ces règles dans le protocole du DIP
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Les lieux communs doivent avoir des limites clairement définies. En particulier sur la question de l’accessibilité. À moins qu’il n’y ait une communauté précise, cela devient accessible à tous, et ce n’est pas comme cela que les biens communs fonctionnent. Les "limites" sont mises en œuvre par le registre des tokens conservés pour les Instances GIF, et les registres des produits, des oracles et des risk pools dans les Instances GIF elles-mêmes.
2. Les règles doivent s’adapter aux circonstances locales. Il n’existe pas d’approche unique quant à la gestion des ressources communes. Les règles doivent être dictées par les populations locales et les besoins écologiques locaux. Les règles sont toujours créées selon le principe de subsidiarité. Par exemple, les règles de niveau supérieur régissent uniquement les instances GIF qui sont certifiées. Des règles plus granulaires sont mises en œuvre à des niveaux inférieurs et elles peuvent être différentes pour chaque Instance GIF, en fonction de leurs besoins.
3. La prise de décision participative est essentielle. Il existe toutes sortes de moyens d’y parvenir, mais les gens seront plus enclins à suivre les règles s’ils ont participé à leur rédaction. Il est nécessaire d’impliquer autant de personnes que possible dans la prise de décision. La participation est mise en œuvre par les DAO qui régissent les Instances GIF. Chaque Instance GIF est membre du Conseil consultatif du DIF et peut y représenter ses intérêts.
4. Les biens communs doivent être contrôlés. Une fois les règles établies, les communautés ont besoin d’un moyen de vérifier que les gens les respectent. Le fonctionnement des biens communs n’est pas basé sur la bonne volonté mais sur la responsabilité. Le contrôle se fait à deux niveaux : Le niveau supérieur est assuré par le DIF, le Token Curated Registry of GIF Instances et la commission d’arbitrage. À un niveau inférieur, le contrôle est assuré par les DAO qui régissent les instances GIF individuelles.
5. Les sanctions pour ceux qui abusent des biens communs devraient être graduelles. Ostrom a observé que les biens communs qui fonctionnent le mieux ne bannissent pas simplement les personnes qui enfreignent les règles. Cela avait tendance à créer du ressentiment. Ils avaient plutôt des systèmes d’avertissements et d’amendes, ainsi que des conséquences informelles sur la réputation de la communauté. Il existe différentes méthodes de sanction, chacune ayant un niveau de sévérité différent, voir chapitre 3.
6. La résolution des conflits doit être facilement accessible. Lorsque des problèmes surgissent, leur résolution doit être informelle, peu coûteuse et directe. Cela signifie que tout le monde peut soumettre ses problèmes à la médiation et que personne n’est exclu. Les problèmes doivent être résolus plutôt qu’ignorés à cause des frais de justice. Ceci est mis en œuvre par le conseil d’arbitrage qui offre une résolution des conflits à tous les niveaux.
7. Les communs nécessitent le droit de s’organiser. Les règles communes ne compteront pas si une autorité locale supérieure ne reconnaît pas leur légitimité. Ceci est mis en œuvre par les règles écrites qui régissent le DIF et qui, à leur tour, régissent les DAO représentant les différentes instances du GIF.
8. Les biens communs fonctionnent mieux lorsqu’ils sont imbriqués dans des réseaux plus vastes. Certaines choses peuvent être gérées localement, mais d’autres peuvent nécessiter une coopération régionale plus large - par exemple, un réseau d’irrigation peut dépendre d’une rivière que d’autres utilisent également en amont. Ceci est mis en œuvre par la structure hiérarchique, au sommet de laquelle se trouve une fondation juridique reconnue par la loi suisse.
[](#6_glossaire_et_abréviations)
6 Glossaire et abréviations
============================================================
[](#6_1_termes_utilisés_de_langlais)
6.1 Termes utilisés de l’anglais
---------------------------------------------------------------------
| Dénomination anglaise | Dénomination française |
| --- | --- |
| Blockchain | Chaîne de blocs |
| Component | Composant |
| Component owner | Propriétaire du composant |
| DIP token | Le jeton DIP |
| Decentralized insurance | Insurance which is run by a decentralized network |
| DIP token | Please have a look in the abbreviations |
| Ecosystem | Écosystème |
| Global staking pool | Piscine globale de staking |
| Instance operator | Opérateur d’instance |
| Investor | Investisseur |
| Legal framework | Cadre juridique |
| Oracle owner | Propriétaire d’Oracle |
| Primary risk pool | Piscine de risques primaire |
| Secondary risk pool | Piscine de risques socondaire |
| Product owner | Propriétaire du produit |
| Investor | Investors bring in risk capital in risk pools or risk bundles in return for intest payments |
| Risk pool keeper | Gardien du pool de risques |
| Risk pool NFT | NFT de la piscine des risques |
| Smart contract | Contrat intelligent |
| Stablecoins | Jetons stables |
| The elevator pitch | Le discours de l’ascenseur |
[](#6_2_explications_des_termes_techniques)
6.2 Explications des termes techniques
----------------------------------------------------------------------------------
| Notion | Dénomination française | Explication / Définition |
| --- | --- | --- |
| Black swan event | Événement cygne noir | Un événement rare mais catastrophique/ Un événement qui surprend, qui a un effet majeur et qui est souvent rationalisé de manière inappropriée après coup avec le bénéfice du recul. |
| Collateralization | Collatéralisation | Le processus de garantie d’un prêt avec un actif de valeur/ L’utilisation d’un actif de valeur comme garantie pour garantir un prêt. |
| Decentralized Insurance | Assurance décentralisée | Une assurance qui est gérée par un réseau décentralisé. |
| Ecosystem | Écosystème | Un système cohérent de participants et de ressources, qui sert un certain objectif. |
| Etherisc platform | Plate-forme Etherisc | L’ensemble des participants, des parties prenantes, des règles, des techniques, des protocoles, du système logiciel, de smart contracts, qui constituent l’écosystème d’Etherisc. |
| Float of liquidity | Float de la liquidité | Le montant moyen des liquidités qui ne sont pas nécessaires pour les créances. |
| GIF (Generic Insurance Framework) | GIF (Cadre Générique de L’assurance) | Soit le GIF ou le framework générique d’assurance. |
| Insurance | Assurance | Un moyen de protection contre les pertes financières/ Une forme de gestion des risques, principalement utilisée pour se couvrir contre le risque d’une perte éventuelle ou incertaine. |
| Long tail risks | Risques de longue traîne | Risques élevés non plausibles représentés par la "longue queue" de la courbe de distribution des risques. |
| P2P-insurance models | Modèles d’assurance P2P | Un petit groupe d’individus ayant un intérêt commun qui combinent leurs primes pour s’assurer contre les risques. |
| Parametric Insurance | Assurance paramétrique | Une assurance où le processus de règlement des sinistres est piloté par les données. |
| Premium | Prime | Montant d’argent pour acheter une police d’assurance. |
| Protocol token | Jeton de protocole | Un token qui sécurise ou active un protocole. |
| Risk pool | Piscine de risques | Un contrat intelligent qui collecte les fonds utilisés pour indemniser les sinistres d’assurance. |
| Risk pool token | Tokens de piscine de risque | Une classe de token similaires, un pour chaque pool de risques, qui représentent les risques. |
| Smart contract | Contrat intelligent | Un programme stocké sur une chaîne de blocs qui s’exécute lorsque des conditions prédéterminées sont remplies. |
| Stablecoin | Jeton stable | Une crypto-monnaie conçue pour avoir un prix relativement stable, généralement en étant rattachée à une marchandise ou à une monnaie ou en ayant son offre régulée par un algorithme. |
| Staking | Staking | Le processus de verrouillage par les investisseurs d’un certain montant de DIP token pour lever des capitaux soutenant les garanties techniques. |
| Tragedy of the commons | La tragédie des biens communs | Un problème social et politique dans lequel chaque individu est incité à agir d’une manière qui, en fin de compte, sera nuisible à tous les individus. Selon Elinor Ostrom, ce problème peut être résolu. |
| Transaction costs | Coûts de transaction | Coût pour effectuer une transaction économique (à ne pas confondre avec les frais de transaction). |
[](#6_3_abréviations)
6.3 Abréviations
--------------------------------------
| Acronymes et abréviations | Explication / Définition anglais | Explication / Définition français |
| --- | --- | --- |
| DAO | Decentralized autonomous organization | Organisation autonome décentralisée |
| dAPP | Decentralized application | Application décentralisée |
| DIF | Decentralized Insurance Foundation | Fondation d’assurance décentralisée |
| DIP Token | Decentralized Insurance Protocol token | Protocol token d’assurance décentralisé |
| EGM | Etherisc Governance Model | Modèle de gouvernance d’Etherisc |
| EOA | Externally owned address | Adresse appartenant à l’extérieur |
| GIF | Generic Insurance Framework | Framework générique de l’assurance |
| GSP | Global staking pool | Piscine globale de staking |
| KPI | Key performance indicator | Indicateur clé de performance |
| NFT | Non fungible token | Token non fongible |
| P2P | Peer-to-peer | Pair à pair |
| PRP | Primary risk pool | Piscine de risque primaire |
| SRP | Secondary risk pool | Piscine de risque secondaire |
* * *
[1](#_footnoteref_1)
. [https://en.wikipedia.org/wiki/Insurance](https://en.wikipedia.org/wiki/Insurance)
[2](#_footnoteref_2)
. [https://paytm.com/blog/insurance/what-is-insurance-definition-benefits-and-types/](https://paytm.com/blog/insurance/what-is-insurance-definition-benefits-and-types/)
[3](#_footnoteref_3)
. Allstate.com: What Perils Are Typically Covered By A Homeowners Insurance Policy?
[4](#_footnoteref_4)
. [https://en.wikipedia.org/wiki/Law\_of\_large\_numbers](https://en.wikipedia.org/wiki/Law_of_large_numbers)
[5](#_footnoteref_5)
. [http://www.npr.org/sections/money/2010/03/warren\_buffett\_explains\_the\_ge.html](http://www.npr.org/sections/money/2010/03/warren_buffett_explains_the_ge.html)
[6](#_footnoteref_6)
. $100 for covering the risk against $120 premium ⇒ 100/120 loss ratio = 83%
[7](#_footnoteref_7)
. The downside of this is the fact that inefficiencies tend to hide in the organization. The bigger the organization, the fewer the people doing real work (people at the “rim” of the organization) and the more people are needed in the center to organize the people at the rim (the “management”). Furthermore, to limit internal inefficiencies, companies need a plethora of control mechanisms (that’s the old style) or complicated incentive systems (that’s the more modern way)
[8](#_footnoteref_8)
. [https://assets.kpmg.com/content/dam/kpmg/au/pdf/2016/general-insurance-industry-review-2016.pdf](https://assets.kpmg.com/content/dam/kpmg/au/pdf/2016/general-insurance-industry-review-2016.pdf)
[9](#_footnoteref_9)
. There is a fourth element - reinsurance. The purpose of reinsurance is to reduce the cost of risk diversification by categorizing and securitizing different risks. Reinsurance and “wholesale” risk transfer enabled by reinsurance adds another layer of complexity, and therefore we won’t discuss reinsurance in this paper.
[10](#_footnoteref_10)
. Some blockchains, like Ethereum (which we use), enable programs (called “smart contracts”) that are uncensorable, immutable, and permanent. These smart contracts can interact with each other to perform a wide variety of actions, including financial and escrow transactions. This makes possible direct and transparent interactions between two parties who may be and may remain anonymous, that previously required a third-party intermediary to be effective. The term was originally coined by Nick Szabo, but in a slightly different meaning. Note: The above definition was thankfully supplied by Ron Bernstein, who was not successful in finding the original author - please contact us if you are the author.
[11](#_footnoteref_11)
. Network effect is described as the effect that one user of a good or service has on the value of that product to other people. The classical example is the telephone: the more people use it, the more valuable the telephone is for all.
[12](#_footnoteref_12)
. We use the term “company” here for easier reading. Of course, in DeFi/blockchain applications, a “company” can also be a DAO or a simple blockchain address (EOA)!
[13](#_footnoteref_13)
. [https://en.wikipedia.org/wiki/Elinor\_Ostrom](https://en.wikipedia.org/wiki/Elinor_Ostrom)
; see also [https://www.onthecommons.org/magazine/elinor-ostroms-8-principles-managing-commmons](https://www.onthecommons.org/magazine/elinor-ostroms-8-principles-managing-commmons)
---
# Unpermissioned example components - Etherisc Docs
Unpermissioned example components
=================================
This directory contains a set of unpermissioned example compoents that are mainly used for testing purposes. The expose all the available functions of the component without requiring any permissions (and thereby setup) to use them.
Components that are built in such a way should never be used in production, as they expose functions that can move tokens or other assets without any authorization.
[](#contracts)
Contracts
------------------------
### [](#SimpleDistribution)
`SimpleDistribution`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/unpermissioned/SimpleDistribution.sol)
import "@etherisc/gif-next/contracts/examples/unpermissioned/SimpleDistribution.sol";
Functions
* \[`constructor(registry, productNftId, authorization, initialOwner)`\]
* \[`initialize(registry, productNftId, authorization, initialOwner, name)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setLocked(locked)`\]
* \[`setWallet(newWallet)`\]
* \[`createReferral2(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
BasicDistribution
* \[`setFees(distributionFee, minDistributionOwnerFee)`\]
* \[`createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`createDistributor(distributor, distributorType, data)`\]
* \[`changeDistributorType(distributorNftId, distributorType, data)`\]
* \[`createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`_initializeBasicDistribution(registry, instanceNftId, authorization, initialOwner, name)`\]
Distribution
* \[`processRenewal(referralId, feeAmount)`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
* \[`getDiscountPercentage(referralCode)`\]
* \[`getReferralId(referralCode)`\]
* \[`calculateRenewalFeeAmount(, netPremiumAmount)`\]
* \[`isVerifying()`\]
* \[`__Distribution_init(registry, productNftId, authorization, isInterceptor, initialOwner, name)`\]
* \[`_setFees(distributionFee, minDistributionOwnerFee)`\]
* \[`_createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`_createDistributor(distributor, distributorType, data)`\]
* \[`_changeDistributorType(distributorNftId, distributorType, data)`\]
* \[`_createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`_withdrawCommission(distributorNftId, amount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#SimpleDistribution-constructor-address-NftId-contract-IAuthorization-address-)
`constructor(address registry, NftId productNftId, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimpleDistribution-initialize-address-NftId-contract-IAuthorization-address-string-)
`initialize(address registry, NftId productNftId, contract IAuthorization authorization, address initialOwner, string name)` public
#### [](#SimpleDistribution-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
#### [](#SimpleDistribution-setLocked-bool-)
`setLocked(bool locked)` external
#### [](#SimpleDistribution-setWallet-address-)
`setWallet(address newWallet)` external
#### [](#SimpleDistribution-createReferral2-NftId-string-UFixed-uint32-Timestamp-bytes-)
`createReferral2(NftId distributorNftId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt, bytes data) → ReferralId referralId` external
create referral codes. This is required for testing only to provide a distributor that is not the message sender.
### [](#SimpleOracle)
`SimpleOracle`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/unpermissioned/SimpleOracle.sol)
import "@etherisc/gif-next/contracts/examples/unpermissioned/SimpleOracle.sol";
Functions
* \[`constructor(registry, productNftId, authorization, initialOwner)`\]
* \[`initialize(registry, productNftId, authorization, initialOwner, name)`\]
* \[`_request(requestId, requesterId, requestData, expiryAt)`\]
* \[`_cancel(requestId)`\]
* \[`respondAsync(requestId, responseText, revertInCall, revertUntil)`\]
* \[`_respondSync(requestId)`\]
BasicOracle
* \[`respond(requestId, responseData)`\]
* \[`_initializeBasicOracle(registry, instanceNftId, authorization, initialOwner, name)`\]
Oracle
* \[`request(requestId, requesterId, requestData, expiryAt)`\]
* \[`cancel(requestId)`\]
* \[`isVerifying()`\]
* \[`withdrawFees()`\]
* \[`activeRequests()`\]
* \[`getActiveRequest(idx)`\]
* \[`isActiveRequest(requestId)`\]
* \[`__Oracle_init(registry, productNftId, authorization, initialOwner, name)`\]
* \[`_respond(requestId, responseData)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
* \[`LogSimpleOracleRequestReceived(requestId, requesterId, synchronous, requestText)`\]
* \[`LogSimpleOracleCancellingReceived(requestId)`\]
* \[`LogSimpleOracleAsyncResponseSent(requestId, responseText)`\]
* \[`LogSimpleOracleSyncResponseSent(requestId, responseText)`\]
IOracleComponent
* \[`LogOracleRequestReceived(requestId, requesterId)`\]
* \[`LogOracleRequestCancelled(requestId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#SimpleOracle-constructor-address-NftId-contract-IAuthorization-address-)
`constructor(address registry, NftId productNftId, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimpleOracle-initialize-address-NftId-contract-IAuthorization-address-string-)
`initialize(address registry, NftId productNftId, contract IAuthorization authorization, address initialOwner, string name)` public
#### [](#SimpleOracle-_request-RequestId-NftId-bytes-Timestamp-)
`_request(RequestId requestId, NftId requesterId, bytes requestData, Timestamp expiryAt)` internal
use case specific handling of oracle requests for now only log is emitted to verify that request has been received by oracle component
#### [](#SimpleOracle-_cancel-RequestId-)
`_cancel(RequestId requestId)` internal
use case specific handling of oracle requests for now only log is emitted to verify that cancelling has been received by oracle component
#### [](#SimpleOracle-respondAsync-RequestId-string-bool-Timestamp-)
`respondAsync(RequestId requestId, string responseText, bool revertInCall, Timestamp revertUntil)` external
#### [](#SimpleOracle-_respondSync-RequestId-)
`_respondSync(RequestId requestId)` internal
#### [](#SimpleOracle-LogSimpleOracleRequestReceived-RequestId-NftId-bool-string-)
`LogSimpleOracleRequestReceived(RequestId requestId, NftId requesterId, bool synchronous, string requestText)` event
#### [](#SimpleOracle-LogSimpleOracleCancellingReceived-RequestId-)
`LogSimpleOracleCancellingReceived(RequestId requestId)` event
#### [](#SimpleOracle-LogSimpleOracleAsyncResponseSent-RequestId-string-)
`LogSimpleOracleAsyncResponseSent(RequestId requestId, string responseText)` event
#### [](#SimpleOracle-LogSimpleOracleSyncResponseSent-RequestId-string-)
`LogSimpleOracleSyncResponseSent(RequestId requestId, string responseText)` event
### [](#SimplePool)
`SimplePool`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/unpermissioned/SimplePool.sol)
import "@etherisc/gif-next/contracts/examples/unpermissioned/SimplePool.sol";
Functions
* \[`constructor(registry, productNftId, poolInfo, authorization, initialOwner)`\]
* \[`initialize(registry, productNftId, poolInfo, authorization, initialOwner)`\]
* \[`createBundle(fee, initialAmount, lifetime, filter)`\]
* \[`fundPoolWallet(amount)`\]
* \[`defundPoolWallet(amount)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setLocked(locked)`\]
* \[`setWallet(newWallet)`\]
BasicPool
* \[`_initializeBasicPool(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`stake(bundleNftId, amount)`\]
* \[`unstake(bundleNftId, amount)`\]
* \[`extend(bundleNftId, lifetimeExtension)`\]
* \[`setBundleLocked(bundleNftId, locked)`\]
* \[`closeBundle(bundleNftId)`\]
* \[`setBundleFee(bundleNftId, fee)`\]
* \[`withdrawBundleFees(bundleNftId, amount)`\]
* \[`setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`setFees(poolFee, stakingFee, performanceFee)`\]
Pool
* \[`getContractLocation(name)`\]
* \[`verifyApplication(applicationNftId, bundleNftId, collateralizationAmount)`\]
* \[`processConfirmedClaim(policyNftId, claimId, amount)`\]
* \[`applicationMatchesBundle(applicationNftId, applicationData, bundleNftId, bundleFilter, collateralizationAmount)`\]
* \[`getInitialPoolInfo()`\]
* \[`__Pool_init(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`_setPoolFees(poolFee, stakingFee, performanceFee)`\]
* \[`_setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`_fundPoolWallet(amount)`\]
* \[`_defundPoolWallet(amount)`\]
* \[`_createBundle(bundleOwner, fee, lifetime, filter)`\]
* \[`_setBundleFee(bundleNftId, fee)`\]
* \[`_stake(bundleNftId, amount)`\]
* \[`_unstake(bundleNftId, amount)`\]
* \[`_extend(bundleNftId, lifetimeExtension)`\]
* \[`_setBundleLocked(bundleNftId, locked)`\]
* \[`_closeBundle(bundleNftId)`\]
* \[`_withdrawBundleFees(bundleNftId, amount)`\]
* \[`_processFundedClaim(policyNftId, claimId, availableAmount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IPoolComponent
* \[`LogPoolVerifiedByPool(pool, applicationNftId, collateralizationAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#SimplePool-constructor-address-NftId-struct-IComponents-PoolInfo-contract-IAuthorization-address-)
`constructor(address registry, NftId productNftId, struct IComponents.PoolInfo poolInfo, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimplePool-initialize-address-NftId-struct-IComponents-PoolInfo-contract-IAuthorization-address-)
`initialize(address registry, NftId productNftId, struct IComponents.PoolInfo poolInfo, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimplePool-createBundle-struct-Fee-uint256-Seconds-bytes-)
`createBundle(struct Fee fee, uint256 initialAmount, Seconds lifetime, bytes filter) → NftId bundleNftId, uint256 netStakedAmountInt` external
#### [](#SimplePool-fundPoolWallet-Amount-)
`fundPoolWallet(Amount amount)` external
#### [](#SimplePool-defundPoolWallet-Amount-)
`defundPoolWallet(Amount amount)` external
#### [](#SimplePool-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
#### [](#SimplePool-setLocked-bool-)
`setLocked(bool locked)` external
#### [](#SimplePool-setWallet-address-)
`setWallet(address newWallet)` external
### [](#SimpleProduct)
`SimpleProduct`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/unpermissioned/SimpleProduct.sol)
import "@etherisc/gif-next/contracts/examples/unpermissioned/SimpleProduct.sol";
Functions
* \[`constructor(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`initialize(registry, instanceNftid, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`createRisk(id, data)`\]
* \[`updateRisk(id, data)`\]
* \[`setRiskLocked(id, locked)`\]
* \[`closeRisk(id)`\]
* \[`createApplication(applicationOwner, riskId, sumInsured, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`createApplication2(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`revoke(applicationNftId)`\]
* \[`createPolicy(applicationNftId, requirePremiumPayment, activateAt)`\]
* \[`createPolicy2(applicationNftId, requirePremiumPayment, activateAt, maxPremiumAmount)`\]
* \[`decline(policyNftId)`\]
* \[`expire(policyNftId, expireAt)`\]
* \[`collectPremium(policyNftId, activateAt)`\]
* \[`activate(policyNftId, activateAt)`\]
* \[`adjustActivation(policyNftId, activateAt)`\]
* \[`close(policyNftId)`\]
* \[`submitClaim(policyNftId, claimAmount, submissionData)`\]
* \[`revokeClaim(policyNftId, claimId)`\]
* \[`confirmClaim(policyNftId, claimId, confirmedAmount, processData)`\]
* \[`declineClaim(policyNftId, claimId, processData)`\]
* \[`cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`createPayout(policyNftId, claimId, amount, data)`\]
* \[`cancelPayout(policyNftId, payoutId)`\]
* \[`createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`processPayout(policyNftId, payoutId)`\]
* \[`createOracleRequest(oracleNftId, requestText, expiryAt, synchronous)`\]
* \[`createOracleRequest2(oracleNftId, requestText, expiryAt, synchronous, callbackMethod)`\]
* \[`cancelOracleRequest(requestId)`\]
* \[`fulfillOracleRequestSync(requestId, responseData)`\]
* \[`fulfillOracleRequestAsync(requestId, responseData)`\]
* \[`resend(requestId)`\]
* \[`doSomethingOnlyWhenActive()`\]
* \[`getOracleService()`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setLocked(locked)`\]
* \[`setWallet(newWallet)`\]
BasicProduct
* \[`setFees(productFee, processingFee)`\]
* \[`_initializeBasicProduct(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
Product
* \[`registerComponent(component)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`calculatePremium(sumInsuredAmount, riskId, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`calculateNetPremium(sumInsuredAmount, , , )`\]
* \[`getInitialProductInfo()`\]
* \[`getInitialFeeInfo()`\]
* \[`__Product_init(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`_setFees(productFee, processingFee)`\]
* \[`_createRisk(id, data)`\]
* \[`_updateRisk(id, data)`\]
* \[`_setRiskLocked(id, locked)`\]
* \[`_closeRisk(id)`\]
* \[`_createApplication(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`_revoke(applicationNftId)`\]
* \[`_createPolicy(applicationNftId, activateAt, maxPremiumAmount)`\]
* \[`_decline(policyNftId)`\]
* \[`_expire(policyNftId, expireAt)`\]
* \[`_adjustActivation(policyNftId, activateAt)`\]
* \[`_collectPremium(policyNftId, activateAt)`\]
* \[`_activate(policyNftId, activateAt)`\]
* \[`_close(policyNftId)`\]
* \[`_submitClaim(policyNftId, claimAmount, claimData)`\]
* \[`_revokeClaim(policyNftId, claimId)`\]
* \[`_confirmClaim(policyNftId, claimId, confirmedAmount, data)`\]
* \[`_declineClaim(policyNftId, claimId, data)`\]
* \[`_cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`_createPayout(policyNftId, claimId, amount, data)`\]
* \[`_createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`_processPayout(policyNftId, payoutId)`\]
* \[`_cancelPayout(policyNftId, payoutId)`\]
* \[`_getProductStorage()`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
* \[`LogSimpleProductRequestAsyncFulfilled(requestId, responseText, responseDataLength)`\]
* \[`LogSimpleProductRequestSyncFulfilled(requestId, responseText, responseDataLength)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#SimpleProduct-constructor-address-NftId-string-struct-IComponents-ProductInfo-struct-IComponents-FeeInfo-contract-IAuthorization-address-)
`constructor(address registry, NftId instanceNftId, string name, struct IComponents.ProductInfo productInfo, struct IComponents.FeeInfo feeInfo, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimpleProduct-initialize-address-NftId-string-struct-IComponents-ProductInfo-struct-IComponents-FeeInfo-contract-IAuthorization-address-)
`initialize(address registry, NftId instanceNftid, string name, struct IComponents.ProductInfo productInfo, struct IComponents.FeeInfo feeInfo, contract IAuthorization authorization, address initialOwner)` public
#### [](#SimpleProduct-createRisk-string-bytes-)
`createRisk(string id, bytes data) → RiskId` public
#### [](#SimpleProduct-updateRisk-RiskId-bytes-)
`updateRisk(RiskId id, bytes data)` public
#### [](#SimpleProduct-setRiskLocked-RiskId-bool-)
`setRiskLocked(RiskId id, bool locked)` public
#### [](#SimpleProduct-closeRisk-RiskId-)
`closeRisk(RiskId id)` public
#### [](#SimpleProduct-createApplication-address-RiskId-uint256-Seconds-bytes-NftId-ReferralId-)
`createApplication(address applicationOwner, RiskId riskId, uint256 sumInsured, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → NftId nftId` public
#### [](#SimpleProduct-createApplication2-address-RiskId-Amount-Amount-Seconds-bytes-NftId-ReferralId-)
`createApplication2(address applicationOwner, RiskId riskId, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → NftId nftId` public
#### [](#SimpleProduct-revoke-NftId-)
`revoke(NftId applicationNftId)` public
#### [](#SimpleProduct-createPolicy-NftId-bool-Timestamp-)
`createPolicy(NftId applicationNftId, bool requirePremiumPayment, Timestamp activateAt)` public
#### [](#SimpleProduct-createPolicy2-NftId-bool-Timestamp-Amount-)
`createPolicy2(NftId applicationNftId, bool requirePremiumPayment, Timestamp activateAt, Amount maxPremiumAmount)` public
#### [](#SimpleProduct-decline-NftId-)
`decline(NftId policyNftId)` public
#### [](#SimpleProduct-expire-NftId-Timestamp-)
`expire(NftId policyNftId, Timestamp expireAt) → Timestamp` public
#### [](#SimpleProduct-collectPremium-NftId-Timestamp-)
`collectPremium(NftId policyNftId, Timestamp activateAt)` public
#### [](#SimpleProduct-activate-NftId-Timestamp-)
`activate(NftId policyNftId, Timestamp activateAt)` public
#### [](#SimpleProduct-adjustActivation-NftId-Timestamp-)
`adjustActivation(NftId policyNftId, Timestamp activateAt)` public
#### [](#SimpleProduct-close-NftId-)
`close(NftId policyNftId)` public
#### [](#SimpleProduct-submitClaim-NftId-Amount-bytes-)
`submitClaim(NftId policyNftId, Amount claimAmount, bytes submissionData) → ClaimId` public
#### [](#SimpleProduct-revokeClaim-NftId-ClaimId-)
`revokeClaim(NftId policyNftId, ClaimId claimId)` public
#### [](#SimpleProduct-confirmClaim-NftId-ClaimId-Amount-bytes-)
`confirmClaim(NftId policyNftId, ClaimId claimId, Amount confirmedAmount, bytes processData)` public
#### [](#SimpleProduct-declineClaim-NftId-ClaimId-bytes-)
`declineClaim(NftId policyNftId, ClaimId claimId, bytes processData)` public
#### [](#SimpleProduct-cancelConfirmedClaim-NftId-ClaimId-)
`cancelConfirmedClaim(NftId policyNftId, ClaimId claimId)` public
#### [](#SimpleProduct-createPayout-NftId-ClaimId-Amount-bytes-)
`createPayout(NftId policyNftId, ClaimId claimId, Amount amount, bytes data) → PayoutId` public
#### [](#SimpleProduct-cancelPayout-NftId-PayoutId-)
`cancelPayout(NftId policyNftId, PayoutId payoutId)` public
#### [](#SimpleProduct-createPayoutForBeneficiary-NftId-ClaimId-Amount-address-bytes-)
`createPayoutForBeneficiary(NftId policyNftId, ClaimId claimId, Amount amount, address beneficiary, bytes data) → PayoutId` public
#### [](#SimpleProduct-processPayout-NftId-PayoutId-)
`processPayout(NftId policyNftId, PayoutId payoutId) → Amount netPayoutAmount, Amount processingFeeAmount` public
#### [](#SimpleProduct-createOracleRequest-NftId-string-Timestamp-bool-)
`createOracleRequest(NftId oracleNftId, string requestText, Timestamp expiryAt, bool synchronous) → RequestId` public
#### [](#SimpleProduct-createOracleRequest2-NftId-string-Timestamp-bool-string-)
`createOracleRequest2(NftId oracleNftId, string requestText, Timestamp expiryAt, bool synchronous, string callbackMethod) → RequestId` public
#### [](#SimpleProduct-cancelOracleRequest-RequestId-)
`cancelOracleRequest(RequestId requestId)` public
#### [](#SimpleProduct-fulfillOracleRequestSync-RequestId-bytes-)
`fulfillOracleRequestSync(RequestId requestId, bytes responseData)` public
#### [](#SimpleProduct-fulfillOracleRequestAsync-RequestId-bytes-)
`fulfillOracleRequestAsync(RequestId requestId, bytes responseData)` public
#### [](#SimpleProduct-resend-RequestId-)
`resend(RequestId requestId)` public
#### [](#SimpleProduct-doSomethingOnlyWhenActive--)
`doSomethingOnlyWhenActive() → bool` public
#### [](#SimpleProduct-getOracleService--)
`getOracleService() → contract IOracleService` public
#### [](#SimpleProduct-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
#### [](#SimpleProduct-setLocked-bool-)
`setLocked(bool locked)` external
#### [](#SimpleProduct-setWallet-address-)
`setWallet(address newWallet)` external
#### [](#SimpleProduct-LogSimpleProductRequestAsyncFulfilled-RequestId-string-uint256-)
`LogSimpleProductRequestAsyncFulfilled(RequestId requestId, string responseText, uint256 responseDataLength)` event
#### [](#SimpleProduct-LogSimpleProductRequestSyncFulfilled-RequestId-string-uint256-)
`LogSimpleProductRequestSyncFulfilled(RequestId requestId, string responseText, uint256 responseDataLength)` event
[← examples/fire](/gif-next/3.x/api/examples/fire)
---
# Distribution - Etherisc Docs
Distribution
============
Contains interfaces and contracts related to distribution.
[](#contracts)
Contracts
------------------------
### [](#IDistributionComponent)
`IDistributionComponent`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/IDistributionComponent.sol)
import "@etherisc/gif-next/contracts/distribution/IDistributionComponent.sol";
Functions
* \[`getDiscountPercentage(referralCode)`\]
* \[`getReferralId(referralCode)`\]
* \[`calculateRenewalFeeAmount(referralId, netPremiumAmount)`\]
* \[`processRenewal(referralId, feeAmount)`\]
* \[`isVerifying()`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
IInstanceLinkedComponent
* \[`withdrawFees(amount)`\]
* \[`getInstance()`\]
IAuthorizedComponent
* \[`getAuthorization()`\]
IComponent
* \[`getName()`\]
* \[`getToken()`\]
* \[`getTokenHandler()`\]
* \[`getWallet()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
ITransferInterceptor
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IDistributionComponent-getDiscountPercentage-string-)
`getDiscountPercentage(string referralCode) → UFixed discountPercentage, ReferralStatus status` external
#### [](#IDistributionComponent-getReferralId-string-)
`getReferralId(string referralCode) → ReferralId referralId` external
#### [](#IDistributionComponent-calculateRenewalFeeAmount-ReferralId-uint256-)
`calculateRenewalFeeAmount(ReferralId referralId, uint256 netPremiumAmount) → uint256 feeAmount` external
#### [](#IDistributionComponent-processRenewal-ReferralId-uint256-)
`processRenewal(ReferralId referralId, uint256 feeAmount)` external
Callback function to process a renewal of a policy. The default implementation is empty. Overwrite this function to implement a use case specific behaviour.
#### [](#IDistributionComponent-isVerifying--)
`isVerifying() → bool verifying` external
Returns true to ensure component is called when transferring distributor Nft Ids.
#### [](#IDistributionComponent-withdrawCommission-NftId-Amount-)
`withdrawCommission(NftId distributorNftId, Amount amount) → Amount withdrawnAmount` external
Withdraw commission for the distributor
### [](#IDistributionService)
`IDistributionService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/IDistributionService.sol)
import "@etherisc/gif-next/contracts/distribution/IDistributionService.sol";
Functions
* \[`createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`createDistributor(distributor, distributorType, data)`\]
* \[`changeDistributorType(distributorNftId, newDistributorType, data)`\]
* \[`createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`processReferral(distributionNftId, referralId)`\]
* \[`processSale(distributionNftId, referralId, premium)`\]
* \[`referralIsValid(distributorNftId, referralId)`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
* \[`getDiscountPercentage(instanceReader, referralId)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogDistributionServiceCommissionWithdrawn(distributorNftId, recipient, amount, tokenAddress)`\]
* \[`LogDistributionServiceDistributorTypeCreated(distributionNftId, distributorType, name, commissionPercentage)`\]
* \[`LogDistributionServiceDistributorCreated(distributionNftId, distributorNftId, distributor, distributorType)`\]
* \[`LogDistributionServiceDistributorTypeChanged(distributorNftId, oldDistributorType, newDistributorType)`\]
* \[`LogDistributionServiceReferralCreated(distributorNftId, referralId, code, discountPercentage, maxReferrals, expiryAt)`\]
* \[`LogDistributionServiceReferralProcessed(distributorNftId, referralId, usedReferrals)`\]
* \[`LogDistributionServiceSaleProcessed(distributionNftId, premium, distributionOwnerFee)`\]
* \[`LogDistributionServiceSaleProcessedWithReferral(distributionNftId, distributorNftId, referralId, numPoliciesSold, premium, distributionOwnerFee, commissionAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IDistributionService-createDistributorType-string-UFixed-UFixed-UFixed-uint32-Seconds-bool-bool-bytes-)
`createDistributorType(string name, UFixed minDiscountPercentage, UFixed maxDiscountPercentage, UFixed commissionPercentage, uint32 maxReferralCount, Seconds maxReferralLifetime, bool allowSelfReferrals, bool allowRenewals, bytes data) → DistributorType distributorType` external
#### [](#IDistributionService-createDistributor-address-DistributorType-bytes-)
`createDistributor(address distributor, DistributorType distributorType, bytes data) → NftId distributorNftId` external
#### [](#IDistributionService-changeDistributorType-NftId-DistributorType-bytes-)
`changeDistributorType(NftId distributorNftId, DistributorType newDistributorType, bytes data)` external
#### [](#IDistributionService-createReferral-NftId-string-UFixed-uint32-Timestamp-bytes-)
`createReferral(NftId distributorNftId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt, bytes data) → ReferralId referralId` external
#### [](#IDistributionService-processReferral-NftId-ReferralId-)
`processReferral(NftId distributionNftId, ReferralId referralId)` external
callback from product service when a referral is used. Calling this will increment the referral usage counter.
#### [](#IDistributionService-processSale-NftId-ReferralId-struct-IPolicy-PremiumInfo-)
`processSale(NftId distributionNftId, ReferralId referralId, struct IPolicy.PremiumInfo premium)` external
callback from product service when selling a policy for a specific referralId
#### [](#IDistributionService-referralIsValid-NftId-ReferralId-)
`referralIsValid(NftId distributorNftId, ReferralId referralId) → bool isValid` external
#### [](#IDistributionService-withdrawCommission-NftId-Amount-)
`withdrawCommission(NftId distributorNftId, Amount amount) → Amount withdrawnAmount` external
Withdraw commission for the distributor
#### [](#IDistributionService-getDiscountPercentage-contract-InstanceReader-ReferralId-)
`getDiscountPercentage(contract InstanceReader instanceReader, ReferralId referralId) → UFixed discountPercentage, ReferralStatus status` external
Returns the discount percentage for the provided referral code. The function retuns both the percentage and the status of the referral code.
#### [](#IDistributionService-LogDistributionServiceCommissionWithdrawn-NftId-address-Amount-address-)
`LogDistributionServiceCommissionWithdrawn(NftId indexed distributorNftId, address indexed recipient, Amount amount, address indexed tokenAddress)` event
#### [](#IDistributionService-LogDistributionServiceDistributorTypeCreated-NftId-DistributorType-string-UFixed-)
`LogDistributionServiceDistributorTypeCreated(NftId indexed distributionNftId, DistributorType indexed distributorType, string name, UFixed commissionPercentage)` event
#### [](#IDistributionService-LogDistributionServiceDistributorCreated-NftId-NftId-address-DistributorType-)
`LogDistributionServiceDistributorCreated(NftId indexed distributionNftId, NftId indexed distributorNftId, address indexed distributor, DistributorType distributorType)` event
#### [](#IDistributionService-LogDistributionServiceDistributorTypeChanged-NftId-DistributorType-DistributorType-)
`LogDistributionServiceDistributorTypeChanged(NftId indexed distributorNftId, DistributorType indexed oldDistributorType, DistributorType indexed newDistributorType)` event
#### [](#IDistributionService-LogDistributionServiceReferralCreated-NftId-ReferralId-string-UFixed-uint32-Timestamp-)
`LogDistributionServiceReferralCreated(NftId indexed distributorNftId, ReferralId indexed referralId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt)` event
#### [](#IDistributionService-LogDistributionServiceReferralProcessed-NftId-ReferralId-uint32-)
`LogDistributionServiceReferralProcessed(NftId indexed distributorNftId, ReferralId indexed referralId, uint32 usedReferrals)` event
#### [](#IDistributionService-LogDistributionServiceSaleProcessed-NftId-Amount-Amount-)
`LogDistributionServiceSaleProcessed(NftId indexed distributionNftId, Amount premium, Amount distributionOwnerFee)` event
#### [](#IDistributionService-LogDistributionServiceSaleProcessedWithReferral-NftId-NftId-ReferralId-uint32-Amount-Amount-Amount-)
`LogDistributionServiceSaleProcessedWithReferral(NftId indexed distributionNftId, NftId indexed distributorNftId, ReferralId indexed referralId, uint32 numPoliciesSold, Amount premium, Amount distributionOwnerFee, Amount commissionAmount)` event
### [](#Distribution)
`Distribution`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/Distribution.sol)
import "@etherisc/gif-next/contracts/distribution/Distribution.sol";
Functions
* \[`processRenewal(referralId, feeAmount)`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
* \[`getDiscountPercentage(referralCode)`\]
* \[`getReferralId(referralCode)`\]
* \[`calculateRenewalFeeAmount(, netPremiumAmount)`\]
* \[`isVerifying()`\]
* \[`__Distribution_init(registry, productNftId, authorization, isInterceptor, initialOwner, name)`\]
* \[`_setFees(distributionFee, minDistributionOwnerFee)`\]
* \[`_createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`_createDistributor(distributor, distributorType, data)`\]
* \[`_changeDistributorType(distributorNftId, distributorType, data)`\]
* \[`_createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`_withdrawCommission(distributorNftId, amount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Distribution-processRenewal-ReferralId-uint256-)
`processRenewal(ReferralId referralId, uint256 feeAmount)` external
Callback function to process a renewal of a policy. The default implementation is empty. Overwrite this function to implement a use case specific behaviour.
#### [](#Distribution-withdrawCommission-NftId-Amount-)
`withdrawCommission(NftId distributorNftId, Amount amount) → Amount withdrawnAmount` external
Withdraw commission for the distributor
#### [](#Distribution-getDiscountPercentage-string-)
`getDiscountPercentage(string referralCode) → UFixed discountPercentage, ReferralStatus status` external
#### [](#Distribution-getReferralId-string-)
`getReferralId(string referralCode) → ReferralId referralId` public
#### [](#Distribution-calculateRenewalFeeAmount-ReferralId-uint256-)
`calculateRenewalFeeAmount(ReferralId, uint256 netPremiumAmount) → uint256 feeAmount` external
#### [](#Distribution-isVerifying--)
`isVerifying() → bool verifying` external
Returns true iff the component needs to be called when selling/renewing policis
#### [](#Distribution-__Distribution_init-address-NftId-contract-IAuthorization-bool-address-string-)
`__Distribution_init(address registry, NftId productNftId, contract IAuthorization authorization, bool isInterceptor, address initialOwner, string name)` internal
#### [](#Distribution-_setFees-struct-Fee-struct-Fee-)
`_setFees(struct Fee distributionFee, struct Fee minDistributionOwnerFee)` internal
Sets the distribution fees to the provided values.
#### [](#Distribution-_createDistributorType-string-UFixed-UFixed-UFixed-uint32-Seconds-bool-bool-bytes-)
`_createDistributorType(string name, UFixed minDiscountPercentage, UFixed maxDiscountPercentage, UFixed commissionPercentage, uint32 maxReferralCount, Seconds maxReferralLifetime, bool allowSelfReferrals, bool allowRenewals, bytes data) → DistributorType distributorType` internal
Creates a new distributor type using the provided parameters.
#### [](#Distribution-_createDistributor-address-DistributorType-bytes-)
`_createDistributor(address distributor, DistributorType distributorType, bytes data) → NftId distributorNftId` internal
Turns the provided account into a new distributor of the specified type.
#### [](#Distribution-_changeDistributorType-NftId-DistributorType-bytes-)
`_changeDistributorType(NftId distributorNftId, DistributorType distributorType, bytes data)` internal
Uptates the distributor type for the specified distributor.
#### [](#Distribution-_createReferral-NftId-string-UFixed-uint32-Timestamp-bytes-)
`_createReferral(NftId distributorNftId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt, bytes data) → ReferralId referralId` internal
Create a new referral code for the provided distributor.
#### [](#Distribution-_withdrawCommission-NftId-Amount-)
`_withdrawCommission(NftId distributorNftId, Amount amount) → Amount withdrawnAmount` internal
### [](#BasicDistribution)
`BasicDistribution`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/BasicDistribution.sol)
import "@etherisc/gif-next/contracts/distribution/BasicDistribution.sol";
Functions
* \[`setFees(distributionFee, minDistributionOwnerFee)`\]
* \[`createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`createDistributor(distributor, distributorType, data)`\]
* \[`changeDistributorType(distributorNftId, distributorType, data)`\]
* \[`createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`_initializeBasicDistribution(registry, instanceNftId, authorization, initialOwner, name)`\]
Distribution
* \[`processRenewal(referralId, feeAmount)`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
* \[`getDiscountPercentage(referralCode)`\]
* \[`getReferralId(referralCode)`\]
* \[`calculateRenewalFeeAmount(, netPremiumAmount)`\]
* \[`isVerifying()`\]
* \[`__Distribution_init(registry, productNftId, authorization, isInterceptor, initialOwner, name)`\]
* \[`_setFees(distributionFee, minDistributionOwnerFee)`\]
* \[`_createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`_createDistributor(distributor, distributorType, data)`\]
* \[`_changeDistributorType(distributorNftId, distributorType, data)`\]
* \[`_createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`_withdrawCommission(distributorNftId, amount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BasicDistribution-setFees-struct-Fee-struct-Fee-)
`setFees(struct Fee distributionFee, struct Fee minDistributionOwnerFee)` external
#### [](#BasicDistribution-createDistributorType-string-UFixed-UFixed-UFixed-uint32-Seconds-bool-bool-bytes-)
`createDistributorType(string name, UFixed minDiscountPercentage, UFixed maxDiscountPercentage, UFixed commissionPercentage, uint32 maxReferralCount, Seconds maxReferralLifetime, bool allowSelfReferrals, bool allowRenewals, bytes data) → DistributorType distributorType` external
#### [](#BasicDistribution-createDistributor-address-DistributorType-bytes-)
`createDistributor(address distributor, DistributorType distributorType, bytes data) → NftId distributorNftId` external
#### [](#BasicDistribution-changeDistributorType-NftId-DistributorType-bytes-)
`changeDistributorType(NftId distributorNftId, DistributorType distributorType, bytes data)` external
#### [](#BasicDistribution-createReferral-NftId-string-UFixed-uint32-Timestamp-bytes-)
`createReferral(NftId distributorNftId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt, bytes data) → ReferralId referralId` external
lets distributors create referral codes. referral codes need to be unique
#### [](#BasicDistribution-_initializeBasicDistribution-address-NftId-contract-IAuthorization-address-string-)
`_initializeBasicDistribution(address registry, NftId instanceNftId, contract IAuthorization authorization, address initialOwner, string name)` internal
### [](#BasicDistributionAuthorization)
`BasicDistributionAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/BasicDistributionAuthorization.sol)
import "@etherisc/gif-next/contracts/distribution/BasicDistributionAuthorization.sol";
Functions
* \[`constructor(distributionName)`\]
* \[`_setupServiceTargets()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
* \[`_setupTargetAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#BasicDistributionAuthorization-constructor-string-)
`constructor(string distributionName)` public
#### [](#BasicDistributionAuthorization-_setupServiceTargets--)
`_setupServiceTargets()` internal
Sets up the relevant service targets for the component. Overwrite this function for use case specific authorizations.
#### [](#BasicDistributionAuthorization-_setupTokenHandlerAuthorizations--)
`_setupTokenHandlerAuthorizations()` internal
Sets up the relevant component’s token handler authorizations. Overwrite this function for use case specific authorizations.
#### [](#BasicDistributionAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#DistributionService)
`DistributionService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/DistributionService.sol)
import "@etherisc/gif-next/contracts/distribution/DistributionService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`createDistributorType(name, minDiscountPercentage, maxDiscountPercentage, commissionPercentage, maxReferralCount, maxReferralLifetime, allowSelfReferrals, allowRenewals, data)`\]
* \[`createDistributor(distributor, distributorType, data)`\]
* \[`changeDistributorType(distributorNftId, newDistributorType, data)`\]
* \[`createReferral(distributorNftId, code, discountPercentage, maxReferrals, expiryAt, data)`\]
* \[`processReferral(distributionNftId, referralId)`\]
* \[`processSale(distributionNftId, referralId, premium)`\]
* \[`withdrawCommission(distributorNftId, amount)`\]
* \[`referralIsValid(distributionNftId, referralId)`\]
* \[`getDiscountPercentage(instanceReader, referralId)`\]
* \[`_checkDistributionType(instanceReader, distributorType, expectedDistributionNftId)`\]
* \[`_getAndVerifyActiveDistribution()`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IDistributionService
* \[`LogDistributionServiceCommissionWithdrawn(distributorNftId, recipient, amount, tokenAddress)`\]
* \[`LogDistributionServiceDistributorTypeCreated(distributionNftId, distributorType, name, commissionPercentage)`\]
* \[`LogDistributionServiceDistributorCreated(distributionNftId, distributorNftId, distributor, distributorType)`\]
* \[`LogDistributionServiceDistributorTypeChanged(distributorNftId, oldDistributorType, newDistributorType)`\]
* \[`LogDistributionServiceReferralCreated(distributorNftId, referralId, code, discountPercentage, maxReferrals, expiryAt)`\]
* \[`LogDistributionServiceReferralProcessed(distributorNftId, referralId, usedReferrals)`\]
* \[`LogDistributionServiceSaleProcessed(distributionNftId, premium, distributionOwnerFee)`\]
* \[`LogDistributionServiceSaleProcessedWithReferral(distributionNftId, distributorNftId, referralId, numPoliciesSold, premium, distributionOwnerFee, commissionAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#DistributionService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#DistributionService-createDistributorType-string-UFixed-UFixed-UFixed-uint32-Seconds-bool-bool-bytes-)
`createDistributorType(string name, UFixed minDiscountPercentage, UFixed maxDiscountPercentage, UFixed commissionPercentage, uint32 maxReferralCount, Seconds maxReferralLifetime, bool allowSelfReferrals, bool allowRenewals, bytes data) → DistributorType distributorType` external
#### [](#DistributionService-createDistributor-address-DistributorType-bytes-)
`createDistributor(address distributor, DistributorType distributorType, bytes data) → NftId distributorNftId` external
#### [](#DistributionService-changeDistributorType-NftId-DistributorType-bytes-)
`changeDistributorType(NftId distributorNftId, DistributorType newDistributorType, bytes data)` external
#### [](#DistributionService-createReferral-NftId-string-UFixed-uint32-Timestamp-bytes-)
`createReferral(NftId distributorNftId, string code, UFixed discountPercentage, uint32 maxReferrals, Timestamp expiryAt, bytes data) → ReferralId referralId` external
#### [](#DistributionService-processReferral-NftId-ReferralId-)
`processReferral(NftId distributionNftId, ReferralId referralId)` external
callback from product service when a referral is used. Calling this will increment the referral usage counter.
#### [](#DistributionService-processSale-NftId-ReferralId-struct-IPolicy-PremiumInfo-)
`processSale(NftId distributionNftId, ReferralId referralId, struct IPolicy.PremiumInfo premium)` external
callback from product service when selling a policy for a specific referralId
#### [](#DistributionService-withdrawCommission-NftId-Amount-)
`withdrawCommission(NftId distributorNftId, Amount amount) → Amount withdrawnAmount` public
Withdraw commission for the distributor
#### [](#DistributionService-referralIsValid-NftId-ReferralId-)
`referralIsValid(NftId distributionNftId, ReferralId referralId) → bool isValid` public
#### [](#DistributionService-getDiscountPercentage-contract-InstanceReader-ReferralId-)
`getDiscountPercentage(contract InstanceReader instanceReader, ReferralId referralId) → UFixed discountPercentage, ReferralStatus status` external
Returns the discount percentage for the provided referral code. The function retuns both the percentage and the status of the referral code.
#### [](#DistributionService-_checkDistributionType-contract-InstanceReader-DistributorType-NftId-)
`_checkDistributionType(contract InstanceReader instanceReader, DistributorType distributorType, NftId expectedDistributionNftId)` internal
#### [](#DistributionService-_getAndVerifyActiveDistribution--)
`_getAndVerifyActiveDistribution() → NftId poolNftId, contract IInstance instance` internal
#### [](#DistributionService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#DistributionServiceManager)
`DistributionServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/distribution/DistributionServiceManager.sol)
import "@etherisc/gif-next/contracts/distribution/DistributionServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getDistributionService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#DistributionServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with distribution service implementation and deploys instance
#### [](#DistributionServiceManager-getDistributionService--)
`getDistributionService() → contract DistributionService distributionService` external
[← authorization](/gif-next/3.x/api/authorization)
[instance →](/gif-next/3.x/api/instance)
---
# Fire insurance example components - Etherisc Docs
Fire insurance example components
=================================
This directory contains the set of contracts required for the fire insurance. The fire insurance example is a minimal fully permissioned set of example components that can be used to run a (very simple) fire insurance.
The product is built without a distribution and oracle component.
[](#contracts)
Contracts
------------------------
### [](#FirePool)
`FirePool`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/fire/FirePool.sol)
import "@etherisc/gif-next/contracts/examples/fire/FirePool.sol";
Functions
* \[`constructor(registry, fireProductNftId, componentName, authorization)`\]
* \[`_intialize(registry, fireProductNftId, componentName, poolInfo, authorization, initialOwner)`\]
* \[`createBundle(fee, initialAmount, lifetime)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setLocked(locked)`\]
* \[`setWallet(newWallet)`\]
BasicPool
* \[`_initializeBasicPool(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`stake(bundleNftId, amount)`\]
* \[`unstake(bundleNftId, amount)`\]
* \[`extend(bundleNftId, lifetimeExtension)`\]
* \[`setBundleLocked(bundleNftId, locked)`\]
* \[`closeBundle(bundleNftId)`\]
* \[`setBundleFee(bundleNftId, fee)`\]
* \[`withdrawBundleFees(bundleNftId, amount)`\]
* \[`setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`setFees(poolFee, stakingFee, performanceFee)`\]
Pool
* \[`getContractLocation(name)`\]
* \[`verifyApplication(applicationNftId, bundleNftId, collateralizationAmount)`\]
* \[`processConfirmedClaim(policyNftId, claimId, amount)`\]
* \[`applicationMatchesBundle(applicationNftId, applicationData, bundleNftId, bundleFilter, collateralizationAmount)`\]
* \[`getInitialPoolInfo()`\]
* \[`__Pool_init(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`_setPoolFees(poolFee, stakingFee, performanceFee)`\]
* \[`_setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`_fundPoolWallet(amount)`\]
* \[`_defundPoolWallet(amount)`\]
* \[`_createBundle(bundleOwner, fee, lifetime, filter)`\]
* \[`_setBundleFee(bundleNftId, fee)`\]
* \[`_stake(bundleNftId, amount)`\]
* \[`_unstake(bundleNftId, amount)`\]
* \[`_extend(bundleNftId, lifetimeExtension)`\]
* \[`_setBundleLocked(bundleNftId, locked)`\]
* \[`_closeBundle(bundleNftId)`\]
* \[`_withdrawBundleFees(bundleNftId, amount)`\]
* \[`_processFundedClaim(policyNftId, claimId, availableAmount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IPoolComponent
* \[`LogPoolVerifiedByPool(pool, applicationNftId, collateralizationAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#FirePool-constructor-address-NftId-string-contract-IAuthorization-)
`constructor(address registry, NftId fireProductNftId, string componentName, contract IAuthorization authorization)` public
#### [](#FirePool-_intialize-address-NftId-string-struct-IComponents-PoolInfo-contract-IAuthorization-address-)
`_intialize(address registry, NftId fireProductNftId, string componentName, struct IComponents.PoolInfo poolInfo, contract IAuthorization authorization, address initialOwner)` internal
#### [](#FirePool-createBundle-struct-Fee-Amount-Seconds-)
`createBundle(struct Fee fee, Amount initialAmount, Seconds lifetime) → NftId bundleNftId, Amount netStakedAmount` external
#### [](#FirePool-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
#### [](#FirePool-setLocked-bool-)
`setLocked(bool locked)` external
#### [](#FirePool-setWallet-address-)
`setWallet(address newWallet)` external
### [](#FirePoolAuthorization)
`FirePoolAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/fire/FirePoolAuthorization.sol)
import "@etherisc/gif-next/contracts/examples/fire/FirePoolAuthorization.sol";
Functions
* \[`constructor(poolName)`\]
* \[`_setupTargetAuthorizations()`\]
BasicPoolAuthorization
* \[`_setupServiceTargets()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#FirePoolAuthorization-constructor-string-)
`constructor(string poolName)` public
#### [](#FirePoolAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#FireProduct)
`FireProduct`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/fire/FireProduct.sol)
import "@etherisc/gif-next/contracts/examples/fire/FireProduct.sol";
This is the product component for the fire insurance example. It show how to insure a house for a given suminsured in a city. The risk is based on the city. If a fire is reported in the city, the policy holder is able to submit a claim and get a payout.
Functions
* \[`constructor(registry, instanceNftid, componentName, authorization)`\]
* \[`_initialize(registry, instanceNftId, componentName, authorization, initialOwner)`\]
* \[`cities()`\]
* \[`city(idx)`\]
* \[`riskId(cityName)`\]
* \[`pauseCity(cityName)`\]
* \[`unpauseCity(cityName)`\]
* \[`calculatePremium(cityName, sumInsured, lifetime, bundleNftId)`\]
* \[`calculateNetPremium(sumInsured, , lifetime, )`\]
* \[`createApplication(cityName, sumInsured, lifetime, bundleNftId)`\]
* \[`initializeCity(cityName)`\]
* \[`createPolicy(policyNftId, activateAt)`\]
* \[`decline(policyNftId)`\]
* \[`expire(policyNftId, expireAt)`\]
* \[`close(policyNftId)`\]
* \[`reportFire(fireId, cityName, damageLevel, reportedAt)`\]
* \[`fire(fireId)`\]
* \[`submitClaim(policyNftId, fireId)`\]
* \[`_checkClaimConditions(policyNftId, policyInfo, fireId)`\]
* \[`_getClaimAmount(policyNftId, sumInsured, damageLevel)`\]
* \[`_damageLevelToPayoutPercentage(damageLevel)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setLocked(locked)`\]
* \[`setWallet(newWallet)`\]
BasicProduct
* \[`setFees(productFee, processingFee)`\]
* \[`_initializeBasicProduct(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
Product
* \[`registerComponent(component)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`calculatePremium(sumInsuredAmount, riskId, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`getInitialProductInfo()`\]
* \[`getInitialFeeInfo()`\]
* \[`__Product_init(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`_setFees(productFee, processingFee)`\]
* \[`_createRisk(id, data)`\]
* \[`_updateRisk(id, data)`\]
* \[`_setRiskLocked(id, locked)`\]
* \[`_closeRisk(id)`\]
* \[`_createApplication(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`_revoke(applicationNftId)`\]
* \[`_createPolicy(applicationNftId, activateAt, maxPremiumAmount)`\]
* \[`_decline(policyNftId)`\]
* \[`_expire(policyNftId, expireAt)`\]
* \[`_adjustActivation(policyNftId, activateAt)`\]
* \[`_collectPremium(policyNftId, activateAt)`\]
* \[`_activate(policyNftId, activateAt)`\]
* \[`_close(policyNftId)`\]
* \[`_submitClaim(policyNftId, claimAmount, claimData)`\]
* \[`_revokeClaim(policyNftId, claimId)`\]
* \[`_confirmClaim(policyNftId, claimId, confirmedAmount, data)`\]
* \[`_declineClaim(policyNftId, claimId, data)`\]
* \[`_cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`_createPayout(policyNftId, claimId, amount, data)`\]
* \[`_createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`_processPayout(policyNftId, payoutId)`\]
* \[`_cancelPayout(policyNftId, payoutId)`\]
* \[`_getProductStorage()`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#FireProduct-constructor-address-NftId-string-contract-IAuthorization-)
`constructor(address registry, NftId instanceNftid, string componentName, contract IAuthorization authorization)` public
#### [](#FireProduct-_initialize-address-NftId-string-contract-IAuthorization-address-)
`_initialize(address registry, NftId instanceNftId, string componentName, contract IAuthorization authorization, address initialOwner)` internal
#### [](#FireProduct-cities--)
`cities() → uint256` public
#### [](#FireProduct-city-uint256-)
`city(uint256 idx) → string` public
#### [](#FireProduct-riskId-string-)
`riskId(string cityName) → RiskId` public
#### [](#FireProduct-pauseCity-string-)
`pauseCity(string cityName)` public
#### [](#FireProduct-unpauseCity-string-)
`unpauseCity(string cityName)` public
#### [](#FireProduct-calculatePremium-string-Amount-Seconds-NftId-)
`calculatePremium(string cityName, Amount sumInsured, Seconds lifetime, NftId bundleNftId) → Amount premiumAmount` public
#### [](#FireProduct-calculateNetPremium-Amount-RiskId-Seconds-bytes-)
`calculateNetPremium(Amount sumInsured, RiskId, Seconds lifetime, bytes) → Amount netPremiumAmount` external
#### [](#FireProduct-createApplication-string-Amount-Seconds-NftId-)
`createApplication(string cityName, Amount sumInsured, Seconds lifetime, NftId bundleNftId) → NftId policyNftId` public
#### [](#FireProduct-initializeCity-string-)
`initializeCity(string cityName) → RiskId risk` public
#### [](#FireProduct-createPolicy-NftId-Timestamp-)
`createPolicy(NftId policyNftId, Timestamp activateAt)` public
Calling this method will lock the sum insured amount in the pool and activate the policy at the given time. It will also collect the tokens payment for the premium. An approval with the correct amount towards the TokenHandler of the product is therefor required.
#### [](#FireProduct-decline-NftId-)
`decline(NftId policyNftId)` public
Decline the policy application
#### [](#FireProduct-expire-NftId-Timestamp-)
`expire(NftId policyNftId, Timestamp expireAt) → Timestamp` public
#### [](#FireProduct-close-NftId-)
`close(NftId policyNftId)` public
#### [](#FireProduct-reportFire-uint256-string-DamageLevel-Timestamp-)
`reportFire(uint256 fireId, string cityName, DamageLevel damageLevel, Timestamp reportedAt)` public
#### [](#FireProduct-fire-uint256-)
`fire(uint256 fireId) → struct FireProduct.Fire` public
#### [](#FireProduct-submitClaim-NftId-uint256-)
`submitClaim(NftId policyNftId, uint256 fireId) → ClaimId claimId, PayoutId payoutId` public
#### [](#FireProduct-_checkClaimConditions-NftId-struct-IPolicy-PolicyInfo-uint256-)
`_checkClaimConditions(NftId policyNftId, struct IPolicy.PolicyInfo policyInfo, uint256 fireId)` internal
#### [](#FireProduct-_getClaimAmount-NftId-Amount-DamageLevel-)
`_getClaimAmount(NftId policyNftId, Amount sumInsured, DamageLevel damageLevel) → Amount` internal
#### [](#FireProduct-_damageLevelToPayoutPercentage-DamageLevel-)
`_damageLevelToPayoutPercentage(DamageLevel damageLevel) → UFixed` internal
#### [](#FireProduct-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
#### [](#FireProduct-setLocked-bool-)
`setLocked(bool locked)` external
#### [](#FireProduct-setWallet-address-)
`setWallet(address newWallet)` external
### [](#FireProductAuthorization)
`FireProductAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/fire/FireProductAuthorization.sol)
import "@etherisc/gif-next/contracts/examples/fire/FireProductAuthorization.sol";
Functions
* \[`constructor(poolName)`\]
* \[`_setupTargetAuthorizations()`\]
BasicProductAuthorization
* \[`_setupServiceTargets()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#FireProductAuthorization-constructor-string-)
`constructor(string poolName)` public
#### [](#FireProductAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#FireUSD)
`FireUSD`[](https://github.com/etherisc/gif-next/blob/develop/contracts/examples/fire/FireUSD.sol)
import "@etherisc/gif-next/contracts/examples/fire/FireUSD.sol";
FireUSD is a stablecoin with 6 decimals and an initial supply of 1 Billion tokens.
Functions
* \[`constructor()`\]
* \[`decimals()`\]
ERC20
* \[`name()`\]
* \[`symbol()`\]
* \[`totalSupply()`\]
* \[`balanceOf(account)`\]
* \[`transfer(to, value)`\]
* \[`allowance(owner, spender)`\]
* \[`approve(spender, value)`\]
* \[`transferFrom(from, to, value)`\]
* \[`_transfer(from, to, value)`\]
* \[`_update(from, to, value)`\]
* \[`_mint(account, value)`\]
* \[`_burn(account, value)`\]
* \[`_approve(owner, spender, value)`\]
* \[`_approve(owner, spender, value, emitEvent)`\]
* \[`_spendAllowance(owner, spender, value)`\]
Events
IERC20
* \[`Transfer(from, to, value)`\]
* \[`Approval(owner, spender, value)`\]
#### [](#FireUSD-constructor--)
`constructor()` public
#### [](#FireUSD-decimals--)
`decimals() → uint8` public
Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5.05` (`505 / 10 ** 2`).
Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the default value returned by this function, unless it’s overridden.
| | |
| --- | --- |
| | This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. |
[← upgradeability](/gif-next/3.x/api/upgradeability)
[examples/unpermissioned →](/gif-next/3.x/api/examples/unpermissioned)
---
# Authorization - Etherisc Docs
Authorization
=============
Contains interfaces and contracts related to authorization.
[](#contracts)
Contracts
------------------------
### [](#IAccess)
`IAccess`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/IAccess.sol)
import "@etherisc/gif-next/contracts/authorization/IAccess.sol";
### [](#IAuthorization)
`IAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/IAuthorization.sol)
import "@etherisc/gif-next/contracts/authorization/IAuthorization.sol";
Functions
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
IServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
#### [](#IAuthorization-getTokenHandlerName--)
`getTokenHandlerName() → string name` external
Returns the token hander name. Only components have a token handler.
#### [](#IAuthorization-getTokenHandlerTarget--)
`getTokenHandlerTarget() → Str target` external
Returns the token hander target. Only components have a token handler.
#### [](#IAuthorization-getTargets--)
`getTargets() → Str[] targets` external
Returns the complete list of targets.
#### [](#IAuthorization-targetExists-Str-)
`targetExists(Str target) → bool exists` external
Returns true iff the specified target exists.
### [](#IServiceAuthorization)
`IServiceAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/IServiceAuthorization.sol)
import "@etherisc/gif-next/contracts/authorization/IServiceAuthorization.sol";
Functions
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
#### [](#IServiceAuthorization-getDomain--)
`getDomain() → ObjectType targetDomain` external
Returns the main domain of the authorization.
#### [](#IServiceAuthorization-getRelease--)
`getRelease() → VersionPart release` external
Returns the release (VersionPart) for which the authorizations are defined by this contract. Matches with the release returned by the linked service authorization.
#### [](#IServiceAuthorization-getCommitHash--)
`getCommitHash() → string commitHash` external
Returns the commit hash for the related GIF release.
#### [](#IServiceAuthorization-getMainTargetName--)
`getMainTargetName() → string name` external
Returns the main target id name as string. This name is used to derive the target id and a corresponding target role name Overwrite this function to change the basic pool target name.
#### [](#IServiceAuthorization-getMainTarget--)
`getMainTarget() → Str target` external
Returns the main target.
#### [](#IServiceAuthorization-getServiceDomains--)
`getServiceDomains() → ObjectType[] serviceDomains` external
Returns the full list of service domains for this release. Services need to be registered for the release in revers order of this list.
#### [](#IServiceAuthorization-getServiceDomain-uint256-)
`getServiceDomain(uint256 idx) → ObjectType serviceDomain` external
Returns the service domain for the provided index.
#### [](#IServiceAuthorization-getServiceTarget-ObjectType-)
`getServiceTarget(ObjectType serviceDomain) → Str serviceTarget` external
Returns the service target for the specified domain.
#### [](#IServiceAuthorization-getServiceRole-ObjectType-)
`getServiceRole(ObjectType serviceDomain) → RoleId serviceRoleId` external
Returns the service target for the specified domain.
#### [](#IServiceAuthorization-getServiceAddress-ObjectType-)
`getServiceAddress(ObjectType serviceDomain) → address service` external
Returns the expected service address for the provided domain.
#### [](#IServiceAuthorization-getTargetRole-Str-)
`getTargetRole(Str target) → RoleId roleId` external
Returns the role id associated with the target. If no role is associated with the target the zero role id is returned.
#### [](#IServiceAuthorization-roleExists-RoleId-)
`roleExists(RoleId roleId) → bool exists` external
Returns true iff the role exists.
#### [](#IServiceAuthorization-getRoles--)
`getRoles() → RoleId[] roles` external
Returns the list of involved roles.
#### [](#IServiceAuthorization-getRoleInfo-RoleId-)
`getRoleInfo(RoleId roleId) → struct IAccess.RoleInfo roleInfo` external
Returns the role info for the provided role id.
#### [](#IServiceAuthorization-getRoleName-RoleId-)
`getRoleName(RoleId roleId) → string roleName` external
Returns the name for the provided role id.
#### [](#IServiceAuthorization-getAuthorizedRoles-Str-)
`getAuthorizedRoles(Str target) → RoleId[] roleIds` external
For the given target the list of authorized role ids is returned
#### [](#IServiceAuthorization-getAuthorizedFunctions-Str-RoleId-)
`getAuthorizedFunctions(Str target, RoleId roleId) → struct IAccess.FunctionInfo[] authorizatedFunctions` external
For the given target and role id the list of authorized functions is returned
### [](#IAccessAdmin)
`IAccessAdmin`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/IAccessAdmin.sol)
import "@etherisc/gif-next/contracts/authorization/IAccessAdmin.sol";
Base interface for registry admin, release admin, and instance admin
Functions
* \[`getAuthorization()`\]
* \[`getLinkedNftId()`\]
* \[`isLocked()`\]
* \[`roles()`\]
* \[`getRoleId(idx)`\]
* \[`roleExists(roleId)`\]
* \[`getRoleForName(name)`\]
* \[`getRoleInfo(roleId)`\]
* \[`isRoleActive(roleId)`\]
* \[`isRoleCustom(roleId)`\]
* \[`isRoleMember(roleId, account)`\]
* \[`isRoleAdmin(roleId, account)`\]
* \[`roleMembers(roleId)`\]
* \[`getRoleMember(roleId, idx)`\]
* \[`targetExists(target)`\]
* \[`getTargetForName(name)`\]
* \[`targets()`\]
* \[`getTargetAddress(idx)`\]
* \[`getTargetInfo(target)`\]
* \[`isTargetLocked(target)`\]
* \[`authorizedFunctions(target)`\]
* \[`getAuthorizedFunction(target, idx)`\]
IRelease
* \[`getRelease()`\]
IRegistryLinked
* \[`getRegistry()`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogAccessAdminRoleCreated(roleId, roleAdminId, targetType, name, admin)`\]
* \[`LogAccessAdminTargetCreated(target, roleId, managed, name, admin)`\]
* \[`LogAccessAdminRoleActivatedSet(roleId, active, admin, lastUpdateIn)`\]
* \[`LogAccessAdminRoleGranted(account, roleName, admin)`\]
* \[`LogAccessAdminRoleRevoked(account, roleName, admin)`\]
* \[`LogAccessAdminTargetLockedSet(target, locked, admin, lastUpdateIn)`\]
* \[`LogAccessAdminFunctionGranted(target, selector, roleId, func, admin, lastUpdateIn)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IAccessAdmin-getAuthorization--)
`getAuthorization() → contract IAuthorization authorization` external
#### [](#IAccessAdmin-getLinkedNftId--)
`getLinkedNftId() → NftId linkedNftId` external
#### [](#IAccessAdmin-isLocked--)
`isLocked() → bool locked` external
#### [](#IAccessAdmin-roles--)
`roles() → uint256 numberOfRoles` external
#### [](#IAccessAdmin-getRoleId-uint256-)
`getRoleId(uint256 idx) → RoleId roleId` external
#### [](#IAccessAdmin-roleExists-RoleId-)
`roleExists(RoleId roleId) → bool exists` external
#### [](#IAccessAdmin-getRoleForName-string-)
`getRoleForName(string name) → RoleId roleId, bool exists` external
#### [](#IAccessAdmin-getRoleInfo-RoleId-)
`getRoleInfo(RoleId roleId) → struct IAccess.RoleInfo roleInfo` external
#### [](#IAccessAdmin-isRoleActive-RoleId-)
`isRoleActive(RoleId roleId) → bool isActive` external
#### [](#IAccessAdmin-isRoleCustom-RoleId-)
`isRoleCustom(RoleId roleId) → bool isCustom` external
#### [](#IAccessAdmin-isRoleMember-RoleId-address-)
`isRoleMember(RoleId roleId, address account) → bool` external
#### [](#IAccessAdmin-isRoleAdmin-RoleId-address-)
`isRoleAdmin(RoleId roleId, address account) → bool` external
#### [](#IAccessAdmin-roleMembers-RoleId-)
`roleMembers(RoleId roleId) → uint256 numberOfMembers` external
#### [](#IAccessAdmin-getRoleMember-RoleId-uint256-)
`getRoleMember(RoleId roleId, uint256 idx) → address account` external
#### [](#IAccessAdmin-targetExists-address-)
`targetExists(address target) → bool exists` external
#### [](#IAccessAdmin-getTargetForName-Str-)
`getTargetForName(Str name) → address target` external
#### [](#IAccessAdmin-targets--)
`targets() → uint256 numberOfTargets` external
#### [](#IAccessAdmin-getTargetAddress-uint256-)
`getTargetAddress(uint256 idx) → address target` external
#### [](#IAccessAdmin-getTargetInfo-address-)
`getTargetInfo(address target) → struct IAccess.TargetInfo targetInfo` external
#### [](#IAccessAdmin-isTargetLocked-address-)
`isTargetLocked(address target) → bool locked` external
#### [](#IAccessAdmin-authorizedFunctions-address-)
`authorizedFunctions(address target) → uint256 numberOfFunctions` external
#### [](#IAccessAdmin-getAuthorizedFunction-address-uint256-)
`getAuthorizedFunction(address target, uint256 idx) → struct IAccess.FunctionInfo func, RoleId roleId` external
#### [](#IAccessAdmin-LogAccessAdminRoleCreated-RoleId-RoleId-enum-IAccess-TargetType-string-string-)
`LogAccessAdminRoleCreated(RoleId indexed roleId, RoleId indexed roleAdminId, enum IAccess.TargetType indexed targetType, string name, string admin)` event
#### [](#IAccessAdmin-LogAccessAdminTargetCreated-address-RoleId-bool-string-string-)
`LogAccessAdminTargetCreated(address indexed target, RoleId indexed roleId, bool indexed managed, string name, string admin)` event
#### [](#IAccessAdmin-LogAccessAdminRoleActivatedSet-RoleId-bool-string-Blocknumber-)
`LogAccessAdminRoleActivatedSet(RoleId indexed roleId, bool indexed active, string admin, Blocknumber indexed lastUpdateIn)` event
#### [](#IAccessAdmin-LogAccessAdminRoleGranted-address-string-string-)
`LogAccessAdminRoleGranted(address indexed account, string roleName, string admin)` event
#### [](#IAccessAdmin-LogAccessAdminRoleRevoked-address-string-string-)
`LogAccessAdminRoleRevoked(address indexed account, string roleName, string admin)` event
#### [](#IAccessAdmin-LogAccessAdminTargetLockedSet-address-bool-string-Blocknumber-)
`LogAccessAdminTargetLockedSet(address indexed target, bool indexed locked, string admin, Blocknumber indexed lastUpdateIn)` event
#### [](#IAccessAdmin-LogAccessAdminFunctionGranted-address-Selector-RoleId-string-string-Blocknumber-)
`LogAccessAdminFunctionGranted(address indexed target, Selector indexed selector, RoleId indexed roleId, string func, string admin, Blocknumber lastUpdateIn)` event
### [](#AccessAdmin)
`AccessAdmin`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/AccessAdmin.sol)
import "@etherisc/gif-next/contracts/authorization/AccessAdmin.sol";
A generic access amin contract that implements role based access control based on OpenZeppelin’s AccessManager contract. The contract provides read functions to query all available roles, targets and access rights. This contract works for both a constructor based deployment or a deployment based on cloning and initialization.
Functions
* \[`initialize(authority, adminName)`\]
* \[`__AccessAdmin_init(authority, adminName)`\]
* \[`getRelease()`\]
* \[`getRegistry()`\]
* \[`getLinkedNftId()`\]
* \[`getAuthorization()`\]
* \[`isLocked()`\]
* \[`roles()`\]
* \[`getRoleId(idx)`\]
* \[`getAdminRole()`\]
* \[`getPublicRole()`\]
* \[`roleExists(roleId)`\]
* \[`getRoleForName(name)`\]
* \[`getRoleInfo(roleId)`\]
* \[`isRoleActive(roleId)`\]
* \[`isRoleCustom(roleId)`\]
* \[`roleMembers(roleId)`\]
* \[`getRoleMember(roleId, idx)`\]
* \[`isRoleMember(roleId, account)`\]
* \[`isRoleAdmin(roleId, account)`\]
* \[`targetExists(target)`\]
* \[`targets()`\]
* \[`getTargetAddress(idx)`\]
* \[`getTargetInfo(target)`\]
* \[`getTargetForName(name)`\]
* \[`isTargetLocked(target)`\]
* \[`authorizedFunctions(target)`\]
* \[`getAuthorizedFunction(target, idx)`\]
* \[`getFunctionInfo(target, selector)`\]
* \[`_linkToNftOwnable(registerable)`\]
* \[`_createRoles(authorization)`\]
* \[`_createRole(roleId, info, revertOnExistingRole)`\]
* \[`_setRoleActive(roleId, active)`\]
* \[`_grantRoleToAccount(roleId, account)`\]
* \[`_revokeRoleFromAccount(roleId, account)`\]
* \[`_getOrCreateTargetRoleIdAndName(target, targetName, targetType)`\]
* \[`_createTarget(target, targetName, targetType, checkAuthority)`\]
* \[`_createTargetUnchecked(target, targetName, targetType, managed)`\]
* \[`_setTargetLocked(target, locked)`\]
* \[`_authorizeFunctions(authorization, target, roleId)`\]
* \[`_authorizeTargetFunctions(target, roleId, functions, onlyComponentOrContractTargets, addFunctions)`\]
* \[`_updateFunctionAccess(target, roleId, func, addFunction)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IAccessAdmin
* \[`LogAccessAdminRoleCreated(roleId, roleAdminId, targetType, name, admin)`\]
* \[`LogAccessAdminTargetCreated(target, roleId, managed, name, admin)`\]
* \[`LogAccessAdminRoleActivatedSet(roleId, active, admin, lastUpdateIn)`\]
* \[`LogAccessAdminRoleGranted(account, roleName, admin)`\]
* \[`LogAccessAdminRoleRevoked(account, roleName, admin)`\]
* \[`LogAccessAdminTargetLockedSet(target, locked, admin, lastUpdateIn)`\]
* \[`LogAccessAdminFunctionGranted(target, selector, roleId, func, admin, lastUpdateIn)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#AccessAdmin-initialize-address-string-)
`initialize(address authority, string adminName)` public
Initializes this admin with the provided accessManager (and authorization specification). Internally initializes access manager with this admin and creates basic role setup.
#### [](#AccessAdmin-__AccessAdmin_init-address-string-)
`__AccessAdmin_init(address authority, string adminName)` internal
Initializes this admin with the provided accessManager and name. IMPORTANT - cloning of an access admin and initialization MUST be done in the same tx. - this function as well as any completeSetup functions MUST be called in the same tx.
#### [](#AccessAdmin-getRelease--)
`getRelease() → VersionPart release` public
Registers a registry contract for a specified chain. Only one chain registry may be registered per chain
#### [](#AccessAdmin-getRegistry--)
`getRegistry() → contract IRegistry registry` public
#### [](#AccessAdmin-getLinkedNftId--)
`getLinkedNftId() → NftId linkedNftId` external
#### [](#AccessAdmin-getAuthorization--)
`getAuthorization() → contract IAuthorization authorization` public
#### [](#AccessAdmin-isLocked--)
`isLocked() → bool locked` public
#### [](#AccessAdmin-roles--)
`roles() → uint256 numberOfRoles` external
#### [](#AccessAdmin-getRoleId-uint256-)
`getRoleId(uint256 idx) → RoleId roleId` external
#### [](#AccessAdmin-getAdminRole--)
`getAdminRole() → RoleId roleId` public
#### [](#AccessAdmin-getPublicRole--)
`getPublicRole() → RoleId roleId` public
#### [](#AccessAdmin-roleExists-RoleId-)
`roleExists(RoleId roleId) → bool exists` public
#### [](#AccessAdmin-getRoleForName-string-)
`getRoleForName(string name) → RoleId roleId, bool exists` public
#### [](#AccessAdmin-getRoleInfo-RoleId-)
`getRoleInfo(RoleId roleId) → struct IAccess.RoleInfo` public
#### [](#AccessAdmin-isRoleActive-RoleId-)
`isRoleActive(RoleId roleId) → bool isActive` external
#### [](#AccessAdmin-isRoleCustom-RoleId-)
`isRoleCustom(RoleId roleId) → bool isActive` external
#### [](#AccessAdmin-roleMembers-RoleId-)
`roleMembers(RoleId roleId) → uint256 numberOfMembers` external
#### [](#AccessAdmin-getRoleMember-RoleId-uint256-)
`getRoleMember(RoleId roleId, uint256 idx) → address account` external
#### [](#AccessAdmin-isRoleMember-RoleId-address-)
`isRoleMember(RoleId roleId, address account) → bool` public
#### [](#AccessAdmin-isRoleAdmin-RoleId-address-)
`isRoleAdmin(RoleId roleId, address account) → bool` public
#### [](#AccessAdmin-targetExists-address-)
`targetExists(address target) → bool exists` public
#### [](#AccessAdmin-targets--)
`targets() → uint256 numberOfTargets` external
#### [](#AccessAdmin-getTargetAddress-uint256-)
`getTargetAddress(uint256 idx) → address target` external
#### [](#AccessAdmin-getTargetInfo-address-)
`getTargetInfo(address target) → struct IAccess.TargetInfo targetInfo` public
#### [](#AccessAdmin-getTargetForName-Str-)
`getTargetForName(Str name) → address target` public
#### [](#AccessAdmin-isTargetLocked-address-)
`isTargetLocked(address target) → bool locked` public
#### [](#AccessAdmin-authorizedFunctions-address-)
`authorizedFunctions(address target) → uint256 numberOfFunctions` external
#### [](#AccessAdmin-getAuthorizedFunction-address-uint256-)
`getAuthorizedFunction(address target, uint256 idx) → struct IAccess.FunctionInfo func, RoleId roleId` external
#### [](#AccessAdmin-getFunctionInfo-address-Selector-)
`getFunctionInfo(address target, Selector selector) → struct IAccess.FunctionInfo functionInfo` external
#### [](#AccessAdmin-_linkToNftOwnable-address-)
`_linkToNftOwnable(address registerable)` internal
#### [](#AccessAdmin-_createRoles-contract-IServiceAuthorization-)
`_createRoles(contract IServiceAuthorization authorization)` internal
#### [](#AccessAdmin-_createRole-RoleId-struct-IAccess-RoleInfo-bool-)
`_createRole(RoleId roleId, struct IAccess.RoleInfo info, bool revertOnExistingRole)` internal
Creates a role based on the provided parameters. Checks that the provided role and role id and role name not already used.
#### [](#AccessAdmin-_setRoleActive-RoleId-bool-)
`_setRoleActive(RoleId roleId, bool active)` internal
Activates or deactivates role. The role activ property is indirectly controlled over the pausedAt timestamp.
#### [](#AccessAdmin-_grantRoleToAccount-RoleId-address-)
`_grantRoleToAccount(RoleId roleId, address account)` internal
grant the specified role to the provided account
#### [](#AccessAdmin-_revokeRoleFromAccount-RoleId-address-)
`_revokeRoleFromAccount(RoleId roleId, address account)` internal
revoke the specified role from the provided account
#### [](#AccessAdmin-_getOrCreateTargetRoleIdAndName-address-string-enum-IAccess-TargetType-)
`_getOrCreateTargetRoleIdAndName(address target, string targetName, enum IAccess.TargetType targetType) → RoleId roleId, string roleName, bool exists` internal
#### [](#AccessAdmin-_createTarget-address-string-enum-IAccess-TargetType-bool-)
`_createTarget(address target, string targetName, enum IAccess.TargetType targetType, bool checkAuthority) → RoleId contractRoleId` internal
#### [](#AccessAdmin-_createTargetUnchecked-address-string-enum-IAccess-TargetType-bool-)
`_createTargetUnchecked(address target, string targetName, enum IAccess.TargetType targetType, bool managed) → RoleId targetRoleId` internal
Creates a new target and a corresponding contract role. The function assigns the role to the target and logs the creation.
#### [](#AccessAdmin-_setTargetLocked-address-bool-)
`_setTargetLocked(address target, bool locked)` internal
#### [](#AccessAdmin-_authorizeFunctions-contract-IAuthorization-Str-RoleId-)
`_authorizeFunctions(contract IAuthorization authorization, Str target, RoleId roleId)` internal
Authorize the functions of the target for the specified role.
#### [](#AccessAdmin-_authorizeTargetFunctions-address-RoleId-struct-IAccess-FunctionInfo---bool-bool-)
`_authorizeTargetFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions, bool onlyComponentOrContractTargets, bool addFunctions)` internal
Authorize the functions of the target for the specified role. Flag addFunctions determines if functions are added or removed.
#### [](#AccessAdmin-_updateFunctionAccess-address-RoleId-struct-IAccess-FunctionInfo-bool-)
`_updateFunctionAccess(address target, RoleId roleId, struct IAccess.FunctionInfo func, bool addFunction)` internal
### [](#AccessManagerCloneable)
`AccessManagerCloneable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/AccessManagerCloneable.sol)
import "@etherisc/gif-next/contracts/authorization/AccessManagerCloneable.sol";
An AccessManager based on OpenZeppelin that is cloneable and has a central lock property. The lock property allows to lock all services of a release in a central place. Cloned by upon release preparation and instance cloning.
Modifiers
* [`onlyAdminRole()`](#AccessManagerCloneable-onlyAdminRole--)
Functions
* \[`initialize(admin)`\]
* \[`completeSetup(registry, release)`\]
* \[`canCall(caller, target, selector)`\]
* \[`setLocked(locked)`\]
* \[`getRelease()`\]
* \[`isLocked()`\]
* \[`_checkAndSetRelease(release)`\]
* \[`_checkAndSetRegistry(registry)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagerUpgradeable
* \[`__AccessManager_init(initialAdmin)`\]
* \[`__AccessManager_init_unchained(initialAdmin)`\]
* \[`expiration()`\]
* \[`minSetback()`\]
* \[`isTargetClosed(target)`\]
* \[`getTargetFunctionRole(target, selector)`\]
* \[`getTargetAdminDelay(target)`\]
* \[`getRoleAdmin(roleId)`\]
* \[`getRoleGuardian(roleId)`\]
* \[`getRoleGrantDelay(roleId)`\]
* \[`getAccess(roleId, account)`\]
* \[`hasRole(roleId, account)`\]
* \[`labelRole(roleId, label)`\]
* \[`grantRole(roleId, account, executionDelay)`\]
* \[`revokeRole(roleId, account)`\]
* \[`renounceRole(roleId, callerConfirmation)`\]
* \[`setRoleAdmin(roleId, admin)`\]
* \[`setRoleGuardian(roleId, guardian)`\]
* \[`setGrantDelay(roleId, newDelay)`\]
* \[`_grantRole(roleId, account, grantDelay, executionDelay)`\]
* \[`_revokeRole(roleId, account)`\]
* \[`_setRoleAdmin(roleId, admin)`\]
* \[`_setRoleGuardian(roleId, guardian)`\]
* \[`_setGrantDelay(roleId, newDelay)`\]
* \[`setTargetFunctionRole(target, selectors, roleId)`\]
* \[`_setTargetFunctionRole(target, selector, roleId)`\]
* \[`setTargetAdminDelay(target, newDelay)`\]
* \[`_setTargetAdminDelay(target, newDelay)`\]
* \[`setTargetClosed(target, closed)`\]
* \[`_setTargetClosed(target, closed)`\]
* \[`getSchedule(id)`\]
* \[`getNonce(id)`\]
* \[`schedule(target, data, when)`\]
* \[`execute(target, data)`\]
* \[`cancel(caller, target, data)`\]
* \[`consumeScheduledOp(caller, data)`\]
* \[`_consumeScheduledOp(operationId)`\]
* \[`hashOperation(caller, target, data)`\]
* \[`updateAuthority(target, newAuthority)`\]
MulticallUpgradeable
* \[`__Multicall_init()`\]
* \[`__Multicall_init_unchained()`\]
* \[`multicall(data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
* \[`LogAccessManagerLocked(accessManager, locked)`\]
IAccessManager
* \[`OperationScheduled(operationId, nonce, schedule, caller, target, data)`\]
* \[`OperationExecuted(operationId, nonce)`\]
* \[`OperationCanceled(operationId, nonce)`\]
* \[`RoleLabel(roleId, label)`\]
* \[`RoleGranted(roleId, account, delay, since, newMember)`\]
* \[`RoleRevoked(roleId, account)`\]
* \[`RoleAdminChanged(roleId, admin)`\]
* \[`RoleGuardianChanged(roleId, guardian)`\]
* \[`RoleGrantDelayChanged(roleId, delay, since)`\]
* \[`TargetClosed(target, closed)`\]
* \[`TargetFunctionRoleUpdated(target, selector, roleId)`\]
* \[`TargetAdminDelayUpdated(target, delay, since)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#AccessManagerCloneable-onlyAdminRole--)
`onlyAdminRole()` modifier
#### [](#AccessManagerCloneable-initialize-address-)
`initialize(address admin)` public
#### [](#AccessManagerCloneable-completeSetup-address-VersionPart-)
`completeSetup(address registry, VersionPart release)` external
Completes the setup of the access manager. Links the access manager to the registry and sets the release version.
#### [](#AccessManagerCloneable-canCall-address-address-bytes4-)
`canCall(address caller, address target, bytes4 selector) → bool immediate, uint32 delay` public
Returns true if the caller is authorized to call the target with the given selector and the manager lock is not set to locked. Feturn values as in OpenZeppelin AccessManager. For a locked manager the function reverts with ErrorAccessManagerTargetAdminLocked.
#### [](#AccessManagerCloneable-setLocked-bool-)
`setLocked(bool locked)` external
Locks/unlocks all services of this access manager. Only the corresponding access admin can lock/unlock the services.
#### [](#AccessManagerCloneable-getRelease--)
`getRelease() → VersionPart release` external
Returns the release version of this access manager. For the registry admin release 3 is returned. For the release admin and the instance admin the actual release version is returned.
#### [](#AccessManagerCloneable-isLocked--)
`isLocked() → bool` public
Returns true iff all contracts of this access manager are locked.
#### [](#AccessManagerCloneable-_checkAndSetRelease-VersionPart-)
`_checkAndSetRelease(VersionPart release)` internal
#### [](#AccessManagerCloneable-_checkAndSetRegistry-address-)
`_checkAndSetRegistry(address registry)` internal
#### [](#AccessManagerCloneable-LogAccessManagerLocked-address-bool-)
`LogAccessManagerLocked(address indexed accessManager, bool indexed locked)` event
### [](#Authorization)
`Authorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/Authorization.sol)
import "@etherisc/gif-next/contracts/authorization/Authorization.sol";
Functions
* \[`constructor(mainTargetName, domain, release, commitHash, targetType, includeTokenHandler)`\]
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupServiceTargets()`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
* \[`_setupTargetAuthorizations()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#Authorization-constructor-string-ObjectType-uint8-string-enum-IAccess-TargetType-bool-)
`constructor(string mainTargetName, ObjectType domain, uint8 release, string commitHash, enum IAccess.TargetType targetType, bool includeTokenHandler)` public
#### [](#Authorization-getTokenHandlerName--)
`getTokenHandlerName() → string` public
Returns the token hander name. Only components have a token handler.
#### [](#Authorization-getTokenHandlerTarget--)
`getTokenHandlerTarget() → Str` public
Returns the token hander target. Only components have a token handler.
#### [](#Authorization-getTarget-string-)
`getTarget(string targetName) → Str target` public
#### [](#Authorization-getTargets--)
`getTargets() → Str[] targets` external
Returns the complete list of targets.
#### [](#Authorization-targetExists-Str-)
`targetExists(Str target) → bool exists` external
Returns true iff the specified target exists.
#### [](#Authorization-_setupServiceTargets--)
`_setupServiceTargets()` internal
Sets up the relevant service targets for the component. Overwrite this function for use case specific authorizations.
#### [](#Authorization-_setupTargets--)
`_setupTargets()` internal
Sets up the relevant (non-service) targets for the component. Overwrite this function for use case specific authorizations.
#### [](#Authorization-_setupRoles--)
`_setupRoles()` internal
Sets up the relevant roles for the component. Overwrite this function for use case specific authorizations.
#### [](#Authorization-_setupTokenHandlerAuthorizations--)
`_setupTokenHandlerAuthorizations()` internal
Sets up the relevant component’s token handler authorizations. Overwrite this function for use case specific authorizations.
#### [](#Authorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
#### [](#Authorization-_addCustomRole-RoleId-RoleId-uint32-string-)
`_addCustomRole(RoleId roleId, RoleId adminRoleId, uint32 maxMemberCount, string name)` internal
Add a contract role for the provided role id and name.
#### [](#Authorization-_addGifTarget-string-)
`_addGifTarget(string contractName)` internal
Add a gif target with its corresponding contract role
#### [](#Authorization-_addInstanceTarget-string-)
`_addInstanceTarget(string contractName)` internal
Add an instance target with its corresponding contract role
#### [](#Authorization-_addTarget-string-)
`_addTarget(string name)` internal
Use this method to to add an authorized target.
#### [](#Authorization-_toTargetRoleId-ObjectType-)
`_toTargetRoleId(ObjectType targetDomain) → RoleId targetRoleId` internal
Role id for targets registry, staking and instance
#### [](#Authorization-_toTargetRoleName-string-)
`_toTargetRoleName(string targetName) → string` internal
Returns the role name for the specified target name
### [](#ServiceAuthorization)
`ServiceAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/authorization/ServiceAuthorization.sol)
import "@etherisc/gif-next/contracts/authorization/ServiceAuthorization.sol";
Base contract for release specific service authorization contracts and for Authorization contracts.
Functions
* \[`constructor(mainTargetName, domain, release, commitHash)`\]
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#ServiceAuthorization-constructor-string-ObjectType-uint8-string-)
`constructor(string mainTargetName, ObjectType domain, uint8 release, string commitHash)` public
#### [](#ServiceAuthorization-getDomain--)
`getDomain() → ObjectType targetDomain` public
Returns the main domain of the authorization.
#### [](#ServiceAuthorization-getRelease--)
`getRelease() → VersionPart release` public
Returns the release (VersionPart) for which the authorizations are defined by this contract. Matches with the release returned by the linked service authorization.
#### [](#ServiceAuthorization-getCommitHash--)
`getCommitHash() → string commitHash` external
Returns the commit hash for the related GIF release.
#### [](#ServiceAuthorization-getMainTargetName--)
`getMainTargetName() → string name` public
Returns the main target id name as string. This name is used to derive the target id and a corresponding target role name Overwrite this function to change the basic pool target name.
#### [](#ServiceAuthorization-getMainTarget--)
`getMainTarget() → Str target` external
Returns the main target.
#### [](#ServiceAuthorization-getServiceDomains--)
`getServiceDomains() → ObjectType[] serviceDomains` external
Returns the full list of service domains for this release. Services need to be registered for the release in revers order of this list.
#### [](#ServiceAuthorization-getServiceDomain-uint256-)
`getServiceDomain(uint256 idx) → ObjectType serviceDomain` external
Returns the service domain for the provided index.
#### [](#ServiceAuthorization-getServiceTarget-ObjectType-)
`getServiceTarget(ObjectType serviceDomain) → Str target` public
Returns the service target for the specified domain.
#### [](#ServiceAuthorization-getServiceRole-ObjectType-)
`getServiceRole(ObjectType serviceDomain) → RoleId serviceRoleId` public
Returns the service target for the specified domain.
#### [](#ServiceAuthorization-getServiceAddress-ObjectType-)
`getServiceAddress(ObjectType serviceDomain) → address service` external
Returns the expected service address for the provided domain.
#### [](#ServiceAuthorization-getTargetRole-Str-)
`getTargetRole(Str target) → RoleId roleId` public
Returns the role id associated with the target. If no role is associated with the target the zero role id is returned.
#### [](#ServiceAuthorization-roleExists-RoleId-)
`roleExists(RoleId roleId) → bool exists` public
Returns true iff the role exists.
#### [](#ServiceAuthorization-getRoles--)
`getRoles() → RoleId[] roles` external
Returns the list of involved roles.
#### [](#ServiceAuthorization-getRoleInfo-RoleId-)
`getRoleInfo(RoleId roleId) → struct IAccess.RoleInfo info` external
Returns the role info for the provided role id.
#### [](#ServiceAuthorization-getRoleName-RoleId-)
`getRoleName(RoleId roleId) → string roleName` external
Returns the name for the provided role id.
#### [](#ServiceAuthorization-getAuthorizedRoles-Str-)
`getAuthorizedRoles(Str target) → RoleId[] roleIds` external
For the given target the list of authorized role ids is returned
#### [](#ServiceAuthorization-getAuthorizedFunctions-Str-RoleId-)
`getAuthorizedFunctions(Str target, RoleId roleId) → struct IAccess.FunctionInfo[] authorizatedFunctions` external
For the given target and role id the list of authorized functions is returned
#### [](#ServiceAuthorization-_setupDomains--)
`_setupDomains()` internal
Defines service domains relevant for the authorization. When used for ReleaseAdmin the list defines the services to be registered for the release. IMPORTANT: Both the list of the service domains as well as the ordering of the domains is important. Trying to register services not in this list or register services in a different order will result in an error.
#### [](#ServiceAuthorization-_setupDomainAuthorizations--)
`_setupDomainAuthorizations()` internal
Overwrite this function for a specific realease.
#### [](#ServiceAuthorization-_authorizeServiceDomain-ObjectType-address-)
`_authorizeServiceDomain(ObjectType serviceDomain, address serviceAddress)` internal
Use this method to to add an authorized domain. The services will need to be registered in the order they are added using this function.
#### [](#ServiceAuthorization-_addTargetWithRole-string-RoleId-string-)
`_addTargetWithRole(string targetName, RoleId roleId, string roleName)` internal
Use this method to to add an authorized target together with its target role.
#### [](#ServiceAuthorization-_addRole-RoleId-struct-IAccess-RoleInfo-)
`_addRole(RoleId roleId, struct IAccess.RoleInfo info)` internal
Use this method to to add an authorized role.
#### [](#ServiceAuthorization-_authorizeForService-ObjectType-ObjectType-)
`_authorizeForService(ObjectType serviceDomain, ObjectType authorizedDomain) → struct IAccess.FunctionInfo[] authorizatedFunctions` internal
Use this method to authorize the specified domain to access the service domain.
#### [](#ServiceAuthorization-_authorizeForTarget-string-RoleId-)
`_authorizeForTarget(string target, RoleId authorizedRoleId) → struct IAccess.FunctionInfo[] authorizatedFunctions` internal
Use this method to authorize the specified role to access the target.
#### [](#ServiceAuthorization-_authorize-struct-IAccess-FunctionInfo---bytes4-string-)
`_authorize(struct IAccess.FunctionInfo[] functions, bytes4 selector, string name)` internal
Use this method to authorize a specific function authorization
[← accounting](/gif-next/3.x/api/accounting)
[distribution →](/gif-next/3.x/api/distribution)
---
# Instance - Etherisc Docs
Instance
========
Contains the instance related contracts.
[](#contracts)
Contracts
------------------------
### [](#InstanceAdmin)
`InstanceAdmin`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/InstanceAdmin.sol)
import "@etherisc/gif-next/contracts/instance/InstanceAdmin.sol";
Modifiers
* [`onlyInstanceService()`](#InstanceAdmin-onlyInstanceService--)
Functions
* \[`constructor(accessManager)`\]
* \[`completeSetup(registry, authorization, release, instance)`\]
* \[`_setupServices(authorization)`\]
* \[`_createInstanceTargets(instanceTargetName)`\]
* \[`_createInstanceTarget(target, name)`\]
* \[`initializeComponentAuthorization(componentAddress, expectedType)`\]
* \[`createRole(name, adminRoleId, maxMemberCount)`\]
* \[`setRoleActive(roleId, active)`\]
* \[`grantRole(roleId, account)`\]
* \[`revokeRole(roleId, account)`\]
* \[`createTarget(target, name)`\]
* \[`authorizeFunctions(target, roleId, functions)`\]
* \[`unauthorizeFunctions(target, functions)`\]
* \[`setInstanceLocked(locked)`\]
* \[`setTargetLocked(target, locked)`\]
* \[`setContractLocked(target, locked)`\]
* \[`getInstanceAuthorization()`\]
* \[`_createTargetAuthorizations(authorization)`\]
AccessAdmin
* \[`initialize(authority, adminName)`\]
* \[`__AccessAdmin_init(authority, adminName)`\]
* \[`getRelease()`\]
* \[`getRegistry()`\]
* \[`getLinkedNftId()`\]
* \[`getAuthorization()`\]
* \[`isLocked()`\]
* \[`roles()`\]
* \[`getRoleId(idx)`\]
* \[`getAdminRole()`\]
* \[`getPublicRole()`\]
* \[`roleExists(roleId)`\]
* \[`getRoleForName(name)`\]
* \[`getRoleInfo(roleId)`\]
* \[`isRoleActive(roleId)`\]
* \[`isRoleCustom(roleId)`\]
* \[`roleMembers(roleId)`\]
* \[`getRoleMember(roleId, idx)`\]
* \[`isRoleMember(roleId, account)`\]
* \[`isRoleAdmin(roleId, account)`\]
* \[`targetExists(target)`\]
* \[`targets()`\]
* \[`getTargetAddress(idx)`\]
* \[`getTargetInfo(target)`\]
* \[`getTargetForName(name)`\]
* \[`isTargetLocked(target)`\]
* \[`authorizedFunctions(target)`\]
* \[`getAuthorizedFunction(target, idx)`\]
* \[`getFunctionInfo(target, selector)`\]
* \[`_linkToNftOwnable(registerable)`\]
* \[`_createRoles(authorization)`\]
* \[`_createRole(roleId, info, revertOnExistingRole)`\]
* \[`_setRoleActive(roleId, active)`\]
* \[`_grantRoleToAccount(roleId, account)`\]
* \[`_revokeRoleFromAccount(roleId, account)`\]
* \[`_getOrCreateTargetRoleIdAndName(target, targetName, targetType)`\]
* \[`_createTarget(target, targetName, targetType, checkAuthority)`\]
* \[`_createTargetUnchecked(target, targetName, targetType, managed)`\]
* \[`_setTargetLocked(target, locked)`\]
* \[`_authorizeFunctions(authorization, target, roleId)`\]
* \[`_authorizeTargetFunctions(target, roleId, functions, onlyComponentOrContractTargets, addFunctions)`\]
* \[`_updateFunctionAccess(target, roleId, func, addFunction)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IAccessAdmin
* \[`LogAccessAdminRoleCreated(roleId, roleAdminId, targetType, name, admin)`\]
* \[`LogAccessAdminTargetCreated(target, roleId, managed, name, admin)`\]
* \[`LogAccessAdminRoleActivatedSet(roleId, active, admin, lastUpdateIn)`\]
* \[`LogAccessAdminRoleGranted(account, roleName, admin)`\]
* \[`LogAccessAdminRoleRevoked(account, roleName, admin)`\]
* \[`LogAccessAdminTargetLockedSet(target, locked, admin, lastUpdateIn)`\]
* \[`LogAccessAdminFunctionGranted(target, selector, roleId, func, admin, lastUpdateIn)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#InstanceAdmin-onlyInstanceService--)
`onlyInstanceService()` modifier
#### [](#InstanceAdmin-constructor-address-)
`constructor(address accessManager)` public
Only used for master instance admin.
#### [](#InstanceAdmin-completeSetup-address-address-VersionPart-address-)
`completeSetup(address registry, address authorization, VersionPart release, address instance)` external
Completes the initialization of this instance admin using the provided instance, registry and version. Important: Initialization of instance admin is only complete after calling this function. Important: The instance MUST be registered and all instance supporting contracts must be wired to this instance.
#### [](#InstanceAdmin-_setupServices-contract-IAuthorization-)
`_setupServices(contract IAuthorization authorization)` internal
grants the service roles to the service addresses based on the authorization specification. Service addresses used for the granting are determined by the registry and the release of this instance.
#### [](#InstanceAdmin-_createInstanceTargets-string-)
`_createInstanceTargets(string instanceTargetName)` internal
#### [](#InstanceAdmin-_createInstanceTarget-address-string-)
`_createInstanceTarget(address target, string name)` internal
#### [](#InstanceAdmin-initializeComponentAuthorization-address-ObjectType-)
`initializeComponentAuthorization(address componentAddress, ObjectType expectedType)` external
Initializes the authorization for the specified component. Important: The component MUST be registered.
#### [](#InstanceAdmin-createRole-string-RoleId-uint32-)
`createRole(string name, RoleId adminRoleId, uint32 maxMemberCount) → RoleId roleId` external
Creates a custom role.
#### [](#InstanceAdmin-setRoleActive-RoleId-bool-)
`setRoleActive(RoleId roleId, bool active)` external
Activtes/pauses the specified role.
#### [](#InstanceAdmin-grantRole-RoleId-address-)
`grantRole(RoleId roleId, address account)` external
Grants the provided role to the specified account
#### [](#InstanceAdmin-revokeRole-RoleId-address-)
`revokeRole(RoleId roleId, address account)` external
Revokes the provided role from the specified account
#### [](#InstanceAdmin-createTarget-address-string-)
`createTarget(address target, string name) → RoleId contractRoleId` external
Create a new contract target. The target needs to be an access managed contract.
#### [](#InstanceAdmin-authorizeFunctions-address-RoleId-struct-IAccess-FunctionInfo---)
`authorizeFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions)` external
Add function authorizations for the specified component or custom target.
#### [](#InstanceAdmin-unauthorizeFunctions-address-struct-IAccess-FunctionInfo---)
`unauthorizeFunctions(address target, struct IAccess.FunctionInfo[] functions)` external
Removes function authorizations for the specified component or custom target.
#### [](#InstanceAdmin-setInstanceLocked-bool-)
`setInstanceLocked(bool locked)` external
locks the instance and all its releated targets including component and custom targets.
#### [](#InstanceAdmin-setTargetLocked-address-bool-)
`setTargetLocked(address target, bool locked)` external
#### [](#InstanceAdmin-setContractLocked-address-bool-)
`setContractLocked(address target, bool locked)` external
#### [](#InstanceAdmin-getInstanceAuthorization--)
`getInstanceAuthorization() → contract IAuthorization instanceAuthorizaion` external
Returns the instance authorization specification used to set up this instance admin.
#### [](#InstanceAdmin-_createTargetAuthorizations-contract-IAuthorization-)
`_createTargetAuthorizations(contract IAuthorization authorization)` internal
### [](#InstanceService)
`InstanceService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/InstanceService.sol)
import "@etherisc/gif-next/contracts/instance/InstanceService.sol";
Modifiers
* [`onlyInstance()`](#InstanceService-onlyInstance--)
Functions
* \[`createRole(roleName, adminRoleId, maxMemberCount)`\]
* \[`setRoleActive(roleId, active)`\]
* \[`grantRole(roleId, account)`\]
* \[`revokeRole(roleId, account)`\]
* \[`createTarget(target, name)`\]
* \[`authorizeFunctions(target, roleId, functions)`\]
* \[`unauthorizeFunctions(target, functions)`\]
* \[`setTargetLocked(target, locked)`\]
* \[`setInstanceLocked(locked)`\]
* \[`createInstance(allowAnyToken)`\]
* \[`setStakingLockingPeriod(stakeLockingPeriod)`\]
* \[`setStakingRewardRate(rewardRate)`\]
* \[`setStakingMaxAmount(maxStakedAmount)`\]
* \[`refillInstanceRewardReserves(rewardProvider, dipAmount)`\]
* \[`withdrawInstanceRewardReserves(dipAmount)`\]
* \[`upgradeInstanceReader()`\]
* \[`setAndRegisterMasterInstance(instanceAddress)`\]
* \[`upgradeMasterInstanceReader(instanceReaderAddress)`\]
* \[`getMasterInstanceReader()`\]
* \[`_cloneNewInstanceAdmin()`\]
* \[`_createInstance(instanceAdmin, instanceOwner, allowAnyToken)`\]
* \[`_initialize(owner, data)`\]
* \[`_checkInstance(instanceAddress, expectedRelease)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IInstanceService
* \[`LogInstanceServiceInstanceLocked(instanceNftId, locked)`\]
* \[`LogInstanceServiceInstanceCreated(instanceNftId, instance)`\]
* \[`LogInstanceServiceMasterInstanceRegistered(masterInstanceNftId, masterInstance, masterInstanceAdmin, masterAccessManager, masterInstanceReader, masterInstanceBundleSet, masterInstanceRiskSet, masterInstanceRequestSet, masterInstanceStore, masterProductStore)`\]
* \[`LogInstanceServiceMasterInstanceReaderUpgraded(instanceNfId, oldInstanceReader, newInstanceReader)`\]
* \[`LogInstanceServiceInstanceReaderUpgraded(instanceNfId, oldInstanceReader, newInstanceReader)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#InstanceService-onlyInstance--)
`onlyInstance()` modifier
#### [](#InstanceService-createRole-string-RoleId-uint32-)
`createRole(string roleName, RoleId adminRoleId, uint32 maxMemberCount) → RoleId roleId` external
Creates a new custom role for the calling instance.
#### [](#InstanceService-setRoleActive-RoleId-bool-)
`setRoleActive(RoleId roleId, bool active)` external
Sets the specified custom role as active or inactive for the calling instance.
#### [](#InstanceService-grantRole-RoleId-address-)
`grantRole(RoleId roleId, address account)` external
Grants the specified custom role to the specified account for the calling instance.
#### [](#InstanceService-revokeRole-RoleId-address-)
`revokeRole(RoleId roleId, address account)` external
Revokes the specified custom role from the specified account for the calling instance.
#### [](#InstanceService-createTarget-address-string-)
`createTarget(address target, string name) → RoleId contractRoleId` external
Creates a new custom target for the calling instance. All custom trargets are created with a corresponding contract role.
#### [](#InstanceService-authorizeFunctions-address-RoleId-struct-IAccess-FunctionInfo---)
`authorizeFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions)` external
Authorizes the specified functions for the specified target.
#### [](#InstanceService-unauthorizeFunctions-address-struct-IAccess-FunctionInfo---)
`unauthorizeFunctions(address target, struct IAccess.FunctionInfo[] functions)` external
Removes any role authorization for the specified functions.
#### [](#InstanceService-setTargetLocked-address-bool-)
`setTargetLocked(address target, bool locked)` external
Locks/unlocks the specified target constrolled by the corresponding instance admin.
#### [](#InstanceService-setInstanceLocked-bool-)
`setInstanceLocked(bool locked)` external
Locks the complete instance, including all its components.
#### [](#InstanceService-createInstance-bool-)
`createInstance(bool allowAnyToken) → contract IInstance instance, NftId instanceNftId` external
Creates a new instance. The caller becomes the owner of the new instance. Creation of a new instance is achieved by this service through the creation and registration of a new clone of the master instance and then setting up the initial wiring and authorization of the necessary components.
#### [](#InstanceService-setStakingLockingPeriod-Seconds-)
`setStakingLockingPeriod(Seconds stakeLockingPeriod)` external
#### [](#InstanceService-setStakingRewardRate-UFixed-)
`setStakingRewardRate(UFixed rewardRate)` external
#### [](#InstanceService-setStakingMaxAmount-Amount-)
`setStakingMaxAmount(Amount maxStakedAmount)` external
#### [](#InstanceService-refillInstanceRewardReserves-address-Amount-)
`refillInstanceRewardReserves(address rewardProvider, Amount dipAmount) → Amount newBalance` external
#### [](#InstanceService-withdrawInstanceRewardReserves-Amount-)
`withdrawInstanceRewardReserves(Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target.
#### [](#InstanceService-upgradeInstanceReader--)
`upgradeInstanceReader()` external
#### [](#InstanceService-setAndRegisterMasterInstance-address-)
`setAndRegisterMasterInstance(address instanceAddress) → NftId masterInstanceNftId` external
#### [](#InstanceService-upgradeMasterInstanceReader-address-)
`upgradeMasterInstanceReader(address instanceReaderAddress)` external
#### [](#InstanceService-getMasterInstanceReader--)
`getMasterInstanceReader() → address` external
#### [](#InstanceService-_cloneNewInstanceAdmin--)
`_cloneNewInstanceAdmin() → contract InstanceAdmin clonedAdmin` internal
create new cloned instance admin function used to setup a new instance
#### [](#InstanceService-_createInstance-contract-InstanceAdmin-address-bool-)
`_createInstance(contract InstanceAdmin instanceAdmin, address instanceOwner, bool allowAnyToken) → contract IInstance` internal
create new cloned instance function used to setup a new instance
#### [](#InstanceService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
top level initializer (upgradable contract)
#### [](#InstanceService-_checkInstance-address-VersionPart-)
`_checkInstance(address instanceAddress, VersionPart expectedRelease)` internal
#### [](#InstanceService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#IInstanceService)
`IInstanceService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/IInstanceService.sol)
import "@etherisc/gif-next/contracts/instance/IInstanceService.sol";
Functions
* \[`createRole(roleName, adminRoleId, maxMemberCount)`\]
* \[`setRoleActive(roleId, active)`\]
* \[`grantRole(roleId, account)`\]
* \[`revokeRole(roleId, account)`\]
* \[`createTarget(target, name)`\]
* \[`authorizeFunctions(target, roleId, functions)`\]
* \[`unauthorizeFunctions(target, functions)`\]
* \[`setTargetLocked(target, locked)`\]
* \[`setInstanceLocked(locked)`\]
* \[`createInstance(allowAnyToken)`\]
* \[`upgradeInstanceReader()`\]
* \[`upgradeMasterInstanceReader(instanceReaderAddress)`\]
* \[`setStakingLockingPeriod(stakeLockingPeriod)`\]
* \[`setStakingRewardRate(rewardRate)`\]
* \[`setStakingMaxAmount(maxStakedAmount)`\]
* \[`refillInstanceRewardReserves(rewardProvider, dipAmount)`\]
* \[`withdrawInstanceRewardReserves(dipAmount)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogInstanceServiceInstanceLocked(instanceNftId, locked)`\]
* \[`LogInstanceServiceInstanceCreated(instanceNftId, instance)`\]
* \[`LogInstanceServiceMasterInstanceRegistered(masterInstanceNftId, masterInstance, masterInstanceAdmin, masterAccessManager, masterInstanceReader, masterInstanceBundleSet, masterInstanceRiskSet, masterInstanceRequestSet, masterInstanceStore, masterProductStore)`\]
* \[`LogInstanceServiceMasterInstanceReaderUpgraded(instanceNfId, oldInstanceReader, newInstanceReader)`\]
* \[`LogInstanceServiceInstanceReaderUpgraded(instanceNfId, oldInstanceReader, newInstanceReader)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IInstanceService-createRole-string-RoleId-uint32-)
`createRole(string roleName, RoleId adminRoleId, uint32 maxMemberCount) → RoleId roleId` external
Creates a new custom role for the calling instance.
#### [](#IInstanceService-setRoleActive-RoleId-bool-)
`setRoleActive(RoleId roleId, bool active)` external
Sets the specified custom role as active or inactive for the calling instance.
#### [](#IInstanceService-grantRole-RoleId-address-)
`grantRole(RoleId roleId, address account)` external
Grants the specified custom role to the specified account for the calling instance.
#### [](#IInstanceService-revokeRole-RoleId-address-)
`revokeRole(RoleId roleId, address account)` external
Revokes the specified custom role from the specified account for the calling instance.
#### [](#IInstanceService-createTarget-address-string-)
`createTarget(address target, string name) → RoleId contractRoleId` external
Creates a new custom target for the calling instance. All custom trargets are created with a corresponding contract role.
#### [](#IInstanceService-authorizeFunctions-address-RoleId-struct-IAccess-FunctionInfo---)
`authorizeFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions)` external
Authorizes the specified functions for the specified target.
#### [](#IInstanceService-unauthorizeFunctions-address-struct-IAccess-FunctionInfo---)
`unauthorizeFunctions(address target, struct IAccess.FunctionInfo[] functions)` external
Removes any role authorization for the specified functions.
#### [](#IInstanceService-setTargetLocked-address-bool-)
`setTargetLocked(address target, bool locked)` external
Locks/unlocks the specified target constrolled by the corresponding instance admin.
#### [](#IInstanceService-setInstanceLocked-bool-)
`setInstanceLocked(bool locked)` external
Locks the complete instance, including all its components.
#### [](#IInstanceService-createInstance-bool-)
`createInstance(bool allowAnyToken) → contract IInstance instance, NftId instanceNftId` external
Creates a new instance. The caller becomes the owner of the new instance. Creation of a new instance is achieved by this service through the creation and registration of a new clone of the master instance and then setting up the initial wiring and authorization of the necessary components.
#### [](#IInstanceService-upgradeInstanceReader--)
`upgradeInstanceReader()` external
#### [](#IInstanceService-upgradeMasterInstanceReader-address-)
`upgradeMasterInstanceReader(address instanceReaderAddress)` external
#### [](#IInstanceService-setStakingLockingPeriod-Seconds-)
`setStakingLockingPeriod(Seconds stakeLockingPeriod)` external
#### [](#IInstanceService-setStakingRewardRate-UFixed-)
`setStakingRewardRate(UFixed rewardRate)` external
#### [](#IInstanceService-setStakingMaxAmount-Amount-)
`setStakingMaxAmount(Amount maxStakedAmount)` external
#### [](#IInstanceService-refillInstanceRewardReserves-address-Amount-)
`refillInstanceRewardReserves(address rewardProvider, Amount dipAmount) → Amount newBalance` external
#### [](#IInstanceService-withdrawInstanceRewardReserves-Amount-)
`withdrawInstanceRewardReserves(Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target.
#### [](#IInstanceService-LogInstanceServiceInstanceLocked-NftId-bool-)
`LogInstanceServiceInstanceLocked(NftId indexed instanceNftId, bool indexed locked)` event
#### [](#IInstanceService-LogInstanceServiceInstanceCreated-NftId-address-)
`LogInstanceServiceInstanceCreated(NftId indexed instanceNftId, address indexed instance)` event
#### [](#IInstanceService-LogInstanceServiceMasterInstanceRegistered-NftId-address-address-address-address-address-address-address-address-address-)
`LogInstanceServiceMasterInstanceRegistered(NftId indexed masterInstanceNftId, address indexed masterInstance, address indexed masterInstanceAdmin, address masterAccessManager, address masterInstanceReader, address masterInstanceBundleSet, address masterInstanceRiskSet, address masterInstanceRequestSet, address masterInstanceStore, address masterProductStore)` event
#### [](#IInstanceService-LogInstanceServiceMasterInstanceReaderUpgraded-NftId-address-address-)
`LogInstanceServiceMasterInstanceReaderUpgraded(NftId indexed instanceNfId, address indexed oldInstanceReader, address indexed newInstanceReader)` event
#### [](#IInstanceService-LogInstanceServiceInstanceReaderUpgraded-NftId-address-address-)
`LogInstanceServiceInstanceReaderUpgraded(NftId indexed instanceNfId, address indexed oldInstanceReader, address indexed newInstanceReader)` event
### [](#InstanceReader)
`InstanceReader`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/InstanceReader.sol)
import "@etherisc/gif-next/contracts/instance/InstanceReader.sol";
Central reader contract for a specific instance. Provides reading functions for all instance data and related component data.
Functions
* \[`initialize()`\]
* \[`initializeWithInstance(instanceAddress)`\]
* \[`getRegistry()`\]
* \[`getInstanceNftId()`\]
* \[`getInstance()`\]
* \[`getComponentInfo(componentNftId)`\]
* \[`getToken(componentNftId)`\]
* \[`getWallet(componentNftId)`\]
* \[`getTokenHandler(componentNftId)`\]
* \[`getBalanceAmount(targetNftId)`\]
* \[`getFeeAmount(targetNftId)`\]
* \[`getLockedAmount(targetNftId)`\]
* \[`products()`\]
* \[`getProduct(idx)`\]
* \[`getProductInfo(productNftId)`\]
* \[`getFeeInfo(productNftId)`\]
* \[`risks(productNftId)`\]
* \[`activeRisks(productNftId)`\]
* \[`getRiskId(productNftId, idx)`\]
* \[`getActiveRiskId(productNftId, idx)`\]
* \[`isProductRisk(productNftId, riskId)`\]
* \[`getRiskInfo(riskId)`\]
* \[`getRiskState(riskId)`\]
* \[`policiesForRisk(riskId)`\]
* \[`getPolicyForRisk(riskId, idx)`\]
* \[`policiesForBundle(bundleNftId)`\]
* \[`getPolicyForBundle(bundleNftId, idx)`\]
* \[`getPolicyInfo(policyNftId)`\]
* \[`getPolicyState(policyNftId)`\]
* \[`policyIsActive(policyNftId)`\]
* \[`claims(policyNftId)`\]
* \[`getClaimId(idx)`\]
* \[`getClaimInfo(policyNftId, claimId)`\]
* \[`getClaimState(policyNftId, claimId)`\]
* \[`getRemainingClaimableAmount(policyNftId)`\]
* \[`payouts(policyNftId, claimId)`\]
* \[`getPayoutId(claimId, idx)`\]
* \[`getPayoutInfo(policyNftId, payoutId)`\]
* \[`getPayoutState(policyNftId, payoutId)`\]
* \[`getPremiumInfo(policyNftId)`\]
* \[`getPremiumState(policyNftId)`\]
* \[`getRequestInfo(requestId)`\]
* \[`getRequestState(requestId)`\]
* \[`getActiveRequests(oracleNftId)`\]
* \[`getActiveRequestAt(oracleNftId, idx)`\]
* \[`isRequestActive(oracleNftId, requestId)`\]
* \[`getPoolInfo(poolNftId)`\]
* \[`bundles(poolNftId)`\]
* \[`activeBundles(poolNftId)`\]
* \[`getBundleNftId(poolNftId, idx)`\]
* \[`getActiveBundleNftId(poolNftId, idx)`\]
* \[`getBundleInfo(bundleNftId)`\]
* \[`getBundleState(bundleNftId)`\]
* \[`getDistributorTypeInfo(distributorType)`\]
* \[`getDistributorInfo(distributorNftId)`\]
* \[`toReferralId(distributionNftId, referralCode)`\]
* \[`isReferralValid(distributionNftId, referralId)`\]
* \[`getReferralInfo(referralId)`\]
* \[`getDiscountPercentage(referralId)`\]
* \[`roles()`\]
* \[`getRoleId(idx)`\]
* \[`getRoleForName(name)`\]
* \[`getInstanceOwnerRole()`\]
* \[`getRoleInfo(roleId)`\]
* \[`roleExists(roleId)`\]
* \[`isRoleCustom(roleId)`\]
* \[`isRoleActive(roleId)`\]
* \[`roleMembers(roleId)`\]
* \[`getRoleMember(roleId, idx)`\]
* \[`isRoleMember(roleId, account)`\]
* \[`isRoleAdmin(roleId, account)`\]
* \[`targets()`\]
* \[`getTargetAddress(idx)`\]
* \[`getTargetInfo(target)`\]
* \[`targetExists(target)`\]
* \[`isLocked(target)`\]
* \[`authorizedFunctions(target)`\]
* \[`getAuthorizedFunction(target, idx)`\]
* \[`toFunction(selector, name)`\]
* \[`getInstanceAdmin()`\]
* \[`getBundleSet()`\]
* \[`getRiskSet()`\]
* \[`getMetadata(key)`\]
* \[`getState(key)`\]
* \[`toInt(value)`\]
* \[`toString(str)`\]
* \[`toUFixed(value, exp)`\]
* \[`_toPolicyKey(policyNftId)`\]
* \[`_toPremiumKey(policyNftId)`\]
* \[`_toBundleKey(poolNftId)`\]
* \[`_toComponentKey(componentNftId)`\]
#### [](#InstanceReader-initialize--)
`initialize()` public
This initializer needs to be called from the instance itself.
#### [](#InstanceReader-initializeWithInstance-address-)
`initializeWithInstance(address instanceAddress)` public
Initializer to upgrade instance reader via instance service
#### [](#InstanceReader-getRegistry--)
`getRegistry() → contract IRegistry registry` public
Returns the registry this instance is registered in.
#### [](#InstanceReader-getInstanceNftId--)
`getInstanceNftId() → NftId instanceNftid` public
Returns the instance NFT ID.
#### [](#InstanceReader-getInstance--)
`getInstance() → contract IInstance instance` public
Returns the instance contract.
#### [](#InstanceReader-getComponentInfo-NftId-)
`getComponentInfo(NftId componentNftId) → struct IComponents.ComponentInfo info` public
Returns the component info for the given component NFT ID.
#### [](#InstanceReader-getToken-NftId-)
`getToken(NftId componentNftId) → contract IERC20Metadata token` public
Returns the registered token for the given component NFT ID.
#### [](#InstanceReader-getWallet-NftId-)
`getWallet(NftId componentNftId) → address wallet` public
Returns the current wallet address for the given component NFT ID. The wallet address is either the component’s own address or any other wallet address specified by the component owner. The wallet holds the component’s funds. Tokens collected by the component are transferred to the wallet and Tokens distributed from the component are transferred from this wallet.
#### [](#InstanceReader-getTokenHandler-NftId-)
`getTokenHandler(NftId componentNftId) → contract TokenHandler tokenHandler` public
Returns the token handler for the given component NFT ID. The token handler manages all transfers from/to the component’s wallet. To allow a component to collect funds from an account, it has to create a corresponding allowance from the account to the address of the component’s token handler.
#### [](#InstanceReader-getBalanceAmount-NftId-)
`getBalanceAmount(NftId targetNftId) → Amount` external
Returns the current token balance amount for the given component NFT ID. The balance amount includes the fee amount.
#### [](#InstanceReader-getFeeAmount-NftId-)
`getFeeAmount(NftId targetNftId) → Amount` external
Returns the current fee amount for the given NFT ID. The target NFT ID may reference a component, a distributor or a bundle.
#### [](#InstanceReader-getLockedAmount-NftId-)
`getLockedAmount(NftId targetNftId) → Amount` external
Returns the currently locked amount for the given NFT ID. Locked amounts are only tracked for bundles, not for pool. To get the pool locked amount, then locked amounts of the bundles contained in the pool must be summed up. The target NFT ID may only a bundle.
#### [](#InstanceReader-products--)
`products() → uint256 productCount` public
Returns the number of registered products.
#### [](#InstanceReader-getProduct-uint256-)
`getProduct(uint256 idx) → NftId productNftId` public
Returns th product NFT ID for the given index.
#### [](#InstanceReader-getProductInfo-NftId-)
`getProductInfo(NftId productNftId) → struct IComponents.ProductInfo info` public
Returns the product info for the given product NFT ID.
#### [](#InstanceReader-getFeeInfo-NftId-)
`getFeeInfo(NftId productNftId) → struct IComponents.FeeInfo feeInfo` public
Returns the current fee settings for the given product NFT ID.
#### [](#InstanceReader-risks-NftId-)
`risks(NftId productNftId) → uint256 riskCount` public
Returns the total number of registered risks for the specified product.
#### [](#InstanceReader-activeRisks-NftId-)
`activeRisks(NftId productNftId) → uint256 activeRiskCount` public
Returns the number of active risks for the specified product.
#### [](#InstanceReader-getRiskId-NftId-uint256-)
`getRiskId(NftId productNftId, uint256 idx) → RiskId riskId` public
Returns the risk ID for the given product NFT ID and (registered) risk index.
#### [](#InstanceReader-getActiveRiskId-NftId-uint256-)
`getActiveRiskId(NftId productNftId, uint256 idx) → RiskId riskId` public
Returns the active risk ID for the given product NFT ID and (active) risk index.
#### [](#InstanceReader-isProductRisk-NftId-RiskId-)
`isProductRisk(NftId productNftId, RiskId riskId) → bool exists` public
Returns true if the specified risk exists for the given product NFT ID.
#### [](#InstanceReader-getRiskInfo-RiskId-)
`getRiskInfo(RiskId riskId) → struct IRisk.RiskInfo info` public
Returns the risk info for the given risk ID.
#### [](#InstanceReader-getRiskState-RiskId-)
`getRiskState(RiskId riskId) → StateId stateId` public
Returns the risk state for the given risk ID.
#### [](#InstanceReader-policiesForRisk-RiskId-)
`policiesForRisk(RiskId riskId) → uint256 linkedPolicies` public
Returns the number of linked policies for the given risk ID.
#### [](#InstanceReader-getPolicyForRisk-RiskId-uint256-)
`getPolicyForRisk(RiskId riskId, uint256 idx) → NftId linkedPolicyNftId` public
Returns the linked policy NFT ID for the given risk ID and index.
#### [](#InstanceReader-policiesForBundle-NftId-)
`policiesForBundle(NftId bundleNftId) → uint256 linkedPolicies` public
Returns the number of linked policies for the given bundle NFT ID.
#### [](#InstanceReader-getPolicyForBundle-NftId-uint256-)
`getPolicyForBundle(NftId bundleNftId, uint256 idx) → NftId linkedPolicyNftId` public
Returns the linked policy NFT ID for the given risk ID and index.
#### [](#InstanceReader-getPolicyInfo-NftId-)
`getPolicyInfo(NftId policyNftId) → struct IPolicy.PolicyInfo info` public
Returns the info for the given policy NFT ID.
#### [](#InstanceReader-getPolicyState-NftId-)
`getPolicyState(NftId policyNftId) → StateId state` public
Returns the state for the given policy NFT ID.
#### [](#InstanceReader-policyIsActive-NftId-)
`policyIsActive(NftId policyNftId) → bool isCloseable` public
Returns true iff policy is active.
#### [](#InstanceReader-claims-NftId-)
`claims(NftId policyNftId) → uint16 claimCount` public
Returns the number of claims for the given policy NFT ID.
#### [](#InstanceReader-getClaimId-uint256-)
`getClaimId(uint256 idx) → ClaimId claimId` public
Returns the claim ID for the given policy NFT ID and index.
#### [](#InstanceReader-getClaimInfo-NftId-ClaimId-)
`getClaimInfo(NftId policyNftId, ClaimId claimId) → struct IPolicy.ClaimInfo info` public
Returns the claim info for the given policy NFT ID and claim ID.
#### [](#InstanceReader-getClaimState-NftId-ClaimId-)
`getClaimState(NftId policyNftId, ClaimId claimId) → StateId state` public
Returns the current claim state for the given policy NFT ID and claim ID.
#### [](#InstanceReader-getRemainingClaimableAmount-NftId-)
`getRemainingClaimableAmount(NftId policyNftId) → Amount remainingClaimableAmount` public
Returns the remaining claimable amount for the given policy NFT ID. The remaining claimable amount is the difference between the sum insured amount and total approved claim amounts so far.
#### [](#InstanceReader-payouts-NftId-ClaimId-)
`payouts(NftId policyNftId, ClaimId claimId) → uint24 payoutCount` public
Returns the number of payouts for the given policy NFT ID and claim ID.
#### [](#InstanceReader-getPayoutId-ClaimId-uint24-)
`getPayoutId(ClaimId claimId, uint24 idx) → PayoutId payoutId` public
Returns the payout ID for the given claim ID and index.
#### [](#InstanceReader-getPayoutInfo-NftId-PayoutId-)
`getPayoutInfo(NftId policyNftId, PayoutId payoutId) → struct IPolicy.PayoutInfo info` public
Returns the payout info for the given policy NFT ID and payout ID.
#### [](#InstanceReader-getPayoutState-NftId-PayoutId-)
`getPayoutState(NftId policyNftId, PayoutId payoutId) → StateId state` public
Returns the payout state for the given policy NFT ID and payout ID.
#### [](#InstanceReader-getPremiumInfo-NftId-)
`getPremiumInfo(NftId policyNftId) → struct IPolicy.PremiumInfo info` public
Returns the premium info for the given policy NFT ID.
#### [](#InstanceReader-getPremiumState-NftId-)
`getPremiumState(NftId policyNftId) → StateId state` public
Returns the premium state for the given policy NFT ID.
#### [](#InstanceReader-getRequestInfo-RequestId-)
`getRequestInfo(RequestId requestId) → struct IOracle.RequestInfo requestInfo` public
Returns the request info for the given oracle request ID.
#### [](#InstanceReader-getRequestState-RequestId-)
`getRequestState(RequestId requestId) → StateId state` public
Returns the request info for the given oracle request ID.
#### [](#InstanceReader-getActiveRequests-NftId-)
`getActiveRequests(NftId oracleNftId) → uint256 numberOfRequests` external
#### [](#InstanceReader-getActiveRequestAt-NftId-uint256-)
`getActiveRequestAt(NftId oracleNftId, uint256 idx) → RequestId requestId` external
#### [](#InstanceReader-isRequestActive-NftId-RequestId-)
`isRequestActive(NftId oracleNftId, RequestId requestId) → bool isActive` external
#### [](#InstanceReader-getPoolInfo-NftId-)
`getPoolInfo(NftId poolNftId) → struct IComponents.PoolInfo info` public
Returns the pool info for the given pool NFT ID.
#### [](#InstanceReader-bundles-NftId-)
`bundles(NftId poolNftId) → uint256 bundleCount` public
Returns the total number of registered bundles for the given pool.
#### [](#InstanceReader-activeBundles-NftId-)
`activeBundles(NftId poolNftId) → uint256 bundleCount` public
Returns the number of active bundles for the given pool.
#### [](#InstanceReader-getBundleNftId-NftId-uint256-)
`getBundleNftId(NftId poolNftId, uint256 idx) → NftId bundleNftId` public
Returns the bunde NFT ID for the given pool and index.
#### [](#InstanceReader-getActiveBundleNftId-NftId-uint256-)
`getActiveBundleNftId(NftId poolNftId, uint256 idx) → NftId bundleNftId` public
Returns the active bunde NFT ID for the given pool and index.
#### [](#InstanceReader-getBundleInfo-NftId-)
`getBundleInfo(NftId bundleNftId) → struct IBundle.BundleInfo info` public
Returns the bundle info for the given bundle NFT ID.
#### [](#InstanceReader-getBundleState-NftId-)
`getBundleState(NftId bundleNftId) → StateId state` public
Returns the bundle state for the given bundle NFT ID.
#### [](#InstanceReader-getDistributorTypeInfo-DistributorType-)
`getDistributorTypeInfo(DistributorType distributorType) → struct IDistribution.DistributorTypeInfo info` public
#### [](#InstanceReader-getDistributorInfo-NftId-)
`getDistributorInfo(NftId distributorNftId) → struct IDistribution.DistributorInfo info` public
#### [](#InstanceReader-toReferralId-NftId-string-)
`toReferralId(NftId distributionNftId, string referralCode) → ReferralId referralId` public
#### [](#InstanceReader-isReferralValid-NftId-ReferralId-)
`isReferralValid(NftId distributionNftId, ReferralId referralId) → bool isValid` external
#### [](#InstanceReader-getReferralInfo-ReferralId-)
`getReferralInfo(ReferralId referralId) → struct IDistribution.ReferralInfo info` public
#### [](#InstanceReader-getDiscountPercentage-ReferralId-)
`getDiscountPercentage(ReferralId referralId) → UFixed discountPercentage, ReferralStatus status` public
#### [](#InstanceReader-roles--)
`roles() → uint256` public
Returns the number of defined roles.
#### [](#InstanceReader-getRoleId-uint256-)
`getRoleId(uint256 idx) → RoleId roleId` public
Returns the role ID for the given index.
#### [](#InstanceReader-getRoleForName-string-)
`getRoleForName(string name) → RoleId roleId, bool exists` public
Returns the role ID for the given index.
#### [](#InstanceReader-getInstanceOwnerRole--)
`getInstanceOwnerRole() → RoleId roleId` public
Returns the role ID for the instance owner role. This role may be used as a "root" admin role for other custom roles defined for this instance.
#### [](#InstanceReader-getRoleInfo-RoleId-)
`getRoleInfo(RoleId roleId) → struct IAccess.RoleInfo roleInfo` public
Returns the role info for the given role ID.
#### [](#InstanceReader-roleExists-RoleId-)
`roleExists(RoleId roleId) → bool exists` public
Returns true iff the provided role ID is defined for this instance.
#### [](#InstanceReader-isRoleCustom-RoleId-)
`isRoleCustom(RoleId roleId) → bool isCustom` public
Returns true iff the provided role ID represents a custom role ID.
#### [](#InstanceReader-isRoleActive-RoleId-)
`isRoleActive(RoleId roleId) → bool isActive` public
Returns true iff the provided role ID is active.
#### [](#InstanceReader-roleMembers-RoleId-)
`roleMembers(RoleId roleId) → uint256 numberOfMembers` public
Returns the number of members (accounts) for the given role ID.
#### [](#InstanceReader-getRoleMember-RoleId-uint256-)
`getRoleMember(RoleId roleId, uint256 idx) → address account` public
Returns the member (account address) for the given role ID and index.
#### [](#InstanceReader-isRoleMember-RoleId-address-)
`isRoleMember(RoleId roleId, address account) → bool isMember` public
Returns true iff the given account is a member of the specified role ID.
#### [](#InstanceReader-isRoleAdmin-RoleId-address-)
`isRoleAdmin(RoleId roleId, address account) → bool isMember` public
Returns true iff the given account is an admin of the specified role ID. Role admins may grant and revoke the role to other accounts.
#### [](#InstanceReader-targets--)
`targets() → uint256 targetCount` public
Returns the number of targets (contracts) defined for this instance.
#### [](#InstanceReader-getTargetAddress-uint256-)
`getTargetAddress(uint256 idx) → address target` public
Returns the target address for the given index.
#### [](#InstanceReader-getTargetInfo-address-)
`getTargetInfo(address target) → struct IAccess.TargetInfo targetInfo` public
Returns the target info for the given target address.
#### [](#InstanceReader-targetExists-address-)
`targetExists(address target) → bool exists` public
Returns true iff the given target is defined for this instance.
#### [](#InstanceReader-isLocked-address-)
`isLocked(address target) → bool` public
Returns true iff the given target is locked.
#### [](#InstanceReader-authorizedFunctions-address-)
`authorizedFunctions(address target) → uint256 numberOfFunctions` external
Returns the number of authorized functions for the given target.
#### [](#InstanceReader-getAuthorizedFunction-address-uint256-)
`getAuthorizedFunction(address target, uint256 idx) → struct IAccess.FunctionInfo func, RoleId roleId` external
Returns the authorized function info for the given target and index.
#### [](#InstanceReader-toFunction-bytes4-string-)
`toFunction(bytes4 selector, string name) → struct IAccess.FunctionInfo` public
Returns a function info for the given function selector and function name. The function selector must not be zero and the function name must not be empty.
#### [](#InstanceReader-getInstanceAdmin--)
`getInstanceAdmin() → contract InstanceAdmin instanceAdmin` external
#### [](#InstanceReader-getBundleSet--)
`getBundleSet() → contract BundleSet bundleSet` external
#### [](#InstanceReader-getRiskSet--)
`getRiskSet() → contract RiskSet riskSet` external
#### [](#InstanceReader-getMetadata-Key32-)
`getMetadata(Key32 key) → struct IBaseStore.Metadata metadata` public
#### [](#InstanceReader-getState-Key32-)
`getState(Key32 key) → StateId state` public
#### [](#InstanceReader-toInt-UFixed-)
`toInt(UFixed value) → uint256` public
#### [](#InstanceReader-toString-Str-)
`toString(Str str) → string` public
#### [](#InstanceReader-toUFixed-uint256-int8-)
`toUFixed(uint256 value, int8 exp) → UFixed` public
#### [](#InstanceReader-_toPolicyKey-NftId-)
`_toPolicyKey(NftId policyNftId) → Key32` internal
#### [](#InstanceReader-_toPremiumKey-NftId-)
`_toPremiumKey(NftId policyNftId) → Key32` internal
#### [](#InstanceReader-_toBundleKey-NftId-)
`_toBundleKey(NftId poolNftId) → Key32` internal
#### [](#InstanceReader-_toComponentKey-NftId-)
`_toComponentKey(NftId componentNftId) → Key32` internal
### [](#Instance)
`Instance`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/Instance.sol)
import "@etherisc/gif-next/contracts/instance/Instance.sol";
Modifiers
* [`onlyCustomRoleAdmin(roleId)`](#Instance-onlyCustomRoleAdmin-RoleId-)
Functions
* \[`initialize(instanceContracts, registry, release, initialOwner, tokenRegistryDisabled)`\]
* \[`setInstanceLocked(locked)`\]
* \[`upgradeInstanceReader()`\]
* \[`registerProduct(product, token)`\]
* \[`setStakingLockingPeriod(stakeLockingPeriod)`\]
* \[`setStakingRewardRate(rewardRate)`\]
* \[`setStakingMaxAmount(maxStakedAmount)`\]
* \[`refillStakingRewardReserves(dipAmount)`\]
* \[`withdrawStakingRewardReserves(dipAmount)`\]
* \[`createRole(roleName, adminRoleId, maxMemberCount)`\]
* \[`setRoleActive(roleId, active)`\]
* \[`grantRole(roleId, account)`\]
* \[`revokeRole(roleId, account)`\]
* \[`createTarget(target, name)`\]
* \[`setTargetLocked(target, locked)`\]
* \[`authorizeFunctions(target, roleId, functions)`\]
* \[`unauthorizeFunctions(target, functions)`\]
* \[`setInstanceReader(instanceReader)`\]
* \[`isInstanceLocked()`\]
* \[`isTargetLocked(target)`\]
* \[`products()`\]
* \[`getProduct(idx)`\]
* \[`getInstanceReader()`\]
* \[`getBundleSet()`\]
* \[`getRiskSet()`\]
* \[`getRequestSet()`\]
* \[`getInstanceAdmin()`\]
* \[`getInstanceStore()`\]
* \[`getProductStore()`\]
* \[`isTokenRegistryDisabled()`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IInstance
* \[`LogInstanceCustomRoleCreated(roleId, roleName, adminRoleId, maxMemberCount)`\]
* \[`LogInstanceCustomRoleActiveSet(roleId, active, caller)`\]
* \[`LogInstanceCustomRoleGranted(roleId, account, caller)`\]
* \[`LogInstanceCustomRoleRevoked(roleId, account, caller)`\]
* \[`LogInstanceCustomTargetCreated(target, targetRoleId, name)`\]
* \[`LogInstanceTargetLocked(target, locked)`\]
* \[`LogInstanceCustomTargetFunctionRoleSet(target, selectors, roleId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Instance-onlyCustomRoleAdmin-RoleId-)
`onlyCustomRoleAdmin(RoleId roleId)` modifier
#### [](#Instance-initialize-struct-IInstance-InstanceContracts-contract-IRegistry-VersionPart-address-bool-)
`initialize(struct IInstance.InstanceContracts instanceContracts, contract IRegistry registry, VersionPart release, address initialOwner, bool tokenRegistryDisabled)` external
#### [](#Instance-setInstanceLocked-bool-)
`setInstanceLocked(bool locked)` external
Locks/unlocks the complete instance, including all its components.
#### [](#Instance-upgradeInstanceReader--)
`upgradeInstanceReader()` external
Upgrades the instance reader to the specified target.
#### [](#Instance-registerProduct-address-address-)
`registerProduct(address product, address token) → NftId productNftId` external
Register a product with the instance.
#### [](#Instance-setStakingLockingPeriod-Seconds-)
`setStakingLockingPeriod(Seconds stakeLockingPeriod)` external
Sets the duration for locking new stakes on this instance..
#### [](#Instance-setStakingRewardRate-UFixed-)
`setStakingRewardRate(UFixed rewardRate)` external
Sets the staking reward rate \[apr\] for this instance.
#### [](#Instance-setStakingMaxAmount-Amount-)
`setStakingMaxAmount(Amount maxStakedAmount)` external
Sets the maximum staked amount for this instance.
#### [](#Instance-refillStakingRewardReserves-Amount-)
`refillStakingRewardReserves(Amount dipAmount) → Amount newRewardReserveBalance` external
Refills the staking reward reserves for the specified target.
#### [](#Instance-withdrawStakingRewardReserves-Amount-)
`withdrawStakingRewardReserves(Amount dipAmount) → Amount newRewardReserveBalance` external
Defunds the staking reward reserves for the specified target.
#### [](#Instance-createRole-string-RoleId-uint32-)
`createRole(string roleName, RoleId adminRoleId, uint32 maxMemberCount) → RoleId roleId` external
Creates a new custom role for the calling instance. Custom roles are intended to be used for access control of custom components and its helper contracts. Custom roles are not intended to be used as target roles for custom contracts.
#### [](#Instance-setRoleActive-RoleId-bool-)
`setRoleActive(RoleId roleId, bool active)` external
Activates/deactivates the specified role. Only instance owner or account with role admin role can call this function.
#### [](#Instance-grantRole-RoleId-address-)
`grantRole(RoleId roleId, address account)` external
Grants the specified role to the account. Only active roles can be granted. Only instance owner or account with role admin role can call this function.
#### [](#Instance-revokeRole-RoleId-address-)
`revokeRole(RoleId roleId, address account)` external
Revokes the specified role from the account. Only instance owner or account with role admin role can call this function.
#### [](#Instance-createTarget-address-string-)
`createTarget(address target, string name) → RoleId targetRoleId` external
Creates a new custom target. Custom targets are intended to be used for access control helper contracts of components. Custom targets are not intended to be used for components.
#### [](#Instance-setTargetLocked-address-bool-)
`setTargetLocked(address target, bool locked)` external
Locks/unlocks the specified target.
#### [](#Instance-authorizeFunctions-address-RoleId-struct-IAccess-FunctionInfo---)
`authorizeFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions)` external
Authorizes the specified functions for the target and provided role.
#### [](#Instance-unauthorizeFunctions-address-struct-IAccess-FunctionInfo---)
`unauthorizeFunctions(address target, struct IAccess.FunctionInfo[] functions)` external
Removes any role authorization for the specified functions.
#### [](#Instance-setInstanceReader-contract-InstanceReader-)
`setInstanceReader(contract InstanceReader instanceReader)` external
Sets the instance reader for the instance. Permissioned: only the instance service may call this function.
#### [](#Instance-isInstanceLocked--)
`isInstanceLocked() → bool` external
returns the overall locking state of the instance (including all components)
#### [](#Instance-isTargetLocked-address-)
`isTargetLocked(address target) → bool` external
returns the locking state of the specified target
#### [](#Instance-products--)
`products() → uint256 productCount` external
#### [](#Instance-getProduct-uint256-)
`getProduct(uint256 idx) → NftId productNftId` external
#### [](#Instance-getInstanceReader--)
`getInstanceReader() → contract InstanceReader` external
#### [](#Instance-getBundleSet--)
`getBundleSet() → contract BundleSet` external
#### [](#Instance-getRiskSet--)
`getRiskSet() → contract RiskSet` external
#### [](#Instance-getRequestSet--)
`getRequestSet() → contract RequestSet` external
#### [](#Instance-getInstanceAdmin--)
`getInstanceAdmin() → contract InstanceAdmin` external
#### [](#Instance-getInstanceStore--)
`getInstanceStore() → contract InstanceStore` external
#### [](#Instance-getProductStore--)
`getProductStore() → contract ProductStore` external
#### [](#Instance-isTokenRegistryDisabled--)
`isTokenRegistryDisabled() → bool` external
### [](#IInstance)
`IInstance`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/IInstance.sol)
import "@etherisc/gif-next/contracts/instance/IInstance.sol";
Functions
* \[`setInstanceLocked(locked)`\]
* \[`upgradeInstanceReader()`\]
* \[`setInstanceReader(instanceReader)`\]
* \[`setStakingLockingPeriod(stakeLockingPeriod)`\]
* \[`setStakingRewardRate(rewardRate)`\]
* \[`setStakingMaxAmount(maxStakedAmount)`\]
* \[`refillStakingRewardReserves(dipAmount)`\]
* \[`withdrawStakingRewardReserves(dipAmount)`\]
* \[`setTargetLocked(target, locked)`\]
* \[`registerProduct(product, token)`\]
* \[`createRole(roleName, adminRoleId, maxMemberCount)`\]
* \[`setRoleActive(roleId, active)`\]
* \[`grantRole(roleId, account)`\]
* \[`revokeRole(roleId, account)`\]
* \[`createTarget(target, name)`\]
* \[`authorizeFunctions(target, roleId, functions)`\]
* \[`unauthorizeFunctions(target, functions)`\]
* \[`isInstanceLocked()`\]
* \[`isTargetLocked(target)`\]
* \[`products()`\]
* \[`getProduct(idx)`\]
* \[`getInstanceReader()`\]
* \[`getBundleSet()`\]
* \[`getRiskSet()`\]
* \[`getRequestSet()`\]
* \[`getInstanceAdmin()`\]
* \[`getInstanceStore()`\]
* \[`getProductStore()`\]
* \[`isTokenRegistryDisabled()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogInstanceCustomRoleCreated(roleId, roleName, adminRoleId, maxMemberCount)`\]
* \[`LogInstanceCustomRoleActiveSet(roleId, active, caller)`\]
* \[`LogInstanceCustomRoleGranted(roleId, account, caller)`\]
* \[`LogInstanceCustomRoleRevoked(roleId, account, caller)`\]
* \[`LogInstanceCustomTargetCreated(target, targetRoleId, name)`\]
* \[`LogInstanceTargetLocked(target, locked)`\]
* \[`LogInstanceCustomTargetFunctionRoleSet(target, selectors, roleId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IInstance-setInstanceLocked-bool-)
`setInstanceLocked(bool locked)` external
Locks/unlocks the complete instance, including all its components.
#### [](#IInstance-upgradeInstanceReader--)
`upgradeInstanceReader()` external
Upgrades the instance reader to the specified target.
#### [](#IInstance-setInstanceReader-contract-InstanceReader-)
`setInstanceReader(contract InstanceReader instanceReader)` external
Sets the instance reader for the instance. Permissioned: only the instance service may call this function.
#### [](#IInstance-setStakingLockingPeriod-Seconds-)
`setStakingLockingPeriod(Seconds stakeLockingPeriod)` external
Sets the duration for locking new stakes on this instance..
#### [](#IInstance-setStakingRewardRate-UFixed-)
`setStakingRewardRate(UFixed rewardRate)` external
Sets the staking reward rate \[apr\] for this instance.
#### [](#IInstance-setStakingMaxAmount-Amount-)
`setStakingMaxAmount(Amount maxStakedAmount)` external
Sets the maximum staked amount for this instance.
#### [](#IInstance-refillStakingRewardReserves-Amount-)
`refillStakingRewardReserves(Amount dipAmount) → Amount newBalance` external
Refills the staking reward reserves for the specified target.
#### [](#IInstance-withdrawStakingRewardReserves-Amount-)
`withdrawStakingRewardReserves(Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target.
#### [](#IInstance-setTargetLocked-address-bool-)
`setTargetLocked(address target, bool locked)` external
Locks/unlocks the specified target.
#### [](#IInstance-registerProduct-address-address-)
`registerProduct(address product, address token) → NftId productNftId` external
Register a product with the instance.
#### [](#IInstance-createRole-string-RoleId-uint32-)
`createRole(string roleName, RoleId adminRoleId, uint32 maxMemberCount) → RoleId roleId` external
Creates a new custom role for the calling instance. Custom roles are intended to be used for access control of custom components and its helper contracts. Custom roles are not intended to be used as target roles for custom contracts.
#### [](#IInstance-setRoleActive-RoleId-bool-)
`setRoleActive(RoleId roleId, bool active)` external
Activates/deactivates the specified role. Only instance owner or account with role admin role can call this function.
#### [](#IInstance-grantRole-RoleId-address-)
`grantRole(RoleId roleId, address account)` external
Grants the specified role to the account. Only active roles can be granted. Only instance owner or account with role admin role can call this function.
#### [](#IInstance-revokeRole-RoleId-address-)
`revokeRole(RoleId roleId, address account)` external
Revokes the specified role from the account. Only instance owner or account with role admin role can call this function.
#### [](#IInstance-createTarget-address-string-)
`createTarget(address target, string name) → RoleId contractRoleId` external
Creates a new custom target. Custom targets are intended to be used for access control helper contracts of components. Custom targets are not intended to be used for components.
#### [](#IInstance-authorizeFunctions-address-RoleId-struct-IAccess-FunctionInfo---)
`authorizeFunctions(address target, RoleId roleId, struct IAccess.FunctionInfo[] functions)` external
Authorizes the specified functions for the target and provided role.
#### [](#IInstance-unauthorizeFunctions-address-struct-IAccess-FunctionInfo---)
`unauthorizeFunctions(address target, struct IAccess.FunctionInfo[] functions)` external
Removes any role authorization for the specified functions.
#### [](#IInstance-isInstanceLocked--)
`isInstanceLocked() → bool isLocked` external
returns the overall locking state of the instance (including all components)
#### [](#IInstance-isTargetLocked-address-)
`isTargetLocked(address target) → bool isLocked` external
returns the locking state of the specified target
#### [](#IInstance-products--)
`products() → uint256 productCount` external
#### [](#IInstance-getProduct-uint256-)
`getProduct(uint256 idx) → NftId productNftId` external
#### [](#IInstance-getInstanceReader--)
`getInstanceReader() → contract InstanceReader` external
#### [](#IInstance-getBundleSet--)
`getBundleSet() → contract BundleSet` external
#### [](#IInstance-getRiskSet--)
`getRiskSet() → contract RiskSet` external
#### [](#IInstance-getRequestSet--)
`getRequestSet() → contract RequestSet` external
#### [](#IInstance-getInstanceAdmin--)
`getInstanceAdmin() → contract InstanceAdmin` external
#### [](#IInstance-getInstanceStore--)
`getInstanceStore() → contract InstanceStore` external
#### [](#IInstance-getProductStore--)
`getProductStore() → contract ProductStore` external
#### [](#IInstance-isTokenRegistryDisabled--)
`isTokenRegistryDisabled() → bool` external
#### [](#IInstance-LogInstanceCustomRoleCreated-RoleId-string-RoleId-uint32-)
`LogInstanceCustomRoleCreated(RoleId indexed roleId, string indexed roleName, RoleId indexed adminRoleId, uint32 maxMemberCount)` event
#### [](#IInstance-LogInstanceCustomRoleActiveSet-RoleId-bool-address-)
`LogInstanceCustomRoleActiveSet(RoleId indexed roleId, bool indexed active, address indexed caller)` event
#### [](#IInstance-LogInstanceCustomRoleGranted-RoleId-address-address-)
`LogInstanceCustomRoleGranted(RoleId indexed roleId, address indexed account, address indexed caller)` event
#### [](#IInstance-LogInstanceCustomRoleRevoked-RoleId-address-address-)
`LogInstanceCustomRoleRevoked(RoleId indexed roleId, address indexed account, address indexed caller)` event
#### [](#IInstance-LogInstanceCustomTargetCreated-address-RoleId-string-)
`LogInstanceCustomTargetCreated(address indexed target, RoleId indexed targetRoleId, string indexed name)` event
#### [](#IInstance-LogInstanceTargetLocked-address-bool-)
`LogInstanceTargetLocked(address indexed target, bool indexed locked)` event
#### [](#IInstance-LogInstanceCustomTargetFunctionRoleSet-address-bytes4---RoleId-)
`LogInstanceCustomTargetFunctionRoleSet(address indexed target, bytes4[] selectors, RoleId indexed roleId)` event
### [](#InstanceServiceManager)
`InstanceServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/InstanceServiceManager.sol)
import "@etherisc/gif-next/contracts/instance/InstanceServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getInstanceService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#InstanceServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with instance service implementation
#### [](#InstanceServiceManager-getInstanceService--)
`getInstanceService() → contract InstanceService instanceService` external
### [](#InstanceStore)
`InstanceStore`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/InstanceStore.sol)
import "@etherisc/gif-next/contracts/instance/InstanceStore.sol";
Functions
* \[`initialize()`\]
* \[`createComponent(componentNftId, componentInfo)`\]
* \[`updateComponent(componentNftId, componentInfo, newState)`\]
* \[`getComponentInfo(componentNftId)`\]
* \[`createPool(poolNftId, info)`\]
* \[`updatePool(poolNftId, info, newState)`\]
* \[`getPoolInfo(poolNftId)`\]
* \[`createDistributorType(distributorType, info)`\]
* \[`updateDistributorType(distributorType, info, newState)`\]
* \[`updateDistributorTypeState(distributorType, newState)`\]
* \[`getDistributorTypeInfo(distributorType)`\]
* \[`createDistributor(distributorNftId, info)`\]
* \[`updateDistributor(distributorNftId, info, newState)`\]
* \[`updateDistributorState(distributorNftId, newState)`\]
* \[`getDistributorInfo(distributorNftId)`\]
* \[`createReferral(referralId, referralInfo)`\]
* \[`updateReferral(referralId, referralInfo, newState)`\]
* \[`updateReferralState(referralId, newState)`\]
* \[`getReferralInfo(referralId)`\]
* \[`createBundle(bundleNftId, bundle)`\]
* \[`updateBundle(bundleNftId, bundle, newState)`\]
* \[`updateBundleState(bundleNftId, newState)`\]
* \[`getBundleInfo(bundleNftId)`\]
* \[`createRequest(request)`\]
* \[`updateRequest(requestId, request, newState)`\]
* \[`updateRequestState(requestId, newState)`\]
* \[`getRequestInfo(requestId)`\]
* \[`increaseBalance(targetNftId, amount)`\]
* \[`decreaseBalance(targetNftId, amount)`\]
* \[`increaseFees(targetNftId, amount)`\]
* \[`decreaseFees(targetNftId, amount)`\]
* \[`increaseLocked(targetNftId, amount)`\]
* \[`decreaseLocked(targetNftId, amount)`\]
BaseStore
* \[`_createMetadata(key32)`\]
* \[`_updateState(key32, state)`\]
* \[`exists(key32)`\]
* \[`getMetadata(key32)`\]
* \[`getState(key32)`\]
* \[`toKey32(objectType, id)`\]
ObjectLifecycle
* \[`_initializeLifecycle()`\]
* \[`_setupLifecycle()`\]
ObjectCounter
* \[`_createNextRequestId()`\]
BalanceStore
* \[`getBalanceAmount(targetNftId)`\]
* \[`getLockedAmount(targetNftId)`\]
* \[`getFeeAmount(targetNftId)`\]
* \[`getAmounts(targetNftId)`\]
* \[`_registerBalanceTarget(targetNftId)`\]
* \[`_increaseFees(targetNftId, amount)`\]
* \[`_decreaseFees(targetNftId, amount)`\]
* \[`_increaseLocked(targetNftId, amount)`\]
* \[`_decreaseLocked(targetNftId, amount)`\]
* \[`_increaseBalance(targetNftId, amount)`\]
* \[`_decreaseBalance(targetNftId, amount)`\]
* \[`_setLastUpdatedIn(targetNftId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Lifecycle
* \[`setInitialState(ttype, state)`\]
* \[`setStateTransition(ttype, oldState, newState)`\]
* \[`hasLifecycle(objectType)`\]
* \[`getInitialState(objectType)`\]
* \[`checkTransition(stateId, objectType, expectedFromId, toId)`\]
* \[`isValidTransition(objectType, fromId, toId)`\]
Events
* \[`LogProductStoreComponentInfoCreated(componentNftId, state, createdby, txOrigin)`\]
* \[`LogProductStoreComponentInfoUpdated(componentNftId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStorePoolInfoCreated(poolNftId, state, createdBy, txOrigin)`\]
* \[`LogProductStorePoolInfoUpdated(poolNftId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStoreDistributorTypeInfoCreated(distributorType, state, createdBy, txOrigin)`\]
* \[`LogProductStoreDistributorTypeInfoUpdated(distributorType, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStoreDistributorInfoCreated(distributorNftId, state, createdBy, txOrigin)`\]
* \[`LogProductStoreDistributorInfoUpdated(distributorNftId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStoreReferralInfoCreated(referralId, state, createdBy, txOrigin)`\]
* \[`LogProductStoreReferralInfoUpdated(referralId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStoreBundleInfoCreated(bundleNftId, state, createdBy, txOrigin)`\]
* \[`LogProductStoreBundleInfoUpdated(bundleNftId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
* \[`LogProductStoreRequestInfoCreated(requestId, state, createdBy, txOrigin)`\]
* \[`LogProductStoreRequestInfoUpdated(requestId, oldState, newState, updatedBy, txOrigin, lastUpdatedIn)`\]
IBaseStore
* \[`LogBaseStoreMetadataCreated(key, objectType, state)`\]
* \[`LogBaseStoreMetadataUpdated(key, oldState, newState)`\]
BalanceStore
* \[`LogBalanceStoreTargetRegistered(targetNftId)`\]
* \[`LogBalanceStoreFeesIncreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
* \[`LogBalanceStoreFeesDecreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
* \[`LogBalanceStoreLockedIncreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
* \[`LogBalanceStoreLockedDecreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
* \[`LogBalanceStoreBalanceIncreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
* \[`LogBalanceStoreBalanceDecreased(targetNftId, addedAmount, newBalance, lastUpdatedIn)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#InstanceStore-initialize--)
`initialize()` public
This initializer needs to be called from the instance itself.
#### [](#InstanceStore-createComponent-NftId-struct-IComponents-ComponentInfo-)
`createComponent(NftId componentNftId, struct IComponents.ComponentInfo componentInfo)` external
#### [](#InstanceStore-updateComponent-NftId-struct-IComponents-ComponentInfo-StateId-)
`updateComponent(NftId componentNftId, struct IComponents.ComponentInfo componentInfo, StateId newState)` external
#### [](#InstanceStore-getComponentInfo-NftId-)
`getComponentInfo(NftId componentNftId) → struct IComponents.ComponentInfo componentInfo` external
#### [](#InstanceStore-createPool-NftId-struct-IComponents-PoolInfo-)
`createPool(NftId poolNftId, struct IComponents.PoolInfo info)` external
#### [](#InstanceStore-updatePool-NftId-struct-IComponents-PoolInfo-StateId-)
`updatePool(NftId poolNftId, struct IComponents.PoolInfo info, StateId newState)` external
#### [](#InstanceStore-getPoolInfo-NftId-)
`getPoolInfo(NftId poolNftId) → struct IComponents.PoolInfo info` external
#### [](#InstanceStore-createDistributorType-DistributorType-struct-IDistribution-DistributorTypeInfo-)
`createDistributorType(DistributorType distributorType, struct IDistribution.DistributorTypeInfo info)` external
#### [](#InstanceStore-updateDistributorType-DistributorType-struct-IDistribution-DistributorTypeInfo-StateId-)
`updateDistributorType(DistributorType distributorType, struct IDistribution.DistributorTypeInfo info, StateId newState)` external
#### [](#InstanceStore-updateDistributorTypeState-DistributorType-StateId-)
`updateDistributorTypeState(DistributorType distributorType, StateId newState)` external
#### [](#InstanceStore-getDistributorTypeInfo-DistributorType-)
`getDistributorTypeInfo(DistributorType distributorType) → struct IDistribution.DistributorTypeInfo info` external
#### [](#InstanceStore-createDistributor-NftId-struct-IDistribution-DistributorInfo-)
`createDistributor(NftId distributorNftId, struct IDistribution.DistributorInfo info)` external
#### [](#InstanceStore-updateDistributor-NftId-struct-IDistribution-DistributorInfo-StateId-)
`updateDistributor(NftId distributorNftId, struct IDistribution.DistributorInfo info, StateId newState)` external
#### [](#InstanceStore-updateDistributorState-NftId-StateId-)
`updateDistributorState(NftId distributorNftId, StateId newState)` external
#### [](#InstanceStore-getDistributorInfo-NftId-)
`getDistributorInfo(NftId distributorNftId) → struct IDistribution.DistributorInfo info` external
#### [](#InstanceStore-createReferral-ReferralId-struct-IDistribution-ReferralInfo-)
`createReferral(ReferralId referralId, struct IDistribution.ReferralInfo referralInfo)` external
#### [](#InstanceStore-updateReferral-ReferralId-struct-IDistribution-ReferralInfo-StateId-)
`updateReferral(ReferralId referralId, struct IDistribution.ReferralInfo referralInfo, StateId newState)` external
#### [](#InstanceStore-updateReferralState-ReferralId-StateId-)
`updateReferralState(ReferralId referralId, StateId newState)` external
#### [](#InstanceStore-getReferralInfo-ReferralId-)
`getReferralInfo(ReferralId referralId) → struct IDistribution.ReferralInfo referralInfo` external
#### [](#InstanceStore-createBundle-NftId-struct-IBundle-BundleInfo-)
`createBundle(NftId bundleNftId, struct IBundle.BundleInfo bundle)` external
#### [](#InstanceStore-updateBundle-NftId-struct-IBundle-BundleInfo-StateId-)
`updateBundle(NftId bundleNftId, struct IBundle.BundleInfo bundle, StateId newState)` external
#### [](#InstanceStore-updateBundleState-NftId-StateId-)
`updateBundleState(NftId bundleNftId, StateId newState)` external
#### [](#InstanceStore-getBundleInfo-NftId-)
`getBundleInfo(NftId bundleNftId) → struct IBundle.BundleInfo bundle` external
#### [](#InstanceStore-createRequest-struct-IOracle-RequestInfo-)
`createRequest(struct IOracle.RequestInfo request) → RequestId requestId` external
#### [](#InstanceStore-updateRequest-RequestId-struct-IOracle-RequestInfo-StateId-)
`updateRequest(RequestId requestId, struct IOracle.RequestInfo request, StateId newState)` external
#### [](#InstanceStore-updateRequestState-RequestId-StateId-)
`updateRequestState(RequestId requestId, StateId newState)` external
#### [](#InstanceStore-getRequestInfo-RequestId-)
`getRequestInfo(RequestId requestId) → struct IOracle.RequestInfo request` external
#### [](#InstanceStore-increaseBalance-NftId-Amount-)
`increaseBalance(NftId targetNftId, Amount amount) → Amount newBalance` external
#### [](#InstanceStore-decreaseBalance-NftId-Amount-)
`decreaseBalance(NftId targetNftId, Amount amount) → Amount newBalance` external
#### [](#InstanceStore-increaseFees-NftId-Amount-)
`increaseFees(NftId targetNftId, Amount amount) → Amount newFeeBalance` external
#### [](#InstanceStore-decreaseFees-NftId-Amount-)
`decreaseFees(NftId targetNftId, Amount amount) → Amount newFeeBalance` external
#### [](#InstanceStore-increaseLocked-NftId-Amount-)
`increaseLocked(NftId targetNftId, Amount amount) → Amount newBalance` external
#### [](#InstanceStore-decreaseLocked-NftId-Amount-)
`decreaseLocked(NftId targetNftId, Amount amount) → Amount newBalance` external
#### [](#InstanceStore-LogProductStoreComponentInfoCreated-NftId-StateId-address-address-)
`LogProductStoreComponentInfoCreated(NftId indexed componentNftId, StateId indexed state, address indexed createdby, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreComponentInfoUpdated-NftId-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreComponentInfoUpdated(NftId indexed componentNftId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStorePoolInfoCreated-NftId-StateId-address-address-)
`LogProductStorePoolInfoCreated(NftId indexed poolNftId, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStorePoolInfoUpdated-NftId-StateId-StateId-address-address-Blocknumber-)
`LogProductStorePoolInfoUpdated(NftId indexed poolNftId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStoreDistributorTypeInfoCreated-DistributorType-StateId-address-address-)
`LogProductStoreDistributorTypeInfoCreated(DistributorType indexed distributorType, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreDistributorTypeInfoUpdated-DistributorType-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreDistributorTypeInfoUpdated(DistributorType indexed distributorType, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStoreDistributorInfoCreated-NftId-StateId-address-address-)
`LogProductStoreDistributorInfoCreated(NftId indexed distributorNftId, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreDistributorInfoUpdated-NftId-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreDistributorInfoUpdated(NftId indexed distributorNftId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStoreReferralInfoCreated-ReferralId-StateId-address-address-)
`LogProductStoreReferralInfoCreated(ReferralId indexed referralId, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreReferralInfoUpdated-ReferralId-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreReferralInfoUpdated(ReferralId indexed referralId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStoreBundleInfoCreated-NftId-StateId-address-address-)
`LogProductStoreBundleInfoCreated(NftId indexed bundleNftId, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreBundleInfoUpdated-NftId-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreBundleInfoUpdated(NftId indexed bundleNftId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
#### [](#InstanceStore-LogProductStoreRequestInfoCreated-RequestId-StateId-address-address-)
`LogProductStoreRequestInfoCreated(RequestId indexed requestId, StateId indexed state, address indexed createdBy, address txOrigin)` event
#### [](#InstanceStore-LogProductStoreRequestInfoUpdated-RequestId-StateId-StateId-address-address-Blocknumber-)
`LogProductStoreRequestInfoUpdated(RequestId indexed requestId, StateId indexed oldState, StateId indexed newState, address updatedBy, address txOrigin, Blocknumber lastUpdatedIn)` event
[← distribution](/gif-next/3.x/api/distribution)
[instance/base →](/gif-next/3.x/api/instance/base)
---
# Module - Etherisc Docs
Module
======
Contains the instance module contracts.
[](#contracts)
Contracts
------------------------
### [](#IBundle)
`IBundle`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/module/IBundle.sol)
import "@etherisc/gif-next/contracts/instance/module/IBundle.sol";
### [](#IComponents)
`IComponents`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/module/IComponents.sol)
import "@etherisc/gif-next/contracts/instance/module/IComponents.sol";
### [](#IDistribution)
`IDistribution`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/module/IDistribution.sol)
import "@etherisc/gif-next/contracts/instance/module/IDistribution.sol";
### [](#IPolicy)
`IPolicy`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/module/IPolicy.sol)
import "@etherisc/gif-next/contracts/instance/module/IPolicy.sol";
### [](#IRisk)
`IRisk`[](https://github.com/etherisc/gif-next/blob/develop/contracts/instance/module/IRisk.sol)
import "@etherisc/gif-next/contracts/instance/module/IRisk.sol";
[← instance/base](/gif-next/3.x/api/instance/base)
[instance/service →](#instance/service.adoc)
---
# Setup of the development environment - Etherisc Docs
Setup of the development environment
====================================
[](#prerequisites)
Prerequisites
--------------------------------
1. A running Docker instance (or other compatible container engine)
2. Visual Studio Code (VS Code) with the [Remote Development Extension Pack](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack)
installed
3. Know how to work with [devcontainers](https://code.visualstudio.com/docs/devcontainers/containers)
(optional)
Installing Docker on Windows is sometimes a struggle. Recommended Approach: Follow the installation instructions for [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
. Installing Docker on [Linux](https://docs.docker.com/desktop/install/linux-install/)
or [Mac](https://docs.docker.com/desktop/install/mac-install/)
should be straight forward.
[](#get_the_source_code_and_editor_ready)
Get the source code and editor ready
------------------------------------------------------------------------------
1. Fork the [gif-sandbox repository](https://github.com/etherisc/gif-sandbox)
to your own github account (if you want to be able to commit changes)
2. Clone the repository to your local machine
3. Open the repository in VS Code
There are three ways to work with the sandbox (described below)
* Use the devcontainer provided in the repository
* Use Github Codespaces
* Run the brownie container outside of vscode devcontainer
### [](#start_the_sandbox_devcontainer)
Start the sandbox devcontainer
* Start the devcontainer (either wait for the pop to build the devcontainer or open the command list (F1) and select the command _Dev Containers: Rebuild and reopen in container_)
* Wait for the devcontainer to finish compiling and deploying the contracts
* The devcontainer setup includes a second container with a ganache instance that is started automatically. A GIF instance is deployed to this ganache instance and the address of the GIF instance is stored in the file `gif_instance_address.txt` in the project root. This GIF instance can also be used by other (newly developed) products/riskpools/oracles for testing purposes.
### [](#use_github_codespaces)
Use Github Codespaces
Github Codespaces is a new feature of Github that allows you to work with a repository in a container environment hosted by Github. To use Github Codespaces you need to have a Github account and you need to be logged in to Github. Open the [gif-sandbox repository](https://github.com/etherisc/gif-sandbox)
in your browser and click on the button `Code` and select `Open with Codespaces` from the dropdown menu. This will open a new browser tab with the sandbox repository in a devcontainer hosted by Github. You can now work with the sandbox repository in the browser (or open the codespace in VS Code by clicking on the button `Open with VS Code` in the upper right corner of the browser tab).
To improve performance of the codespace you can change the machine type in the codespace settings.
### [](#run_brownie_container_outside_of_vscode_devcontainer)
Run brownie container outside of vscode devcontainer
Build the brownie container
docker build -t gif-sandbox-brownie -f Dockerfile.brownie-container .
Run the brownie container
docker run -v .:/sandbox -p 7545:7545 -p 8000:8000 --name gif-sandbox-brownie gif-sandbox-brownie
Open another terminal (the above command will block you current terminal) and start an interactive shell in the brownie container to execute commands
docker exec -it gif-sandbox-brownie bash
After that you need to add the ganache network to the brownie config once and create an empty .env file
brownie networks add Local ganache host=http://localhost:7545 chainid=1337
touch .env
When you are done with the brownie container you can exit the interactive shell (type `exit`) and stop the container
docker stop gif-sandbox-brownie
# to remove the container run
docker rm gif-sandbox-brownie
[](#reset_devcontainer)
Reset devcontainer
------------------------------------------
To completely reset a devcontainer instance follow these steps
1. Shutdown and remove the devcontainer and associated containers
2. Remove the `ganache-db` volume from the devcontainers ganache instance
3. Delete the file `gif_instance_address.txt` from the project sources
4. Restart the devcontainer as described above in the section `Start devcontainer`
[← Overview](/sandbox/)
[Compile, deploy and interact →](/sandbox/fire_insurance_interaction)
---
# Fire insurance example - Etherisc Docs
Fire insurance example
======================
[](#overview)
Overview
----------------------
The fire components is a minimal fully functional and permissioned example for a insurance product built on the GIF. It consists of the following components:
* FirePoolAuthorization: A contract that authorizes the functions on the pool
* FirePool: A pool that holds the funds for the insurance product
* FireProductAuthorization: A contract that authorizes the functions on the product
* FireProduct: The insurance product that is used to insure against fires
* (optional) FireUSD: A ERC20 token that is used as the currency for the insurance product
The product is build in such a way that a customer can buy a policy which insures against fires in a specific city. The product owner can report fires in the city (the report also contains the damage level and the time of the fire). Once a fire has been reported in a city, the customer can submit a claim for the policy and receive an immediate payout (if the policy is eligable for a payout). The payout amount is calculated from the damage level and the sum insured.
The payout is 25% for small fires, 50% for medium fires and 100% for large fires. If the payout exceeds the sum insured, only the remaining sum insured is paid out. If the payout amount is the same as the sum insured after the payout, the policy is automatically expired.
[](#deployment)
Deployment
--------------------------
### [](#with_remix)
With Remix
1. Checkout repository `` gif-next` `` ([https://github.com/etherisc/gif-next.git](https://github.com/etherisc/gif-next.git)
) in Remix IDE.
2. Call 'Update submodules' (Link at the bottom left of the page).
3. Open the `InstanceService` contract in directory `contracts/instance/InstanceService.sol` and compile it.
4. Switch to the `Deploy & Run Transactions` tab and connect to the network of choice (must have a GIF deployment).
5. Connect to the existing `InstanceService` contract.
6. Decide if you want to use a registered token or use an unregistered one (the latter allows for more flexibility during testing but will create an unsupported instance).
7. Call the `createInstance` function (set the `allowAnyToken` parameter according to above decision) and find the log `LogInstanceServiceInstanceCreated` that shows the address of the new instance in field `instance` and the instance nft id in field `instanceNftId`.
8. Now compile the contracts `FireUSD.sol`, `FirePoolAuthorization`, `FirePool`, `FireProductAuthorization` and `FireProduct` in the directory `contracts/examples/fire`.
9. Deploy the FireUSD contract and save the address. You can also use any pre-existing ERC20 Token. If you deploy a new token and have not enabled the `allowAnyToken` flag on the instance, then please ensure that the new token is registered with the token registry as well.
10. Deploy the FirePoolAuthorization contract with an arbitrary unique name and save the address.
11. Deploy the FireProductAuthorization contract with an arbitrary unique name and save the address.
12. Deploy the FireProduct contract and save the address. The product requires the registry address, the instance nft id, the name of the component (same as used in step 11) and the address of the product authorization contract as arguments.
13. Call `registerProduct` on the `Instance` contract and provide the address of the product contract as well as the token address as argument.
14. Get the nft id of the product by calling `getNftId` function on the `FireProduct` contract.
15. Deploy the FirePool contract and save the address. The pool requires the registry address, the product nft id, the name of the component (same as used in step 10) , the address of the token as well as the address of the pool authorization contract as arguments.
16. Call `registerComponent` on the `FireProduct` contract and provide the address of the pool as argument.
17. Get the nft if of the pool by calling `getNftId` function on the `FirePool` contract.
18. Congratulations, the fire product is now deployed and ready to use.
### [](#using_the_hardhat_script)
Using the hardhat script
Run the script `scripts/deploy_fire_components.ts` on an instance that has a gif deployment. The script will deploy the FireUSD, FirePoolAuthorization, FirePool, FireProductAuthorization and FireProduct contracts and register the pool and product in the instance.
It requires the following environment variables to be set:
AMOUNTLIB_ADDRESS
CONTRACTLIB_ADDRESS
FEELIB_ADDRESS
NFTIDLIB_ADDRESS
OBJECTTYPELIB_ADDRESS
REFERRALLIB_ADDRESS
RISKIDLIB_ADDRESS
ROLEIDLIB_ADDRESS
SECONDSLIB_ADDRESS
SELECTORLIB_ADDRESS
STRLIB_ADDRESS
TIMESTAMPLIB_ADDRESS
UFIXEDLIB_ADDRESS
VERSIONPARTLIB_ADDRESS
INSTANCE_SERVICE_ADDRESS
[](#usage)
Usage
----------------
### [](#bundle_creation)
Bundle creation
1. The investor must call `createBundle` on the `FirePool` contract with the `fee`, the `initialAmount` of the bundle and the `lifetime` of the bundle as arguments.
2. The response contains the `bundleNftId` which is required when purchasing policies.
### [](#registration_of_cities)
Registration of cities
1. Registration of new cities is done via call to the method `initializeCity` on the `FireProduct` contract. Anybody can call this function.
### [](#reporting_of_fires)
Reporting of fires
1. To report a fire make sure the city is registered first.
2. Then the `ProductOwner` must call `reportFire` with a unique `fireId` as well as the `cityName`,the damage level (Small - 25% payout, Medium - 50% payout, Large - 100% payout) and the time the fire occured.
### [](#policy_purchase)
Policy purchase
1. Make sure the city is registered beforehand
2. As customer, call `calculatePremium` on `FireProduct` with arguments `cityName`, `sumInsured`, `lifetime` and `bundleNftId` to get the premium amount for this parameter combination.
3. As customer, call `createApplication` with the `cityName`, `sumInsured`, `lifetime` and `bundleNftId` to create a new application. The response contains the `policyNftId` that is needed for the next step.
4. Once the application is created, the `ProductOwner` must confirm the application by calling `createPolicy` with the `policyNftId` and time the policy is active (`activateAt`) as arguments.
### [](#claim_payout)
Claim & Payout
1. After a fire was reported, the customer can now submit a claim and received a payout for this fire by calling `submitClaim` with the `policyNftId` and the `fireId` as arguments. The payout is calculated based on the damage level reported and the sum insured.
2. The payout amount is immediately transferred to the customer.
3. If the payout amount exceeds the sum insured, only the remaining sum insured is paid out.
4. If the payout amount is the same as the sum insured after the payout, the policy is automatically expired.
[← Development setup](/gif-next/3.x/setup)
[accounting →](/gif-next/3.x/api/accounting)
---
# How to write documentation - Etherisc Docs
How to write documentation
==========================
[](#introduction)
Introduction
------------------------------
Documentation for our framework and smart contracts is written in AsciiDoc. This format is easy to read and write, and it can be converted to HTML, PDF, and other formats. Language documentation can be found at [https://docs.asciidoctor.org/asciidoc/latest/](https://docs.asciidoctor.org/asciidoc/latest/)
A nice cheat sheet for AsciiDoc can be found at [https://drive.google.com/file/d/1Y7VaiafvidX5CaX90gJz7t6HZqE-dJWq/view](https://drive.google.com/file/d/1Y7VaiafvidX5CaX90gJz7t6HZqE-dJWq/view)
Smart contacts written in Solidity are documented using NatSpec. Natspec is similar to JavaDoc and is used to generate documentation for the smart contracts direcly in the code. The Natspec docs may use AsciiDoc syntax for formatting. For more details continue reading at [https://docs.soliditylang.org/en/latest/natspec-format.html](https://docs.soliditylang.org/en/latest/natspec-format.html)
Natspec documentation is automatically generated during each build and stored in a separate branch that is prefixed with `docs/`. Documentation from the `develop` branch is automatically published to documentation site at [https://docs.etherisc.com/gif-next/3.x/](https://docs.etherisc.com/gif-next/3.x/)
after each push to the branch.
The vscode plugin `AsciiDoc` is included in the devcontainer to make it easier to write documentation.
[](#rules)
Rules
----------------
* Put manually written documentation in the `docs/modules/ROOT/pages` directory and use the `adoc` file extension.
* Use Natspec syntax to document solidity smart contracts.
* Document in the interface contract if it exists.
* Do not document the obvious … instead explain what the code does, how it does this and how it can be used.
* Integrating a small code example goes a long way. This is often be easier to understand than a long explanation.
* Document at least public/external functions.
* Update the documentation in the same PR as the code changes.
* Delete dead documentation.
* Use graphics and diagrams to explain complex concepts.
* When using external tools (e.g. mermaid or draw.io) to create diagrams, store the source of the diagram in the same folder as the image. This is imporant to be able to modify the diagram in the future.
* If possible use SVG images instead of PNG or JPG.
* The consumers of this documentation are developers, auditors, and other technical people working with the framework and not the consumers. Write the documentation accordingly.
[](#technical_rules)
Technical rules
------------------------------------
### [](#structure)
Structure
Each folder that contains contracts must contain a `README.adoc` file. This file should contain a brief description of the contracts in the folder and a list of the contracts for which documentation should be generated. Unless this file exists, no netspec is generated for a folder.
Example:
= Components
Contains the components contracts.
== Contracts
{{Component}}
{{Distribution}}
{{IComponent}}
{{IDistributionComponent}}
{{IPoolComponent}}
{{IProductComponent}}
{{Pool}}
{{Product}}
[](#generating_natspec_docs_locally)
Generating natspec docs locally
--------------------------------------------------------------------
To generate natspec documentation locally, you can use the command `hh docgen`. This will generate the documentation in the `docs/modules/api/pages/` directory. Do not commit those files to the repository, as they are automatically generated during the build process.
[← Architecture](/gif-next/3.x/arch)
[Development setup →](/gif-next/3.x/setup)
---
# Oracle - Etherisc Docs
Oracle
======
Contains interfaces and contracts related to oracles.
[](#contracts)
Contracts
------------------------
### [](#IOracleComponent)
`IOracleComponent`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/IOracleComponent.sol)
import "@etherisc/gif-next/contracts/oracle/IOracleComponent.sol";
Functions
* \[`request(requestId, requesterNftId, requestData, expiryAt)`\]
* \[`cancel(requestId)`\]
* \[`isVerifying()`\]
* \[`activeRequests()`\]
* \[`getActiveRequest(idx)`\]
* \[`isActiveRequest(requestId)`\]
IInstanceLinkedComponent
* \[`withdrawFees(amount)`\]
* \[`getInstance()`\]
IAuthorizedComponent
* \[`getAuthorization()`\]
IComponent
* \[`getName()`\]
* \[`getToken()`\]
* \[`getTokenHandler()`\]
* \[`getWallet()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
ITransferInterceptor
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogOracleRequestReceived(requestId, requesterId)`\]
* \[`LogOracleRequestCancelled(requestId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IOracleComponent-request-RequestId-NftId-bytes-Timestamp-)
`request(RequestId requestId, NftId requesterNftId, bytes requestData, Timestamp expiryAt)` external
callback method for requesting some data from the oracle
#### [](#IOracleComponent-cancel-RequestId-)
`cancel(RequestId requestId)` external
callback method for cancelling the specified oracle request
#### [](#IOracleComponent-isVerifying--)
`isVerifying() → bool verifying` external
returns true iff the component needs to be called when selling/renewing policis
#### [](#IOracleComponent-activeRequests--)
`activeRequests() → uint256 numberOfRequests` external
#### [](#IOracleComponent-getActiveRequest-uint256-)
`getActiveRequest(uint256 idx) → RequestId requestId` external
#### [](#IOracleComponent-isActiveRequest-RequestId-)
`isActiveRequest(RequestId requestId) → bool isActive` external
#### [](#IOracleComponent-LogOracleRequestReceived-RequestId-NftId-)
`LogOracleRequestReceived(RequestId indexed requestId, NftId indexed requesterId)` event
#### [](#IOracleComponent-LogOracleRequestCancelled-RequestId-)
`LogOracleRequestCancelled(RequestId indexed requestId)` event
### [](#Oracle)
`Oracle`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/Oracle.sol)
import "@etherisc/gif-next/contracts/oracle/Oracle.sol";
Functions
* \[`request(requestId, requesterId, requestData, expiryAt)`\]
* \[`cancel(requestId)`\]
* \[`isVerifying()`\]
* \[`withdrawFees()`\]
* \[`activeRequests()`\]
* \[`getActiveRequest(idx)`\]
* \[`isActiveRequest(requestId)`\]
* \[`__Oracle_init(registry, productNftId, authorization, initialOwner, name)`\]
* \[`_respond(requestId, responseData)`\]
* \[`_request(requestId, requesterId, , )`\]
* \[`_cancel(requestId)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IOracleComponent
* \[`LogOracleRequestReceived(requestId, requesterId)`\]
* \[`LogOracleRequestCancelled(requestId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Oracle-request-RequestId-NftId-bytes-Timestamp-)
`request(RequestId requestId, NftId requesterId, bytes requestData, Timestamp expiryAt)` external
#### [](#Oracle-cancel-RequestId-)
`cancel(RequestId requestId)` external
callback method for cancelling the specified oracle request
#### [](#Oracle-isVerifying--)
`isVerifying() → bool verifying` external
Not relevant for oracle components, always returns false.
#### [](#Oracle-withdrawFees-Amount-)
`withdrawFees(Amount) → Amount` external
Not relevant for oracle components
#### [](#Oracle-activeRequests--)
`activeRequests() → uint256 numberOfRequests` external
#### [](#Oracle-getActiveRequest-uint256-)
`getActiveRequest(uint256 idx) → RequestId requestId` external
#### [](#Oracle-isActiveRequest-RequestId-)
`isActiveRequest(RequestId requestId) → bool isActive` external
#### [](#Oracle-__Oracle_init-address-NftId-contract-IAuthorization-address-string-)
`__Oracle_init(address registry, NftId productNftId, contract IAuthorization authorization, address initialOwner, string name)` internal
#### [](#Oracle-_respond-RequestId-bytes-)
`_respond(RequestId requestId, bytes responseData)` internal
Internal function for handling oracle responses. Default implementation sends response back to oracle service. Use this function in use case specific external/public functions to handle use case specific response handling.
#### [](#Oracle-_request-RequestId-NftId-bytes-Timestamp-)
`_request(RequestId requestId, NftId requesterId, bytes, Timestamp)` internal
use case specific handling of oracle requests for now only log is emitted to verify that request has been received by oracle component
#### [](#Oracle-_cancel-RequestId-)
`_cancel(RequestId requestId)` internal
use case specific handling of oracle requests for now only log is emitted to verify that cancelling has been received by oracle component
### [](#BasicOracle)
`BasicOracle`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/BasicOracle.sol)
import "@etherisc/gif-next/contracts/oracle/BasicOracle.sol";
Functions
* \[`respond(requestId, responseData)`\]
* \[`_initializeBasicOracle(registry, instanceNftId, authorization, initialOwner, name)`\]
Oracle
* \[`request(requestId, requesterId, requestData, expiryAt)`\]
* \[`cancel(requestId)`\]
* \[`isVerifying()`\]
* \[`withdrawFees()`\]
* \[`activeRequests()`\]
* \[`getActiveRequest(idx)`\]
* \[`isActiveRequest(requestId)`\]
* \[`__Oracle_init(registry, productNftId, authorization, initialOwner, name)`\]
* \[`_respond(requestId, responseData)`\]
* \[`_request(requestId, requesterId, , )`\]
* \[`_cancel(requestId)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IOracleComponent
* \[`LogOracleRequestReceived(requestId, requesterId)`\]
* \[`LogOracleRequestCancelled(requestId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BasicOracle-respond-RequestId-bytes-)
`respond(RequestId requestId, bytes responseData)` external
#### [](#BasicOracle-_initializeBasicOracle-address-NftId-contract-IAuthorization-address-string-)
`_initializeBasicOracle(address registry, NftId instanceNftId, contract IAuthorization authorization, address initialOwner, string name)` internal
### [](#BasicOracleAuthorization)
`BasicOracleAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/BasicOracleAuthorization.sol)
import "@etherisc/gif-next/contracts/oracle/BasicOracleAuthorization.sol";
Functions
* \[`constructor(componentName, commitHash)`\]
* \[`_setupServiceTargets()`\]
* \[`_setupTargetAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#BasicOracleAuthorization-constructor-string-string-)
`constructor(string componentName, string commitHash)` public
#### [](#BasicOracleAuthorization-_setupServiceTargets--)
`_setupServiceTargets()` internal
Sets up the relevant service targets for the component. Overwrite this function for use case specific authorizations.
#### [](#BasicOracleAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#OracleService)
`OracleService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/OracleService.sol)
import "@etherisc/gif-next/contracts/oracle/OracleService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`request(oracleNftId, requestData, expiryAt, callbackMethodName)`\]
* \[`respond(requestId, responseData)`\]
* \[`resend(requestId)`\]
* \[`cancel(requestId)`\]
* \[`_checkRequestParams(registry, oracleNftId, requesterInfo, expiryAt, callbackMethodName)`\]
* \[`_checkAndGetRequestInfo(instance, requestId, callerNftId, callerIsOracle)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IOracleService
* \[`LogOracleServiceRequestCreated(requestId, requesterNftId, oracleNftId, expiryAt)`\]
* \[`LogOracleServiceResponseProcessed(requestId, requesterNftId, oracleNftId)`\]
* \[`LogOracleServiceDeliveryFailed(requestId, requesterAddress, functionSignature)`\]
* \[`LogOracleServiceResponseResent(requestId, requesterNftId)`\]
* \[`LogOracleServiceRequestCancelled(requestId, requesterNftId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#OracleService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#OracleService-request-NftId-bytes-Timestamp-string-)
`request(NftId oracleNftId, bytes requestData, Timestamp expiryAt, string callbackMethodName) → RequestId requestId` external
send an oracle request to the specified oracle component. the function returns the id of the newly created request. permissioned: only registered components may send requests to oracles.
#### [](#OracleService-respond-RequestId-bytes-)
`respond(RequestId requestId, bytes responseData) → bool success` external
respond to oracle request by oracle compnent. permissioned: only the oracle component linked to the request id may call this method
#### [](#OracleService-resend-RequestId-)
`resend(RequestId requestId)` external
Resend a failed response to the requester. Only requests in state FAILED may be resent. The request state changes to FULFILLED when calling the callback method of the requester is successful. Permissioned: only the receiving oracle may resend a request
#### [](#OracleService-cancel-RequestId-)
`cancel(RequestId requestId)` external
Notify the oracle component that the specified request has become invalid. Only requests in state ACTIVE may be cancelled. Permissioned: only the requester may cancel a request
#### [](#OracleService-_checkRequestParams-contract-IRegistry-NftId-struct-IRegistry-ObjectInfo-Timestamp-string-)
`_checkRequestParams(contract IRegistry registry, NftId oracleNftId, struct IRegistry.ObjectInfo requesterInfo, Timestamp expiryAt, string callbackMethodName) → NftId requesterNftId, contract IOracleComponent oracle` internal
#### [](#OracleService-_checkAndGetRequestInfo-contract-IInstance-RequestId-NftId-bool-)
`_checkAndGetRequestInfo(contract IInstance instance, RequestId requestId, NftId callerNftId, bool callerIsOracle) → struct IOracle.RequestInfo info` internal
#### [](#OracleService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#OracleServiceManager)
`OracleServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/oracle/OracleServiceManager.sol)
import "@etherisc/gif-next/contracts/oracle/OracleServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getOracleService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#OracleServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with service implementation and deploys instance
#### [](#OracleServiceManager-getOracleService--)
`getOracleService() → contract OracleService oracleService` external
[← instance/service](#instance/service.adoc)
[pool →](/gif-next/3.x/api/pool)
---
# Upgradeability - Etherisc Docs
Upgradeability
==============
Contains interfaces/contracts linked to contract upgradeability.
[](#contracts)
Contracts
------------------------
### [](#IVersionable)
`IVersionable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/upgradeability/IVersionable.sol)
import "@etherisc/gif-next/contracts/upgradeability/IVersionable.sol";
Functions
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
#### [](#IVersionable-initializeVersionable-address-bytes-)
`initializeVersionable(address activatedBy, bytes activationData)` external
IMPORTANT implementation MUST be guarded by initializer modifier new version MUST inherit from previous version
#### [](#IVersionable-upgradeVersionable-bytes-)
`upgradeVersionable(bytes upgradeData)` external
#### [](#IVersionable-getVersion--)
`getVersion() → Version` external
returns version of this contract each new implementation MUST implement this function version number MUST increase
### [](#ProxyManager)
`ProxyManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/upgradeability/ProxyManager.sol)
import "@etherisc/gif-next/contracts/upgradeability/ProxyManager.sol";
manages proxy deployments for upgradable contracs of type IVersionable
Functions
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#ProxyManager-initialize-address-address-bytes-bytes32-)
`initialize(address registry, address implementation, bytes data, bytes32 salt) → contract IVersionable versionable` public
convencience initializer
#### [](#ProxyManager-deploy-address-address-bytes-)
`deploy(address registry, address initialImplementation, bytes initializationData) → contract IVersionable versionable` public
deploy initial contract
#### [](#ProxyManager-deployDetermenistic-address-address-bytes-bytes32-)
`deployDetermenistic(address registry, address initialImplementation, bytes initializationData, bytes32 salt) → contract IVersionable versionable` public
#### [](#ProxyManager-upgrade-address-)
`upgrade(address newImplementation) → contract IVersionable versionable` public
upgrade existing contract. convenience method using empty data
#### [](#ProxyManager-upgrade-address-bytes-)
`upgrade(address newImplementation, bytes upgradeData) → contract IVersionable versionable` public
upgrade existing contract
#### [](#ProxyManager-linkToProxy--)
`linkToProxy() → NftId` public
#### [](#ProxyManager-getDeployData-address-bytes-)
`getDeployData(address proxyOwner, bytes deployData) → bytes data` public
#### [](#ProxyManager-getUpgradeData-bytes-)
`getUpgradeData(bytes upgradeData) → bytes data` public
#### [](#ProxyManager-getProxy--)
`getProxy() → contract UpgradableProxyWithAdmin` public
#### [](#ProxyManager-getVersion--)
`getVersion() → Version` external
#### [](#ProxyManager-getVersionCount--)
`getVersionCount() → uint256` external
#### [](#ProxyManager-getVersion-uint256-)
`getVersion(uint256 idx) → Version` external
#### [](#ProxyManager-getVersionInfo-Version-)
`getVersionInfo(Version _version) → struct ProxyManager.VersionInfo` external
#### [](#ProxyManager-LogProxyManagerVersionableDeployed-address-address-)
`LogProxyManagerVersionableDeployed(address indexed proxy, address indexed initialImplementation)` event
#### [](#ProxyManager-LogProxyManagerVersionableUpgraded-address-address-)
`LogProxyManagerVersionableUpgraded(address indexed proxy, address indexed upgradedImplementation)` event
### [](#UpgradableProxyWithAdmin)
`UpgradableProxyWithAdmin`[](https://github.com/etherisc/gif-next/blob/develop/contracts/upgradeability/UpgradableProxyWithAdmin.sol)
import "@etherisc/gif-next/contracts/upgradeability/UpgradableProxyWithAdmin.sol";
Functions
* \[`constructor(implementation, initialProxyAdminOwner, data)`\]
* \[`getProxyAdmin()`\]
* \[`getInitializationData()`\]
TransparentUpgradeableProxy
* \[`_proxyAdmin()`\]
* \[`_fallback()`\]
ERC1967Proxy
* \[`_implementation()`\]
Proxy
* \[`_delegate(implementation)`\]
* \[`fallback()`\]
#### [](#UpgradableProxyWithAdmin-constructor-address-address-bytes-)
`constructor(address implementation, address initialProxyAdminOwner, bytes data)` public
#### [](#UpgradableProxyWithAdmin-getProxyAdmin--)
`getProxyAdmin() → contract ProxyAdmin` external
#### [](#UpgradableProxyWithAdmin-getInitializationData--)
`getInitializationData() → bytes` external
### [](#Versionable)
`Versionable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/upgradeability/Versionable.sol)
import "@etherisc/gif-next/contracts/upgradeability/Versionable.sol";
Functions
* \[`constructor()`\]
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`getVersion()`\]
* \[`_initialize(, )`\]
* \[`_upgrade(data)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#Versionable-constructor--)
`constructor()` internal
#### [](#Versionable-initializeVersionable-address-bytes-)
`initializeVersionable(address activatedBy, bytes data)` public
#### [](#Versionable-upgradeVersionable-bytes-)
`upgradeVersionable(bytes data)` external
#### [](#Versionable-getVersion--)
`getVersion() → Version` public
returns version of this contract each new implementation MUST implement this function version number MUST increase
#### [](#Versionable-_initialize-address-bytes-)
`_initialize(address, bytes)` internal
#### [](#Versionable-_upgrade-bytes-)
`_upgrade(bytes data)` internal
[← type](/gif-next/3.x/api/type)
[examples/fire →](/gif-next/3.x/api/examples/fire)
---
# Setup of the development environment - Etherisc Docs
Setup of the development environment
====================================
[](#prerequisites)
Prerequisites
--------------------------------
1. A running Docker instance (or other compatible container engine)
2. Visual Studio Code (VS Code) with the [Remote Development Extension Pack](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack)
installed
3. Know how to work with [devcontainers](https://code.visualstudio.com/docs/devcontainers/containers)
(optional)
Installing Docker on Windows is sometimes a struggle. Recommended Approach: Follow the installation instructions for [Docker Desktop](https://docs.docker.com/desktop/install/windows-install/)
. Installing Docker on [Linux](https://docs.docker.com/desktop/install/linux-install/)
or [Mac](https://docs.docker.com/desktop/install/mac-install/)
should be straight forward.
[](#get_the_source_code_and_editor_ready)
Get the source code and editor ready
------------------------------------------------------------------------------
1. Clone the [gif-next repository](https://github.com/etherisc/gif-next)
to your local machine
2. Open the repository in VS Code
There are different ways to work with the repository (described below)
* Use the devcontainer provided in the repository
* Use Github Codespaces
### [](#start_the_devcontainer)
Start the devcontainer
* Start the devcontainer (either wait for the pop to build the devcontainer or open the command list (F1) and select the command _Dev Containers: Rebuild and reopen in container_)
* Wait for the devcontainer to finish setup
* The devcontainer setup includes a second container with an anvil instance that is started automatically. This can be used for local development and testing where persistence is not bound by the lifecycle of the deployment process.
### [](#use_github_codespaces)
Use Github Codespaces
Github Codespaces is a new feature of Github that allows you to work with a repository in a container environment hosted by Github. To use Github Codespaces you need to have a Github account and you need to be logged in to Github. Open the [gif-next repository](https://github.com/etherisc/gif-next)
in your browser and click on the button `Code` and select `Open with Codespaces` from the dropdown menu. This will open a new browser tab with the sandbox repository in a devcontainer hosted by Github. You can now work with the sandbox repository in the browser (or open the codespace in VS Code by clicking on the button `Open with VS Code` in the upper right corner of the browser tab).
To improve performance of the codespace you can change the machine type in the codespace settings.
[← Documentation Howto](/gif-next/3.x/howto-documentation)
[Fire insurance example →](/gif-next/3.x/example-fire)
---
# Fire insurance registration - Etherisc Docs
Fire insurance registration
===========================
[](#overview)
Overview
----------------------
In order to work with _GIF instance_ each component of _fire insurance_ needs to undergo registration. Registration procedure consists of component proposal tx (by component _owner_) followed by component approval tx (by _GIF instance operator_) with consequent configurations.
Each component has _owner_ (implements `getOwner()` method) and _type_ (implements `getType()` method). Prior to registration, _GIF instance operator_ grants component _owner_ a role correspondent to component _type_. This role is required to be able to propose a component.
Components registration order is important: starting with `FireOracle`, followed by `FireRiskpool` and finishing with `FireProduct`.
[](#registration_diagrams)
Registration diagrams
------------------------------------------------
Following diagrams show registrations of components



[← Compile, deploy and interact](/sandbox/fire_insurance_interaction)
[Fire insurance implementation →](/sandbox/fire_insurance_implementation)
---
# Fire insurance implementation - Etherisc Docs
Fire insurance implementation
=============================
[](#overview)
Overview
----------------------
The _fire insurance_ product is a very simple example implementation for a product on the GIF with very few parameters. The idea is to provide a minimal implementation that can be used as a starting point for other products.
The fire insurance can insure a house (identified by its _object name_ and _object value_) with a certain value against fire. In case of a fire, the oracle will provide the product with the size of the damage done by the fire (_S_, _M_, _L_). Depending on the size of the damage, the product will pay out a certain amount of money
* _S_ - None,
* _M_ - 20% of the object value
* _L_ - 100% of the object value.
The fire insurence product consists of three components (contracts):
* The `FireProduct` contract is the main contract that implements the product logic
* The `FireRiskpool` contract is the risk pool contract that holds the funds
* The `FireOracle` contract is the oracle contract that provides the product with data from the _outside world_ (in this case the size of the damage done by a fire)
[](#interaction_diagram)
Interaction diagram
--------------------------------------------
The following diagram shows the interaction between the different components of the fire insurance product and the GIF.

[](#fireproduct_contractsfirefireproduct_sol)
FireProduct (`contracts/fire/FireProduct.sol`)
--------------------------------------------------------------------------------------------
The `FireProduct` contract inherits from the GIF `Product` contract. It provides three main functions (and also some helper functions which we will not discuss here)
* `applyForPolicy`
* `expirePolicy`
* `oracleCallback`
### [](#applyforpolicy)
applyForPolicy
The `applyForPolicy` function takes `objectName` and `objectValue` as parameters and used them to create a new policy for the given object. It returns the `processId` (policy id) of the newly created policy as well as the `requestId` of the orcacle (which is required to provide oracle response).
The `applyForPolicy` function first calculates the premium for the policy based on the `objectValue`. Thereafter it calls [`_newApplication_`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L86)
_on the `Product` contract to create a new \_Application_. The [Application](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L73)
is a data structure that holds all the information about the policy (e.g. the premium, the object name (encoded in the `data` field), the sum insured, etc.).
Right after the application is created, the [`_underwrite_`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L86)
_function is called to underwrite and create the [`Policy`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L82)
, transfer the premium from the customer to the riskpool and set the policy into state \_active_. The important part here is to note, that the policy is only active **after** `_underwrite_` _has been called **and** the premium transfer was \_successful_. If the premium transfer fails, the _Application_ will remain in state `Applied` and no `Policy` is created. A separate `underwrite` function could be used to underwrite the policy at a later point in time, but this is not implemented in the fire insurance product.
Finally the [`_request`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L228)
is called to trigger a fire observation request for the house on the fire oracle.
Its important to note that the `applyForPolicy` function is called by the customer and not by the underwriter.
### [](#expirepolicy)
expirePolicy
The `expirePolicy` function takes the `processId` (policy id) as parameter and expires that policy.
To do that, it just calls the `_expire_` _function on the `Product` contract which sets the state of the `Policy` to \_Expired_. No claims and payouts are possible after a policy has expired.
The `expirePolicy` function must be called by the owner of the product.
### [](#oraclecallback)
oracleCallback
The `oracleCallback` function takes the `requestId`, `processId` and (oracle) `response` as parameters and is called by the oracle to provide the product with the size of the damage done by the fire. As the method also includes claim and payout handling it leads to a completely automated claim and payout process which is executed together with the oracle response.
The function decodes the size of the damage from the `response` and calls the internal `_handleClaim` function.
`_handleClaim` first calculates the payout amount based on the size of the damage and the sum insured.
If the payout amount is larger than zero, a new [Claim](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L94)
is created by calling [`_newClaim`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L165)
immediately followed by a call to [\`\_confirmClaim](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L179)
to confirm the claim (which allows the payout to be processed).
Then a new [`Payout`](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L103)
is created by calling [`_newPayout`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L200)
from the `Product` contract. After that the payout amount is transferred from the riskpool to the customer by calling [`_processPayout`](https://github.com/etherisc/gif-interface/blob/develop/contracts/components/Product.sol#L212)
from the `Product` contract. Finally the policy is expired and closed by calling the respectve methods on the base class.
The four sequential calls to create and confirm the claim as well as create and process the payout can be split into two separate transactions if the product required a more complex claim handling and payout process.
This function can only be called by the oracle.
[](#fireriskpool_contractsfirefireriskpool_sol)
FireRiskpool (`contracts/fire/FireRiskpool.sol`)
------------------------------------------------------------------------------------------------
The `FireRiskpool` contract inherits from the GIF `BasicRiskpool` contract. The `BasicRiskpool` always collateralizes one application using exactly one bundle.
The riskpool must provide (next to some other parameters) the collateralization level, the collateral token and the cap for the total sum insured of the riskpool.
It must also implement the `bundleMatchesApplication` method which provides the logic to match an application with a bundle. In the case of the fire insurance product this matching is very simple and the product will allow for any bundle and application combination for simplicty.
[](#fireoracle_contractsfirefireoracle_sol)
FireOracle (`contracts/fire/FireOracle.sol`)
----------------------------------------------------------------------------------------
The `FireOracle` contract inherits from the GIF `Oracle` contract. The purpose of the oracle is to provide the product with data from the _outside world_ (in this case the size of the damage done by a fire). It needs to send requests to outside systems and return their results.
In the case of the fire insurance product, the oracle will simulate a request to a _fire observation service_ by storing the request id and accepting the result via a call to the `respond` function.
The main methods are
* request
* respond
### [](#request)
request
Takes the `requestId` and `data` as parameters.
The `data` parameter contains an _abi_ encoded string with the `objectName`. The mapping from `objectName` to `requestId` is stored internally for later use in the `respond` function.
### [](#respond)
respond
Takes the `requestId` and `fireCategory` as parameters.
The `fireCategory` is then _abi_ encoded to create the result data which is send back to the product via a call to the `respond` function on the `Oracle` contract. This call triggers the `oracleCallback` function on the product which will then handle the claim and payout process.
[← Fire insurance registration](/sandbox/fire_insurance_registration)
---
# Compile, deploy and interact - Etherisc Docs
Compile, deploy and interact
============================
[](#introduction)
Introduction
------------------------------
This section explains how to compile, deploy and interact with the fire insurance example product.
The fire insurance product is a simple example product that can be used to demonstrate the basic functionality of the GIF platform. It is a simple parametric insurance product that pays out an amount of USDC if a fire event is triggered by the oracle depending on the fire category (_S_ - no payout, _M_ - 20% of the sum insured, _L_ - 100% of the sum insured).
[](#compiling_and_running_the_unit_tests)
Compiling and running the unit tests
------------------------------------------------------------------------------
Start with compiling all contracts.
brownie compile --all
Before running the tests for the first time you will likely need to add an empty `.env` file before.
touch /home/vscode/.brownie/packages/etherisc/gif-contracts@b58fd27/.env
Now run the unit tests for the sandbox.
brownie test -n auto
This shoud result in output similar to the one provided below.
⬢ [Docker] ❯ brownie test -n auto
Brownie v1.19.3 - Python development framework for Ethereum
================================================================= test session starts =================================================================
platform linux -- Python 3.9.16, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /workspace
plugins: eth-brownie-1.19.3, forked-1.4.0, hypothesis-6.27.3, web3-5.31.3, xdist-1.34.0, anyio-3.6.2
gw0 [8] / gw1 [8] / gw2 [8] / gw3 [8] / gw4 [8] / gw5 [8] / gw6 [8] / gw7 [8]
........ [100%]
-- Docs: https://docs.pytest.org/en/stable/warnings.html
========================================================== 8 passed, 101 warnings in 44.52s ===========================================================
The important part is that all tests pass and no errors or failures are shown.
[](#deploy_and_verify_with_ganache)
Deploy and Verify with Ganache
------------------------------------------------------------------
brownie console
In the console use the following steps.
from scripts.deploy_fire import help
help()
The help command then shows an example session.
from scripts.deploy_fire import all_in_1, verify_deploy, create_bundle, create_policy, help
(customer, customer2, product, oracle, riskpool, riskpoolWallet, investor, usdc, instance, instanceService, instanceOperator, bundleId, processId, d) = all_in_1(deploy_all=True)
verify_deploy(d, usdc, product)
This will deploy a new GIF instance as well as the fire insurance product and verify the installation.
[](#deploy_to_a_different_network_containing_a_pre_installed_gif_instance)
Deploy to a different network containing a pre-installed GIF instance
------------------------------------------------------------------------------------------------------------------------------------------------
As an example use the Ganache chain that runs in a separate container (`ganache`) of this devcontainer setup.
brownie console --network=ganache
With an existing instance set parameter `deploy_all=False`. In this case the file `gif_instance_address.txt` needs to exist and contain the addresses of the instance registry The file should be automatically created during the devconainer setup procedure of this repository.
from scripts.deploy_fire import all_in_1, verify_deploy, create_bundle, create_policy, help
(customer, customer2, product, oracle, riskpool, riskpoolWallet, investor, usdc, instance, instanceService, instanceOperator, bundleId, processId, d) = all_in_1(deploy_all=False)
verify_deploy(d, usdc, product)
[](#interacting_with_the_fire_insurance_product_via_console)
Interacting with the fire insurance product via console
--------------------------------------------------------------------------------------------------------------------
### [](#creating_a_new_policy)
Creating a new policy
from scripts.util import s2h
# fund customer wallet and approve treasry with a large amount for simplicity
usdc.transfer(customer, 100000 * 10 ** 6, {'from': instanceOperator})
usdc.approve(instanceService.getTreasuryAddress(), 100000 * 10 ** 6, {'from': customer})
# Create a new policy for a house with a value of 10'000 USDC.
policy = product.applyForPolicy('My house', 10000 * 10 ** 6, {'from': customer})
# Retrieve the `processId` of the new policy
processId = policy.events['LogApplicationCreated'][0]['processId']
# Fetch the state of the applicaton (if [state == 2](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L58) -> policy is underwritten)
instanceService.getApplication(processId).dict()
# Fetch the state of the policy (if [state == 0](https://github.com/etherisc/gif-interface/blob/develop/contracts/modules/IPolicy.sol#L59) -> policy is active, also make sure the premiumPaidAmount is > 0 ... if not probably the allowance was not set correctly)
instanceService.getPolicy(processId).dict()
### [](#sending_an_oracle_response_to_trigger_a_claim_creation_and_payout)
Sending an oracle response to trigger a claim creation and payout
# Retrieve the requestId (created during the underwriting process) of the policy and send oracle response with fire category `M` (20% payout) or use `L` for large fire with 100% payout
requestId = oracle.requestId('My house')
oracle_tx = oracle.respond(requestId, s2h('M'))
# the log list should contain a entry `LogFirePayoutExecuted` with the amount of USDC 2000
oracle_tx.events
### [](#expiring_a_policy)
Expiring a policy
# this will expire the policy - any claims following after expiration will be rejected due to the policy being expired
product.expirePolicy(processId)
[](#interacting_with_the_fire_insurance_product_via_api)
Interacting with the fire insurance product via api
------------------------------------------------------------------------------------------------------------
After the deployment of the contracts, its possible to interact with the product via the openapi interface instead of the brownie console. Therefor start the openapi server
uvicorn server.api:app --host 0.0.0.0
and point your browser to [http://localhost:8000/docs](http://localhost:8000/docs)
. This should show the openapi documentation of the server, the documentation interface also allows interactive usage.
To start, you first need to initialize the openapi instance with the address of the deployed contracts. Then you can create a new policy, send an oracle response and expire the policy as described in the previous section.
Also don’t forget to fund the customer wallet and approve the treasury with a large amount before applying for a policy.
### [](#initialize_the_openapi_instance)
Initialize the openapi instance
Use the `POST /config` request to set the config. The method expects a json body with the following structure (real addresses can be found in the `gif_instance_address.txt` file or via the `product`/`oracle` objects in the brownie console after deployment and the mnemonic (`candy maple cake sugar pudding cream honey rich smooth crumble sweet treat`) is the preconfigured default mnemonic used in the ganache chain of the devcontainer).
{
"registry_address": "0xF12b5dd4EAD5F743C6BaA640B0216200e89B60Da",
"product_address": "0xC791F12F1Cea9B63D3F8C53e5B15ab90bcCe6796",
"oracle_address": "0x61271F03b0C18F6E15da03c21185d419d3f76b97",
"mnemonic": "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat"
}
[](#build_and_test_with_foundry)
Build and test with foundry
------------------------------------------------------------
Foundry is a new toolkit to build and test smart contracts. More documentation about foundry can be found in the foundry [Foundry book](https://book.getfoundry.sh/)
.
The project is configured to use foundry. All contracts in the `contracts` folder can be compiled using foundry as well as brownie (results are stored in `build_foundry`). Foundry tests are writte in solidy and can be found in the `tests_foundry` folder (they need to be separate from brownie based tests). Dependencies are stored in the `lib` folder and are mapped in the `foundry.yaml` config file.
To compile the contracts using foundry, run the following command:
forge build
To run the foundry based tests, run the following command:
forge test
[← Setup of the development environment](/sandbox/setup)
[Fire insurance registration →](/sandbox/fire_insurance_registration)
---
# Shared - Etherisc Docs
Shared
======
Contains interfaces and contracts used across the project.
[](#contracts)
Contracts
------------------------
### [](#INftOwnable)
`INftOwnable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/INftOwnable.sol)
import "@etherisc/gif-next/contracts/shared/INftOwnable.sol";
Functions
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
Events
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
#### [](#INftOwnable-linkToRegisteredNftId--)
`linkToRegisteredNftId() → NftId` external
#### [](#INftOwnable-getNftId--)
`getNftId() → NftId` external
#### [](#INftOwnable-getOwner--)
`getOwner() → address` external
#### [](#INftOwnable-LogNftOwnableNftLinkedToAddress-NftId-address-)
`LogNftOwnableNftLinkedToAddress(NftId indexed nftId, address indexed owner)` event
### [](#IPolicyHolder)
`IPolicyHolder`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/IPolicyHolder.sol)
import "@etherisc/gif-next/contracts/shared/IPolicyHolder.sol";
Generic interface for contracts that need to hold policies and receive payouts. The framework notifies policy holder contracts for policy creation/expiry, claim confirmation and payout execution
Functions
* \[`policyActivated(policyNftId, activatedAt)`\]
* \[`policyExpired(policyNftId, expiredAt)`\]
* \[`claimConfirmed(policyNftId, claimId, amount)`\]
* \[`payoutExecuted(policyNftId, payoutId, amount, beneficiary)`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC721Receiver
* \[`onERC721Received(operator, from, tokenId, data)`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
#### [](#IPolicyHolder-policyActivated-NftId-Timestamp-)
`policyActivated(NftId policyNftId, Timestamp activatedAt)` external
Callback function that will be called after successful policy activation. Active policies may open claims under the activated policy.
#### [](#IPolicyHolder-policyExpired-NftId-Timestamp-)
`policyExpired(NftId policyNftId, Timestamp expiredAt)` external
Callback function to indicate the specified policy has expired. expired policies no longer accept new claims.
#### [](#IPolicyHolder-claimConfirmed-NftId-ClaimId-Amount-)
`claimConfirmed(NftId policyNftId, ClaimId claimId, Amount amount)` external
Callback function to notify the confirmation of the specified claim.
#### [](#IPolicyHolder-payoutExecuted-NftId-PayoutId-Amount-address-)
`payoutExecuted(NftId policyNftId, PayoutId payoutId, Amount amount, address beneficiary)` external
Callback function to notify the successful payout.
### [](#IRegisterable)
`IRegisterable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/IRegisterable.sol)
import "@etherisc/gif-next/contracts/shared/IRegisterable.sol";
Marks contracts that are intended to be registered in the registry.
Functions
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IRegisterable-isActive--)
`isActive() → bool active` external
Returns true iff this contract managed by its authority is active. Queries the IAccessManaged.authority().
#### [](#IRegisterable-getInitialInfo--)
`getInitialInfo() → struct IRegistry.ObjectInfo` external
retuns the object info relevant for registering for this contract IMPORTANT information returned by this function may only be used before the contract is registered in the registry. Once registered this information MUST only be accessed via the registry.
### [](#IRegistryLinked)
`IRegistryLinked`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/IRegistryLinked.sol)
import "@etherisc/gif-next/contracts/shared/IRegistryLinked.sol";
Functions
* \[`getRegistry()`\]
#### [](#IRegistryLinked-getRegistry--)
`getRegistry() → contract IRegistry` external
### [](#IService)
`IService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/IService.sol)
import "@etherisc/gif-next/contracts/shared/IService.sol";
Functions
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IService-getDomain--)
`getDomain() → ObjectType serviceDomain` external
returns the domain for this service. In any GIF release only one service for any given domain may be deployed.
#### [](#IService-getRoleId--)
`getRoleId() → RoleId serviceRoleId` external
returns the GIF release specific role id. These role ids are used to authorize service to service communication.
### [](#NftOwnable)
`NftOwnable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/NftOwnable.sol)
import "@etherisc/gif-next/contracts/shared/NftOwnable.sol";
Modifiers
* [`onlyOwner()`](#NftOwnable-onlyOwner--)
* [`onlyNftOwner(nftId)`](#NftOwnable-onlyNftOwner-NftId-)
* [`onlyNftOfType(nftId, expectedObjectType)`](#NftOwnable-onlyNftOfType-NftId-ObjectType-)
Functions
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#NftOwnable-onlyOwner--)
`onlyOwner()` modifier
enforces msg.sender is owner of nft (or initial owner of nft ownable)
#### [](#NftOwnable-onlyNftOwner-NftId-)
`onlyNftOwner(NftId nftId)` modifier
#### [](#NftOwnable-onlyNftOfType-NftId-ObjectType-)
`onlyNftOfType(NftId nftId, ObjectType expectedObjectType)` modifier
#### [](#NftOwnable-_checkNftType-NftId-ObjectType-)
`_checkNftType(NftId nftId, ObjectType expectedObjectType)` internal
#### [](#NftOwnable-__NftOwnable_init-address-address-)
`__NftOwnable_init(address registry, address initialOwner)` internal
Initialization for upgradable contracts.
#### [](#NftOwnable-linkToRegisteredNftId--)
`linkToRegisteredNftId() → NftId nftId` public
links this contract to nft after registration
#### [](#NftOwnable-getNftId--)
`getNftId() → NftId` public
#### [](#NftOwnable-getOwner--)
`getOwner() → address` public
#### [](#NftOwnable-_linkToNftOwnable-address-)
`_linkToNftOwnable(address nftOwnableAddress) → NftId` internal
used in constructor of registry service manager
### [](#PolicyHolder)
`PolicyHolder`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/PolicyHolder.sol)
import "@etherisc/gif-next/contracts/shared/PolicyHolder.sol";
template implementation for IPolicyHolder
Functions
* \[`_initializePolicyHolder(registryAddress)`\]
* \[`policyActivated(policyNftId, activatedAt)`\]
* \[`policyExpired(policyNftId, expiredAt)`\]
* \[`claimConfirmed(policyNftId, claimId, amount)`\]
* \[`payoutExecuted(policyNftId, payoutId, amount, beneficiary)`\]
* \[`onERC721Received(, , , )`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#PolicyHolder-_initializePolicyHolder-address-)
`_initializePolicyHolder(address registryAddress)` internal
#### [](#PolicyHolder-policyActivated-NftId-Timestamp-)
`policyActivated(NftId policyNftId, Timestamp activatedAt)` external
empty default implementation
#### [](#PolicyHolder-policyExpired-NftId-Timestamp-)
`policyExpired(NftId policyNftId, Timestamp expiredAt)` external
empty default implementation
#### [](#PolicyHolder-claimConfirmed-NftId-ClaimId-Amount-)
`claimConfirmed(NftId policyNftId, ClaimId claimId, Amount amount)` external
empty default implementation
#### [](#PolicyHolder-payoutExecuted-NftId-PayoutId-Amount-address-)
`payoutExecuted(NftId policyNftId, PayoutId payoutId, Amount amount, address beneficiary)` external
empty default implementation
#### [](#PolicyHolder-onERC721Received-address-address-uint256-bytes-)
`onERC721Received(address, address, uint256, bytes) → bytes4` external
### [](#Registerable)
`Registerable`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/Registerable.sol)
import "@etherisc/gif-next/contracts/shared/Registerable.sol";
Modifiers
* [`onlyActive()`](#Registerable-onlyActive--)
Functions
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Registerable-onlyActive--)
`onlyActive()` modifier
#### [](#Registerable-__Registerable_init-address-address-NftId-ObjectType-bool-address-bytes-)
`__Registerable_init(address authority, address registry, NftId parentNftId, ObjectType objectType, bool isInterceptor, address initialOwner, bytes data)` internal
#### [](#Registerable-isActive--)
`isActive() → bool active` public
Returns true iff this contract managed by its authority is active. Queries the IAccessManaged.authority().
#### [](#Registerable-getRelease--)
`getRelease() → VersionPart release` public
Registers a registry contract for a specified chain. Only one chain registry may be registered per chain
#### [](#Registerable-getInitialInfo--)
`getInitialInfo() → struct IRegistry.ObjectInfo info` public
retuns the object info relevant for registering for this contract IMPORTANT information returned by this function may only be used before the contract is registered in the registry. Once registered this information MUST only be accessed via the registry.
### [](#RegistryLinked)
`RegistryLinked`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/RegistryLinked.sol)
import "@etherisc/gif-next/contracts/shared/RegistryLinked.sol";
Functions
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#RegistryLinked-__RegistryLinked_init-address-)
`__RegistryLinked_init(address registry)` internal
initialization for upgradable contracts
#### [](#RegistryLinked-getRegistry--)
`getRegistry() → contract IRegistry` public
### [](#Service)
`Service`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/Service.sol)
import "@etherisc/gif-next/contracts/shared/Service.sol";
service base contract
Functions
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getDomain()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_initialize(, )`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Service-__Service_init-address-address-address-)
`__Service_init(address authority, address registry, address initialOwner)` internal
#### [](#Service-getDomain--)
`getDomain() → ObjectType serviceDomain` external
returns the domain for this service. In any GIF release only one service for any given domain may be deployed.
#### [](#Service-getVersion--)
`getVersion() → Version` public
#### [](#Service-getRoleId--)
`getRoleId() → RoleId serviceRoleId` external
returns the GIF release specific role id. These role ids are used to authorize service to service communication.
#### [](#Service-_getDomain--)
`_getDomain() → ObjectType` internal
#### [](#Service-_getServiceAddress-ObjectType-)
`_getServiceAddress(ObjectType domain) → address` internal
### [](#TokenHandler)
`TokenHandler`[](https://github.com/etherisc/gif-next/blob/develop/contracts/shared/TokenHandler.sol)
import "@etherisc/gif-next/contracts/shared/TokenHandler.sol";
Token specific transfer helper. Contract is derived from TokenHandlerBase and adds authorization based on OpenZeppelin AccessManaged.
Modifiers
* [`onlyService()`](#TokenHandler-onlyService--)
Functions
* \[`constructor(registry, component, token, authority)`\]
* \[`setWallet(newWallet)`\]
* \[`approve(token, amount)`\]
* \[`pullToken(from, amount)`\]
* \[`pushToken(to, amount)`\]
* \[`pushFeeToken(to, amount)`\]
TokenHandlerBase
* \[`checkBalanceAndAllowance(from, amount, checkAmount)`\]
* \[`getWallet()`\]
* \[`_approve(token, amount)`\]
* \[`_setWallet(newWallet)`\]
* \[`_pullToken(from, amount)`\]
* \[`_pushToken(to, amount)`\]
* \[`_transfer(from, to, amount, checkPreconditions)`\]
* \[`_checkBalanceAndAllowance(from, amount, checkAmount)`\]
AccessManaged
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
Events
TokenHandlerBase
* \[`LogTokenHandlerWalletAddressChanged(componentNftId, oldWallet, newWallet)`\]
* \[`LogTokenHandlerWalletTokensTransferred(componentNftId, oldWallet, newWallet, amount)`\]
* \[`LogTokenHandlerTokenApproved(nftId, tokenHandler, token, amount, isMaxAmount)`\]
* \[`LogTokenHandlerTokenTransferred(token, from, to, amount)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#TokenHandler-onlyService--)
`onlyService()` modifier
#### [](#TokenHandler-constructor-address-address-address-address-)
`constructor(address registry, address component, address token, address authority)` public
#### [](#TokenHandler-setWallet-address-)
`setWallet(address newWallet)` external
Sets the wallet address for the component. Seeting the new wallet address to address(0) will set the wallet to the tokenHandler contract itself. If the current wallet has tokens, these will be transferred. If the new wallet address is externally owned, an approval from the owner of the external wallet to the tokenhandler of the component that covers the current component balance must exist.
#### [](#TokenHandler-approve-contract-IERC20Metadata-Amount-)
`approve(contract IERC20Metadata token, Amount amount)` external
Approves token handler to spend up to the specified amount of tokens. Sets spending limit to type(uint256).max for AmountLib.max(). Reverts if component wallet is not component itself. Sets approvel using SareERC20.forceApprove internally.
#### [](#TokenHandler-pullToken-address-Amount-)
`pullToken(address from, Amount amount)` external
Collect tokens from outside of GIF and transfer them to the wallet. This method also checks balance and allowance and makes sure the amount is greater than zero.
#### [](#TokenHandler-pushToken-address-Amount-)
`pushToken(address to, Amount amount)` external
Distribute tokens from a wallet within the scope of gif to some address.
#### [](#TokenHandler-pushFeeToken-address-Amount-)
`pushFeeToken(address to, Amount amount)` external
Distribute fee tokens from a wallet within the scope of gif to some address. Separate push function for component service.
[← registry](/gif-next/3.x/api/registry)
[staking →](/gif-next/3.x/api/staking)
---
# GIF Sandbox - Etherisc Docs
GIF Sandbox
===========
The GIF sandbox actx as an example to show how to setup and use the GIF framework with an example fire insurance product.
If contains the sections
* [Setup of the development environment](setup)
* [Compile, deploy and interact](fire_insurance_interaction)
* [Fire insurance registration](fire_insurance_registration)
* [Fire insurance implementation](fire_insurance_implementation)
[Setup of the development environment →](/sandbox/setup)
---
# Types - Etherisc Docs
Types
=====
Contains the types contracts.
[](#contracts)
Contracts
------------------------
### [](#LibAddressSet)
`LibAddressSet`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/AddressSet.sol)
import "@etherisc/gif-next/contracts/type/AddressSet.sol";
Functions
* \[`add(set, element)`\]
* \[`remove(set, element)`\]
* \[`isEmpty(set)`\]
* \[`contains(set, element)`\]
* \[`getLength(set)`\]
* \[`getElementAt(set, index)`\]
#### [](#LibAddressSet-add-struct-LibAddressSet-Set-address-)
`add(struct LibAddressSet.Set set, address element) → bool added` external
#### [](#LibAddressSet-remove-struct-LibAddressSet-Set-address-)
`remove(struct LibAddressSet.Set set, address element) → bool removed` external
#### [](#LibAddressSet-isEmpty-struct-LibAddressSet-Set-)
`isEmpty(struct LibAddressSet.Set set) → bool empty` external
#### [](#LibAddressSet-contains-struct-LibAddressSet-Set-address-)
`contains(struct LibAddressSet.Set set, address element) → bool inSet` external
#### [](#LibAddressSet-getLength-struct-LibAddressSet-Set-)
`getLength(struct LibAddressSet.Set set) → uint256 length` external
#### [](#LibAddressSet-getElementAt-struct-LibAddressSet-Set-uint256-)
`getElementAt(struct LibAddressSet.Set set, uint256 index) → address element` external
### [](#AmountLib)
`AmountLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Amount.sol)
import "@etherisc/gif-next/contracts/type/Amount.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`toAmount(amount)`\]
* \[`eqz(amount)`\]
* \[`eq(amount1, amount2)`\]
* \[`lt(a1, a2)`\]
* \[`lte(a1, a2)`\]
* \[`gt(a1, a2)`\]
* \[`gte(a1, a2)`\]
* \[`min(a1, a2)`\]
* \[`gtz(amount)`\]
* \[`add(a1, a2)`\]
* \[`sub(a1, a2)`\]
* \[`toInt(amount)`\]
* \[`toUFixed(amount)`\]
* \[`multiplyWith(amount, factor)`\]
* \[`_max()`\]
#### [](#AmountLib-zero--)
`zero() → Amount` public
#### [](#AmountLib-max--)
`max() → Amount` public
#### [](#AmountLib-toAmount-uint256-)
`toAmount(uint256 amount) → Amount` public
converts the uint amount into Amount function reverts if value is exceeding max Amount value
#### [](#AmountLib-eqz-Amount-)
`eqz(Amount amount) → bool` public
return true if amount equals 0
#### [](#AmountLib-eq-Amount-Amount-)
`eq(Amount amount1, Amount amount2) → bool` public
return true if amount1 equals amount2
#### [](#AmountLib-lt-Amount-Amount-)
`lt(Amount a1, Amount a2) → bool` public
return true if amount a1 is less than a2
#### [](#AmountLib-lte-Amount-Amount-)
`lte(Amount a1, Amount a2) → bool` public
return true if amount a1 is less or equal than a2
#### [](#AmountLib-gt-Amount-Amount-)
`gt(Amount a1, Amount a2) → bool` public
return true if amount a1 is greater than a2
#### [](#AmountLib-gte-Amount-Amount-)
`gte(Amount a1, Amount a2) → bool` public
return true if amount a1 is greater or equal than a2
#### [](#AmountLib-min-Amount-Amount-)
`min(Amount a1, Amount a2) → Amount` public
return minimum of a1 and a2.
#### [](#AmountLib-gtz-Amount-)
`gtz(Amount amount) → bool` public
return true if amount is larger than 0
#### [](#AmountLib-add-Amount-Amount-)
`add(Amount a1, Amount a2) → Amount` public
#### [](#AmountLib-sub-Amount-Amount-)
`sub(Amount a1, Amount a2) → Amount` public
#### [](#AmountLib-toInt-Amount-)
`toInt(Amount amount) → uint256` public
#### [](#AmountLib-toUFixed-Amount-)
`toUFixed(Amount amount) → UFixed` public
#### [](#AmountLib-multiplyWith-Amount-UFixed-)
`multiplyWith(Amount amount, UFixed factor) → Amount` public
#### [](#AmountLib-_max--)
`_max() → uint96` internal
### [](#BlocknumberLib)
`BlocknumberLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Blocknumber.sol)
import "@etherisc/gif-next/contracts/type/Blocknumber.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`current()`\]
* \[`toBlocknumber(blocknum)`\]
* \[`eqz(blocknumber)`\]
* \[`gtz(blocknumber)`\]
* \[`gt(a, b)`\]
* \[`gte(a, b)`\]
* \[`lt(a, b)`\]
* \[`lte(a, b)`\]
* \[`eq(a, b)`\]
* \[`ne(a, b)`\]
* \[`toInt(blocknumber)`\]
#### [](#BlocknumberLib-zero--)
`zero() → Blocknumber` public
#### [](#BlocknumberLib-max--)
`max() → Blocknumber` public
#### [](#BlocknumberLib-current--)
`current() → Blocknumber` public
#### [](#BlocknumberLib-toBlocknumber-uint256-)
`toBlocknumber(uint256 blocknum) → Blocknumber` public
#### [](#BlocknumberLib-eqz-Blocknumber-)
`eqz(Blocknumber blocknumber) → bool` public
return true iff blocknumber is 0
#### [](#BlocknumberLib-gtz-Blocknumber-)
`gtz(Blocknumber blocknumber) → bool` public
return true iff blocknumber is > 0
#### [](#BlocknumberLib-gt-Blocknumber-Blocknumber-)
`gt(Blocknumber a, Blocknumber b) → bool isAfter` public
return true if Blocknumber a is greater than Blocknumber b
#### [](#BlocknumberLib-gte-Blocknumber-Blocknumber-)
`gte(Blocknumber a, Blocknumber b) → bool isAfterOrSame` public
return true if Blocknumber a is greater than or equal to Blocknumber b
#### [](#BlocknumberLib-lt-Blocknumber-Blocknumber-)
`lt(Blocknumber a, Blocknumber b) → bool isBefore` public
return true if Blocknumber a is less than Blocknumber b
#### [](#BlocknumberLib-lte-Blocknumber-Blocknumber-)
`lte(Blocknumber a, Blocknumber b) → bool isBeforeOrSame` public
return true if Blocknumber a is less than or equal to Blocknumber b
#### [](#BlocknumberLib-eq-Blocknumber-Blocknumber-)
`eq(Blocknumber a, Blocknumber b) → bool isSame` public
return true if Blocknumber a is equal to Blocknumber b
#### [](#BlocknumberLib-ne-Blocknumber-Blocknumber-)
`ne(Blocknumber a, Blocknumber b) → bool isDifferent` public
return true if Blocknumber a is not equal to Blocknumber b
#### [](#BlocknumberLib-toInt-Blocknumber-)
`toInt(Blocknumber blocknumber) → uint256` public
converts the Blocknumber to a uint256
### [](#ChainIdLib)
`ChainIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/ChainId.sol)
import "@etherisc/gif-next/contracts/type/ChainId.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`current()`\]
* \[`eqz(chainId)`\]
* \[`gtz(chainId)`\]
* \[`toChainId(chainId)`\]
* \[`isCurrentChain(nftId)`\]
* \[`fromNftId(nftId)`\]
* \[`toInt(chainId)`\]
* \[`_fromNftId(nftId)`\]
* \[`_max()`\]
#### [](#ChainIdLib-zero--)
`zero() → ChainId` public
#### [](#ChainIdLib-max--)
`max() → ChainId` public
#### [](#ChainIdLib-current--)
`current() → ChainId` public
#### [](#ChainIdLib-eqz-ChainId-)
`eqz(ChainId chainId) → bool` public
return true iff chainId is 0
#### [](#ChainIdLib-gtz-ChainId-)
`gtz(ChainId chainId) → bool` public
return true iff chainId is > 0
#### [](#ChainIdLib-toChainId-uint256-)
`toChainId(uint256 chainId) → ChainId` public
converts the uint into ChainId function reverts if value is exceeding max ChainId value
#### [](#ChainIdLib-isCurrentChain-NftId-)
`isCurrentChain(NftId nftId) → bool` public
returns true iff NFT ID is from the current chain.
#### [](#ChainIdLib-fromNftId-NftId-)
`fromNftId(NftId nftId) → ChainId` public
#### [](#ChainIdLib-toInt-ChainId-)
`toInt(ChainId chainId) → uint256` public
converts the ChainId to a uint256
#### [](#ChainIdLib-_fromNftId-NftId-)
`_fromNftId(NftId nftId) → uint256 chainIdInt` internal
#### [](#ChainIdLib-_max--)
`_max() → uint96` internal
### [](#ClaimIdLib)
`ClaimIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/ClaimId.sol)
import "@etherisc/gif-next/contracts/type/ClaimId.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`toClaimId(a)`\]
* \[`toInt(a)`\]
* \[`toKey32(claimId, policyNftId)`\]
* \[`toKeyId(claimId, policyNftId)`\]
* \[`gtz(a)`\]
* \[`eq(a, b)`\]
* \[`eqz(a)`\]
#### [](#ClaimIdLib-zero--)
`zero() → ClaimId` public
claim id min value (0), use only for non-initialized values
#### [](#ClaimIdLib-max--)
`max() → ClaimId` public
claim id max value (2\*\*16-1), use only for non-initialized values
#### [](#ClaimIdLib-toClaimId-uint256-)
`toClaimId(uint256 a) → ClaimId` public
Converts an uint into a ClaimId.
#### [](#ClaimIdLib-toInt-ClaimId-)
`toInt(ClaimId a) → uint16` public
Converts the ClaimId to a uint.
#### [](#ClaimIdLib-toKey32-ClaimId-NftId-)
`toKey32(ClaimId claimId, NftId policyNftId) → Key32` public
Converts the ClaimId and NftId to a Key32.
#### [](#ClaimIdLib-toKeyId-ClaimId-NftId-)
`toKeyId(ClaimId claimId, NftId policyNftId) → KeyId` public
Converts the ClaimId and NftId to a Key32.
#### [](#ClaimIdLib-gtz-ClaimId-)
`gtz(ClaimId a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#ClaimIdLib-eq-ClaimId-ClaimId-)
`eq(ClaimId a, ClaimId b) → bool` public
#### [](#ClaimIdLib-eqz-ClaimId-)
`eqz(ClaimId a) → bool` public
Returns true if the value is zero (== 0).
### [](#DistributorTypeLib)
`DistributorTypeLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/DistributorType.sol)
import "@etherisc/gif-next/contracts/type/DistributorType.sol";
Functions
* \[`zero()`\]
* \[`toDistributorType(distributionNftId, name)`\]
* \[`toKey32(id)`\]
* \[`toKeyId(id)`\]
#### [](#DistributorTypeLib-zero--)
`zero() → DistributorType` public
#### [](#DistributorTypeLib-toDistributorType-NftId-string-)
`toDistributorType(NftId distributionNftId, string name) → DistributorType` public
#### [](#DistributorTypeLib-toKey32-DistributorType-)
`toKey32(DistributorType id) → Key32 key` public
Returns the key32 value for the specified nft id and object type.
#### [](#DistributorTypeLib-toKeyId-DistributorType-)
`toKeyId(DistributorType id) → KeyId keyId` public
Returns the key id value for the specified nft id
### [](#FeeLib)
`FeeLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Fee.sol)
import "@etherisc/gif-next/contracts/type/Fee.sol";
Functions
* \[`zero()`\]
* \[`toFee(fractionalFee, fixedFee)`\]
* \[`calculateFee(fee, amount)`\]
* \[`percentageFee(percent)`\]
* \[`eq(a, b)`\]
* \[`gtz(fee)`\]
* \[`eqz(fee)`\]
#### [](#FeeLib-zero--)
`zero() → struct Fee fee` public
Return a zero fee struct (0, 0)
#### [](#FeeLib-toFee-UFixed-uint256-)
`toFee(UFixed fractionalFee, uint256 fixedFee) → struct Fee fee` public
Converts the uint256 to a fee struct.
#### [](#FeeLib-calculateFee-struct-Fee-Amount-)
`calculateFee(struct Fee fee, Amount amount) → Amount feeAmount, Amount netAmount` public
Calculates fee and net amounts for the provided parameters
#### [](#FeeLib-percentageFee-uint8-)
`percentageFee(uint8 percent) → struct Fee fee` public
Return the percent fee struct (x%, 0)
#### [](#FeeLib-eq-struct-Fee-struct-Fee-)
`eq(struct Fee a, struct Fee b) → bool isSame` public
#### [](#FeeLib-gtz-struct-Fee-)
`gtz(struct Fee fee) → bool` public
#### [](#FeeLib-eqz-struct-Fee-)
`eqz(struct Fee fee) → bool` public
### [](#Key32Lib)
`Key32Lib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Key32.sol)
import "@etherisc/gif-next/contracts/type/Key32.sol";
Functions
* \[`toKey32(objectType, id)`\]
* \[`toObjectType(key)`\]
* \[`toKeyId(key)`\]
#### [](#Key32Lib-toKey32-ObjectType-KeyId-)
`toKey32(ObjectType objectType, KeyId id) → Key32` public
#### [](#Key32Lib-toObjectType-Key32-)
`toObjectType(Key32 key) → ObjectType objectType` public
#### [](#Key32Lib-toKeyId-Key32-)
`toKeyId(Key32 key) → KeyId id` public
### [](#LibNftIdSet)
`LibNftIdSet`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/NftIdSet.sol)
import "@etherisc/gif-next/contracts/type/NftIdSet.sol";
Functions
* \[`add(set, nftId)`\]
* \[`remove(set, nftId)`\]
* \[`isEmpty(set)`\]
* \[`contains(set, nftId)`\]
* \[`size(set)`\]
* \[`getElementAt(set, index)`\]
#### [](#LibNftIdSet-add-struct-LibNftIdSet-Set-NftId-)
`add(struct LibNftIdSet.Set set, NftId nftId)` external
#### [](#LibNftIdSet-remove-struct-LibNftIdSet-Set-NftId-)
`remove(struct LibNftIdSet.Set set, NftId nftId)` external
#### [](#LibNftIdSet-isEmpty-struct-LibNftIdSet-Set-)
`isEmpty(struct LibNftIdSet.Set set) → bool empty` external
#### [](#LibNftIdSet-contains-struct-LibNftIdSet-Set-NftId-)
`contains(struct LibNftIdSet.Set set, NftId nftId) → bool inSet` external
#### [](#LibNftIdSet-size-struct-LibNftIdSet-Set-)
`size(struct LibNftIdSet.Set set) → uint256 length` external
#### [](#LibNftIdSet-getElementAt-struct-LibNftIdSet-Set-uint256-)
`getElementAt(struct LibNftIdSet.Set set, uint256 index) → NftId nftId` external
### [](#NftIdLib)
`NftIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/NftId.sol)
import "@etherisc/gif-next/contracts/type/NftId.sol";
Functions
* \[`zero()`\]
* \[`toNftId(id)`\]
* \[`toInt(nftId)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
* \[`eq(a, b)`\]
* \[`ne(a, b)`\]
* \[`toKey32(id, objectType)`\]
* \[`toKeyId(id)`\]
* \[`toNftId(keyId)`\]
#### [](#NftIdLib-zero--)
`zero() → NftId` public
the zero nft id is never a valid nft id and implies a non-initialized value
#### [](#NftIdLib-toNftId-uint256-)
`toNftId(uint256 id) → NftId` public
Converts the uint256 to a NftId.
#### [](#NftIdLib-toInt-NftId-)
`toInt(NftId nftId) → uint96` public
Converts the NftId to a uint256.
#### [](#NftIdLib-gtz-NftId-)
`gtz(NftId a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#NftIdLib-eqz-NftId-)
`eqz(NftId a) → bool` public
Returns true if the value is zero (== 0).
#### [](#NftIdLib-eq-NftId-NftId-)
`eq(NftId a, NftId b) → bool isSame` public
Returns true if the values are equal (==).
#### [](#NftIdLib-ne-NftId-NftId-)
`ne(NftId a, NftId b) → bool isSame` public
Returns true if the values are not equal (!=).
#### [](#NftIdLib-toKey32-NftId-ObjectType-)
`toKey32(NftId id, ObjectType objectType) → Key32 key` public
Returns the key32 value for the specified nft id and object type.
#### [](#NftIdLib-toKeyId-NftId-)
`toKeyId(NftId id) → KeyId keyId` public
Returns the key id value for the specified nft id
#### [](#NftIdLib-toNftId-KeyId-)
`toNftId(KeyId keyId) → NftId nftId` public
### [](#ObjectTypeLib)
`ObjectTypeLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/ObjectType.sol)
import "@etherisc/gif-next/contracts/type/ObjectType.sol";
Functions
* \[`zero()`\]
* \[`toObjectType(objectType)`\]
* \[`toInt(objectType)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
* \[`eq(a, b)`\]
* \[`ne(a, b)`\]
* \[`toName(objectType)`\]
* \[`toVersionedName(name, suffix, release)`\]
#### [](#ObjectTypeLib-zero--)
`zero() → ObjectType` public
#### [](#ObjectTypeLib-toObjectType-uint256-)
`toObjectType(uint256 objectType) → ObjectType` public
Converts the uint256 into ObjectType.
#### [](#ObjectTypeLib-toInt-ObjectType-)
`toInt(ObjectType objectType) → uint96` public
Converts the NftId to a uint256.
#### [](#ObjectTypeLib-gtz-ObjectType-)
`gtz(ObjectType a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#ObjectTypeLib-eqz-ObjectType-)
`eqz(ObjectType a) → bool` public
Returns true if the value is zero (== 0).
#### [](#ObjectTypeLib-eq-ObjectType-ObjectType-)
`eq(ObjectType a, ObjectType b) → bool isSame` public
Returns true if the values are equal (==).
#### [](#ObjectTypeLib-ne-ObjectType-ObjectType-)
`ne(ObjectType a, ObjectType b) → bool isSame` public
Returns true if the values are not equal (!=).
#### [](#ObjectTypeLib-toName-ObjectType-)
`toName(ObjectType objectType) → string name` public
Returns the type/domain name for the provided object type
#### [](#ObjectTypeLib-toVersionedName-string-string-VersionPart-)
`toVersionedName(string name, string suffix, VersionPart release) → string versionedName` external
### [](#PayoutIdLib)
`PayoutIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/PayoutId.sol)
import "@etherisc/gif-next/contracts/type/PayoutId.sol";
Functions
* \[`zero()`\]
* \[`toPayoutId(claimId, payoutNo)`\]
* \[`toClaimId(payoutId)`\]
* \[`toPayoutNo(payoutId)`\]
* \[`toInt(a)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
* \[`toKey32(payoutId, policyNftId)`\]
* \[`toKeyId(payoutId, policyNftId)`\]
#### [](#PayoutIdLib-zero--)
`zero() → PayoutId` public
Converts the PayoutId to a uint.
#### [](#PayoutIdLib-toPayoutId-ClaimId-uint24-)
`toPayoutId(ClaimId claimId, uint24 payoutNo) → PayoutId` public
Converts an uint into a PayoutId.
#### [](#PayoutIdLib-toClaimId-PayoutId-)
`toClaimId(PayoutId payoutId) → ClaimId` public
#### [](#PayoutIdLib-toPayoutNo-PayoutId-)
`toPayoutNo(PayoutId payoutId) → uint24` public
#### [](#PayoutIdLib-toInt-PayoutId-)
`toInt(PayoutId a) → uint40` public
Converts the PayoutId to a uint.
#### [](#PayoutIdLib-gtz-PayoutId-)
`gtz(PayoutId a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#PayoutIdLib-eqz-PayoutId-)
`eqz(PayoutId a) → bool` public
Returns true if the value is zero (== 0).
#### [](#PayoutIdLib-toKey32-PayoutId-NftId-)
`toKey32(PayoutId payoutId, NftId policyNftId) → Key32` public
Converts the PayoutId and NftId to a Key32.
#### [](#PayoutIdLib-toKeyId-PayoutId-NftId-)
`toKeyId(PayoutId payoutId, NftId policyNftId) → KeyId` public
Converts the PayoutId and NftId to a Key32.
### [](#ReferralLib)
`ReferralLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Referral.sol)
import "@etherisc/gif-next/contracts/type/Referral.sol";
Functions
* \[`zero()`\]
* \[`toReferralId(distributionNftId, referral)`\]
* \[`toReferralStatus(status)`\]
* \[`toInt(referralId)`\]
* \[`toKey32(id)`\]
* \[`toKeyId(id)`\]
* \[`eqz(id)`\]
#### [](#ReferralLib-zero--)
`zero() → ReferralId` public
#### [](#ReferralLib-toReferralId-NftId-string-)
`toReferralId(NftId distributionNftId, string referral) → ReferralId` public
#### [](#ReferralLib-toReferralStatus-uint8-)
`toReferralStatus(uint8 status) → ReferralStatus` public
#### [](#ReferralLib-toInt-ReferralId-)
`toInt(ReferralId referralId) → uint256` public
Converts a referral id into a uint256.
#### [](#ReferralLib-toKey32-ReferralId-)
`toKey32(ReferralId id) → Key32 key` public
Returns the key32 value for the specified nft id and object type.
#### [](#ReferralLib-toKeyId-ReferralId-)
`toKeyId(ReferralId id) → KeyId keyId` public
Returns the key id value for the specified nft id
#### [](#ReferralLib-eqz-ReferralId-)
`eqz(ReferralId id) → bool` public
### [](#RiskIdLib)
`RiskIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/RiskId.sol)
import "@etherisc/gif-next/contracts/type/RiskId.sol";
Functions
* \[`zero()`\]
* \[`toInt(riskId)`\]
* \[`toRiskId(productNftId, risk)`\]
* \[`toKey32(riskId)`\]
* \[`toKeyId(id)`\]
* \[`toRiskId(keyId)`\]
* \[`eq(a, b)`\]
* \[`eqz(a)`\]
* \[`gtz(a)`\]
#### [](#RiskIdLib-zero--)
`zero() → RiskId` public
#### [](#RiskIdLib-toInt-RiskId-)
`toInt(RiskId riskId) → uint256` public
#### [](#RiskIdLib-toRiskId-NftId-bytes32-)
`toRiskId(NftId productNftId, bytes32 risk) → RiskId` public
#### [](#RiskIdLib-toKey32-RiskId-)
`toKey32(RiskId riskId) → Key32 key` public
Returns the key32 value for the specified risk id.
#### [](#RiskIdLib-toKeyId-RiskId-)
`toKeyId(RiskId id) → KeyId keyId` public
Returns the key id value for the specified nft id
#### [](#RiskIdLib-toRiskId-KeyId-)
`toRiskId(KeyId keyId) → RiskId riskId` public
#### [](#RiskIdLib-eq-RiskId-RiskId-)
`eq(RiskId a, RiskId b) → bool isSame` public
#### [](#RiskIdLib-eqz-RiskId-)
`eqz(RiskId a) → bool isZero` public
#### [](#RiskIdLib-gtz-RiskId-)
`gtz(RiskId a) → bool isZero` public
### [](#RoleIdLib)
`RoleIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/RoleId.sol)
import "@etherisc/gif-next/contracts/type/RoleId.sol";
Functions
* \[`zero()`\]
* \[`toRoleId(a)`\]
* \[`isServiceRole(roleId)`\]
* \[`toGenericServiceRoleId(objectType)`\]
* \[`toServiceRoleId(serviceDomain, release)`\]
* \[`toInt(a)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
#### [](#RoleIdLib-zero--)
`zero() → RoleId` public
Converts the RoleId to a uint.
#### [](#RoleIdLib-toRoleId-uint256-)
`toRoleId(uint256 a) → RoleId` public
Converts an uint into a role id.
#### [](#RoleIdLib-isServiceRole-RoleId-)
`isServiceRole(RoleId roleId) → bool` public
#### [](#RoleIdLib-toGenericServiceRoleId-ObjectType-)
`toGenericServiceRoleId(ObjectType objectType) → RoleId` public
#### [](#RoleIdLib-toServiceRoleId-ObjectType-VersionPart-)
`toServiceRoleId(ObjectType serviceDomain, VersionPart release) → RoleId serviceRoleId` public
#### [](#RoleIdLib-toInt-RoleId-)
`toInt(RoleId a) → uint64` public
Converts the role id to a uint.
#### [](#RoleIdLib-gtz-RoleId-)
`gtz(RoleId a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#RoleIdLib-eqz-RoleId-)
`eqz(RoleId a) → bool` public
Returns true if the value is zero (== 0).
### [](#SecondsLib)
`SecondsLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Seconds.sol)
import "@etherisc/gif-next/contracts/type/Seconds.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`fromHours(numberOfHours)`\]
* \[`oneDay()`\]
* \[`fromDays(numberOfDays)`\]
* \[`oneYear()`\]
* \[`toSeconds(duration)`\]
* \[`eqz(duration)`\]
* \[`gtz(duration)`\]
* \[`eq(duration1, duration2)`\]
* \[`gt(duration1, duration2)`\]
* \[`lt(duration1, duration2)`\]
* \[`min(duration1, duration2)`\]
* \[`add(duration1, duration2)`\]
* \[`toInt(duration)`\]
* \[`_max()`\]
#### [](#SecondsLib-zero--)
`zero() → Seconds` public
#### [](#SecondsLib-max--)
`max() → Seconds` public
#### [](#SecondsLib-fromHours-uint32-)
`fromHours(uint32 numberOfHours) → Seconds duration` public
#### [](#SecondsLib-oneDay--)
`oneDay() → Seconds duration` public
#### [](#SecondsLib-fromDays-uint32-)
`fromDays(uint32 numberOfDays) → Seconds duration` public
#### [](#SecondsLib-oneYear--)
`oneYear() → Seconds duration` public
#### [](#SecondsLib-toSeconds-uint256-)
`toSeconds(uint256 duration) → Seconds` public
converts the uint duration into Seconds function reverts if duration is exceeding max Seconds value
#### [](#SecondsLib-eqz-Seconds-)
`eqz(Seconds duration) → bool` public
return true if duration equals 0
#### [](#SecondsLib-gtz-Seconds-)
`gtz(Seconds duration) → bool` public
return true if duration is larger than 0
#### [](#SecondsLib-eq-Seconds-Seconds-)
`eq(Seconds duration1, Seconds duration2) → bool` public
return true iff duration1 and duration2 are the same
#### [](#SecondsLib-gt-Seconds-Seconds-)
`gt(Seconds duration1, Seconds duration2) → bool` public
return true if duration1 is larger than duration2
#### [](#SecondsLib-lt-Seconds-Seconds-)
`lt(Seconds duration1, Seconds duration2) → bool` public
return true if duration1 is smaller than duration2
#### [](#SecondsLib-min-Seconds-Seconds-)
`min(Seconds duration1, Seconds duration2) → Seconds` public
returns the smaller of the duration
#### [](#SecondsLib-add-Seconds-Seconds-)
`add(Seconds duration1, Seconds duration2) → Seconds` public
return add duration1 and duration2
#### [](#SecondsLib-toInt-Seconds-)
`toInt(Seconds duration) → uint256` public
#### [](#SecondsLib-_max--)
`_max() → uint40` internal
### [](#StateIdLib)
`StateIdLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/StateId.sol)
import "@etherisc/gif-next/contracts/type/StateId.sol";
Functions
* \[`zero()`\]
* \[`toInt(stateId)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
* \[`eq(a, b)`\]
#### [](#StateIdLib-zero--)
`zero() → StateId` public
#### [](#StateIdLib-toInt-StateId-)
`toInt(StateId stateId) → uint96` public
Converts the NftId to a uint256.
#### [](#StateIdLib-gtz-StateId-)
`gtz(StateId a) → bool` public
Returns true if the value is non-zero (> 0).
#### [](#StateIdLib-eqz-StateId-)
`eqz(StateId a) → bool` public
Returns true if the value is zero (== 0).
#### [](#StateIdLib-eq-StateId-StateId-)
`eq(StateId a, StateId b) → bool isSame` public
Returns true if the values are equal (==).
### [](#TimestampLib)
`TimestampLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Timestamp.sol)
import "@etherisc/gif-next/contracts/type/Timestamp.sol";
Functions
* \[`zero()`\]
* \[`max()`\]
* \[`current()`\]
* \[`toTimestamp(timestamp)`\]
* \[`gt(a, b)`\]
* \[`gte(a, b)`\]
* \[`lt(a, b)`\]
* \[`lte(a, b)`\]
* \[`eq(a, b)`\]
* \[`ne(a, b)`\]
* \[`eqz(timestamp)`\]
* \[`gtz(timestamp)`\]
* \[`addSeconds(timestamp, duration)`\]
* \[`subtractSeconds(timestamp, duration)`\]
* \[`toInt(timestamp)`\]
#### [](#TimestampLib-zero--)
`zero() → Timestamp` public
#### [](#TimestampLib-max--)
`max() → Timestamp` public
#### [](#TimestampLib-current--)
`current() → Timestamp` public
#### [](#TimestampLib-toTimestamp-uint256-)
`toTimestamp(uint256 timestamp) → Timestamp` public
#### [](#TimestampLib-gt-Timestamp-Timestamp-)
`gt(Timestamp a, Timestamp b) → bool isAfter` public
return true if Timestamp a is after Timestamp b
#### [](#TimestampLib-gte-Timestamp-Timestamp-)
`gte(Timestamp a, Timestamp b) → bool isAfterOrSame` public
return true if Timestamp a is after or the same than Timestamp b
#### [](#TimestampLib-lt-Timestamp-Timestamp-)
`lt(Timestamp a, Timestamp b) → bool isBefore` public
return true if Timestamp a is before Timestamp b
#### [](#TimestampLib-lte-Timestamp-Timestamp-)
`lte(Timestamp a, Timestamp b) → bool isBeforeOrSame` public
return true if Timestamp a is before or the same than Timestamp b
#### [](#TimestampLib-eq-Timestamp-Timestamp-)
`eq(Timestamp a, Timestamp b) → bool isSame` public
return true if Timestamp a is equal to Timestamp b
#### [](#TimestampLib-ne-Timestamp-Timestamp-)
`ne(Timestamp a, Timestamp b) → bool isDifferent` public
return true if Timestamp a is not equal to Timestamp b
#### [](#TimestampLib-eqz-Timestamp-)
`eqz(Timestamp timestamp) → bool` public
return true if Timestamp equals 0
#### [](#TimestampLib-gtz-Timestamp-)
`gtz(Timestamp timestamp) → bool` public
return true if Timestamp is larger than 0
#### [](#TimestampLib-addSeconds-Timestamp-Seconds-)
`addSeconds(Timestamp timestamp, Seconds duration) → Timestamp` public
return a new timestamp that is duration seconds later than the provided timestamp.
#### [](#TimestampLib-subtractSeconds-Timestamp-Seconds-)
`subtractSeconds(Timestamp timestamp, Seconds duration) → Timestamp` public
return a new timestamp that is duration seconds earlier than the provided timestamp.
#### [](#TimestampLib-toInt-Timestamp-)
`toInt(Timestamp timestamp) → uint256` public
### [](#UFixedLib)
`UFixedLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/UFixed.sol)
import "@etherisc/gif-next/contracts/type/UFixed.sol";
Functions
* \[`ROUNDING_DOWN()`\]
* \[`ROUNDING_UP()`\]
* \[`ROUNDING_HALF_UP()`\]
* \[`toUFixed(a)`\]
* \[`toUFixed(a, exp)`\]
* \[`decimals()`\]
* \[`toInt(a)`\]
* \[`toInt1000(a)`\]
* \[`toIntWithRounding(a, rounding)`\]
* \[`add(a, b)`\]
* \[`sub(a, b)`\]
* \[`mul(a, b)`\]
* \[`div(a, b)`\]
* \[`gt(a, b)`\]
* \[`gte(a, b)`\]
* \[`lt(a, b)`\]
* \[`lte(a, b)`\]
* \[`eq(a, b)`\]
* \[`gtz(a)`\]
* \[`eqz(a)`\]
* \[`zero()`\]
* \[`one()`\]
* \[`max()`\]
* \[`delta(a, b)`\]
#### [](#UFixedLib-ROUNDING_DOWN--)
`ROUNDING_DOWN() → uint8` public
returns the rounding mode DOWN - 0.4 becomes 0, 0.5 becomes 0, 0.6 becomes 0
#### [](#UFixedLib-ROUNDING_UP--)
`ROUNDING_UP() → uint8` public
returns the rounding mode UP - 0.4 becomes 1, 0.5 becomes 1, 0.6 becomes 1
#### [](#UFixedLib-ROUNDING_HALF_UP--)
`ROUNDING_HALF_UP() → uint8` public
returns the rounding mode HALF\_UP - 0.4 becomes 0, 0.5 becomes 1, 0.6 becomes 1
#### [](#UFixedLib-toUFixed-uint256-)
`toUFixed(uint256 a) → UFixed` public
Converts the uint256 to a uint160 based UFixed. This method reverts if the number is too large to fit in a uint160.
#### [](#UFixedLib-toUFixed-uint256-int8-)
`toUFixed(uint256 a, int8 exp) → UFixed` public
Converts the uint256 to a UFixed with given exponent.
#### [](#UFixedLib-decimals--)
`decimals() → uint256` public
returns the decimals precision of the UFixed type
#### [](#UFixedLib-toInt-UFixed-)
`toInt(UFixed a) → uint256` public
Converts a UFixed to a uint256.
#### [](#UFixedLib-toInt1000-UFixed-)
`toInt1000(UFixed a) → uint256` public
Converts a UFixed to a uint256.
#### [](#UFixedLib-toIntWithRounding-UFixed-uint8-)
`toIntWithRounding(UFixed a, uint8 rounding) → uint256` public
Converts a UFixed to a uint256 with given rounding mode.
#### [](#UFixedLib-add-UFixed-UFixed-)
`add(UFixed a, UFixed b) → UFixed` public
adds two UFixed numbers
#### [](#UFixedLib-sub-UFixed-UFixed-)
`sub(UFixed a, UFixed b) → UFixed` public
subtracts two UFixed numbers
#### [](#UFixedLib-mul-UFixed-UFixed-)
`mul(UFixed a, UFixed b) → UFixed` public
multiplies two UFixed numbers
#### [](#UFixedLib-div-UFixed-UFixed-)
`div(UFixed a, UFixed b) → UFixed` public
divides two UFixed numbers
#### [](#UFixedLib-gt-UFixed-UFixed-)
`gt(UFixed a, UFixed b) → bool isGreaterThan` public
return true if UFixed a is greater than UFixed b
#### [](#UFixedLib-gte-UFixed-UFixed-)
`gte(UFixed a, UFixed b) → bool isGreaterThan` public
return true if UFixed a is greater than or equal to UFixed b
#### [](#UFixedLib-lt-UFixed-UFixed-)
`lt(UFixed a, UFixed b) → bool isGreaterThan` public
return true if UFixed a is less than UFixed b
#### [](#UFixedLib-lte-UFixed-UFixed-)
`lte(UFixed a, UFixed b) → bool isGreaterThan` public
return true if UFixed a is less than or equal to UFixed b
#### [](#UFixedLib-eq-UFixed-UFixed-)
`eq(UFixed a, UFixed b) → bool isEqual` public
return true if UFixed a is equal to UFixed b
#### [](#UFixedLib-gtz-UFixed-)
`gtz(UFixed a) → bool isZero` public
return true if UFixed a is not zero
#### [](#UFixedLib-eqz-UFixed-)
`eqz(UFixed a) → bool isZero` public
return true if UFixed a is zero
#### [](#UFixedLib-zero--)
`zero() → UFixed` public
#### [](#UFixedLib-one--)
`one() → UFixed` public
#### [](#UFixedLib-max--)
`max() → UFixed` public
#### [](#UFixedLib-delta-UFixed-UFixed-)
`delta(UFixed a, UFixed b) → UFixed` public
return the absolute delta between two UFixed numbers
### [](#VersionLib)
`VersionLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Version.sol)
import "@etherisc/gif-next/contracts/type/Version.sol";
Functions
* \[`toInt(version)`\]
* \[`toUint64(version)`\]
* \[`toMajorPart(version)`\]
* \[`toVersionParts(version)`\]
* \[`toVersion(major, minor, patch)`\]
* \[`toVersion(versionNumber)`\]
* \[`zeroVersion()`\]
#### [](#VersionLib-toInt-Version-)
`toInt(Version version) → uint256` external
#### [](#VersionLib-toUint64-Version-)
`toUint64(Version version) → uint64` external
#### [](#VersionLib-toMajorPart-Version-)
`toMajorPart(Version version) → VersionPart major` external
#### [](#VersionLib-toVersionParts-Version-)
`toVersionParts(Version version) → VersionPart major, VersionPart minor, VersionPart patch` external
#### [](#VersionLib-toVersion-uint256-uint256-uint256-)
`toVersion(uint256 major, uint256 minor, uint256 patch) → Version` external
#### [](#VersionLib-toVersion-uint64-)
`toVersion(uint64 versionNumber) → Version` external
#### [](#VersionLib-zeroVersion--)
`zeroVersion() → Version` external
### [](#VersionPartLib)
`VersionPartLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/type/Version.sol)
import "@etherisc/gif-next/contracts/type/Version.sol";
Functions
* \[`releaseMin()`\]
* \[`releaseMax()`\]
* \[`isValidRelease(release)`\]
* \[`toString(a)`\]
* \[`eqz(a)`\]
* \[`gtz(a)`\]
* \[`toInt(a)`\]
* \[`toVersionPart(a)`\]
#### [](#VersionPartLib-releaseMin--)
`releaseMin() → VersionPart` public
#### [](#VersionPartLib-releaseMax--)
`releaseMax() → VersionPart` public
#### [](#VersionPartLib-isValidRelease-VersionPart-)
`isValidRelease(VersionPart release) → bool` external
#### [](#VersionPartLib-toString-VersionPart-)
`toString(VersionPart a) → string` external
#### [](#VersionPartLib-eqz-VersionPart-)
`eqz(VersionPart a) → bool` external
#### [](#VersionPartLib-gtz-VersionPart-)
`gtz(VersionPart a) → bool` external
#### [](#VersionPartLib-toInt-VersionPart-)
`toInt(VersionPart a) → uint256` external
#### [](#VersionPartLib-toVersionPart-uint256-)
`toVersionPart(uint256 a) → VersionPart` public
[← staking](/gif-next/3.x/api/staking)
[upgradeability →](/gif-next/3.x/api/upgradeability)
---
# Pool - Etherisc Docs
Pool
====
Contains interfaces and contracts related to pools.
[](#contracts)
Contracts
------------------------
### [](#IPoolComponent)
`IPoolComponent`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/IPoolComponent.sol)
import "@etherisc/gif-next/contracts/pool/IPoolComponent.sol";
pool components hold and manage the collateral to cover active policies pools come in different flavors
Functions
* \[`verifyApplication(applicationNftId, bundleNftId, collateralizationAmount)`\]
* \[`applicationMatchesBundle(applicationNftId, applicationData, bundleNftId, bundleFilter, collateralizationAmount)`\]
* \[`processConfirmedClaim(policyNftId, claimId, amount)`\]
* \[`getInitialPoolInfo()`\]
IInstanceLinkedComponent
* \[`withdrawFees(amount)`\]
* \[`getInstance()`\]
IAuthorizedComponent
* \[`getAuthorization()`\]
IComponent
* \[`getName()`\]
* \[`getToken()`\]
* \[`getTokenHandler()`\]
* \[`getWallet()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
ITransferInterceptor
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogPoolVerifiedByPool(pool, applicationNftId, collateralizationAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IPoolComponent-verifyApplication-NftId-NftId-Amount-)
`verifyApplication(NftId applicationNftId, NftId bundleNftId, Amount collateralizationAmount)` external
This is a callback function that is called by the product service when underwriting a policy. The pool has the option to check the details and object to underwriting by reverting. The function is only called for "active" pools that ask to be involved/notified. The default implementation is empty.
#### [](#IPoolComponent-applicationMatchesBundle-NftId-bytes-NftId-bytes-Amount-)
`applicationMatchesBundle(NftId applicationNftId, bytes applicationData, NftId bundleNftId, bytes bundleFilter, Amount collateralizationAmount) → bool isMatching` external
Returns true iff the application matches with the bundle. This is a callback function that is only called if a pool declares itself as a verifying pool The default implementation returns true.
#### [](#IPoolComponent-processConfirmedClaim-NftId-ClaimId-Amount-)
`processConfirmedClaim(NftId policyNftId, ClaimId claimId, Amount amount)` external
This is a callback function that is called by the claim service when a claim is confirmed. The pool has the option to implement custom behavirous such as triggering a reinsurance claim or blocking the claim confirmaation. The default implementation is empty.
#### [](#IPoolComponent-getInitialPoolInfo--)
`getInitialPoolInfo() → struct IComponents.PoolInfo info` external
Returns initial pool specific infos for this pool
#### [](#IPoolComponent-LogPoolVerifiedByPool-address-NftId-Amount-)
`LogPoolVerifiedByPool(address indexed pool, NftId indexed applicationNftId, Amount collateralizationAmount)` event
### [](#IPoolService)
`IPoolService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/IPoolService.sol)
import "@etherisc/gif-next/contracts/pool/IPoolService.sol";
Functions
* \[`setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`lockCollateral(instance, token, productNftId, applicationNftId, bundleNftId, sumInsuredAmount)`\]
* \[`releaseCollateral(instance, policyNftId, policyInfo)`\]
* \[`processPayout(instanceReader, instanceStore, productNftId, policyNftId, bundleNftId, payoutId, payoutAmount, payoutBeneficiary)`\]
* \[`stake(bundleNftId, amount)`\]
* \[`unstake(bundleNftId, amount)`\]
* \[`closeBundle(bundleNftId)`\]
* \[`withdrawBundleFees(bundleNftId, amount)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`fundPoolWallet(amount)`\]
* \[`defundPoolWallet(amount)`\]
* \[`processSale(bundleNftId, premium)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogPoolServiceMaxBalanceAmountUpdated(poolNftId, previousMaxCapitalAmount, currentMaxCapitalAmount)`\]
* \[`LogPoolServiceWalletFunded(poolNftId, poolOwner, amount)`\]
* \[`LogPoolServiceWalletDefunded(poolNftId, poolOwner, amount)`\]
* \[`LogPoolServiceBundleCreated(instanceNftId, poolNftId, bundleNftId)`\]
* \[`LogPoolServiceBundleClosed(instanceNftId, poolNftId, bundleNftId, balanceAmount, feeAmount)`\]
* \[`LogPoolServiceBundleStaked(instanceNftId, poolNftId, bundleNftId, amount, netAmount)`\]
* \[`LogPoolServiceBundleUnstaked(instanceNftId, poolNftId, bundleNftId, amount, netAmount)`\]
* \[`LogPoolServiceFeesWithdrawn(bundleNftId, recipient, amount, tokenAddress)`\]
* \[`LogPoolServiceProcessFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`LogPoolServiceApplicationVerified(poolNftId, bundleNftId, applicationNftId, totalCollateralAmount)`\]
* \[`LogPoolServiceCollateralLocked(poolNftId, bundleNftId, applicationNftId, totalCollateralAmount, lockedCollateralAmount)`\]
* \[`LogPoolServiceCollateralReleased(bundleNftId, policyNftId, releasedCollateralAmount)`\]
* \[`LogPoolServiceSaleProcessed(poolNftId, bundleNftId, bundleNetAmount, bundleFeeAmount, poolFeeAmount)`\]
* \[`LogPoolServicePayoutProcessed(poolNftId, bundleNftId, policyNftId, payoutId, netPayoutAmount, processingFeeAmount, payoutBeneficiary)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IPoolService-setMaxBalanceAmount-Amount-)
`setMaxBalanceAmount(Amount maxBalanceAmount)` external
sets the max balance amount for the calling pool
#### [](#IPoolService-lockCollateral-contract-IInstance-address-NftId-NftId-NftId-Amount-)
`lockCollateral(contract IInstance instance, address token, NftId productNftId, NftId applicationNftId, NftId bundleNftId, Amount sumInsuredAmount) → Amount localCollateralAmount, Amount totalCollateralAmount` external
locks required collateral to cover the specified application (and turn it into a policy) - retention level == 1: the full collateral amount will be locked by the specified bundle - retention level < 1: a part of the coverage is provided by the specified bundle, the rest by the pool component in which case the pool component might hold a re-insurance policy may only be called by the policy service for unlocked pool components
#### [](#IPoolService-releaseCollateral-contract-IInstance-NftId-struct-IPolicy-PolicyInfo-)
`releaseCollateral(contract IInstance instance, NftId policyNftId, struct IPolicy.PolicyInfo policyInfo)` external
releases the remaining collateral linked to the specified policy may only be called by the policy service for unlocked pool components
#### [](#IPoolService-processPayout-contract-InstanceReader-contract-InstanceStore-NftId-NftId-NftId-PayoutId-Amount-address-)
`processPayout(contract InstanceReader instanceReader, contract InstanceStore instanceStore, NftId productNftId, NftId policyNftId, NftId bundleNftId, PayoutId payoutId, Amount payoutAmount, address payoutBeneficiary) → Amount netPayoutAmount, Amount processingFeeAmount` external
reduces the locked collateral in the bundle associated with the specified policy and updates pool/bundle counters every payout of a policy reduces the collateral by the payout amount may only be called by the claim service for unlocked pool components
#### [](#IPoolService-stake-NftId-Amount-)
`stake(NftId bundleNftId, Amount amount) → Amount netAmount` external
increase stakes for bundle staking fees will be deducted by the pool service from the staking amount may only be called by registered and unlocked pool components
#### [](#IPoolService-unstake-NftId-Amount-)
`unstake(NftId bundleNftId, Amount amount) → Amount netAmount` external
decrease stakes for bundle performance fees will be deducted by the pool service from the staking amount may only be called by registered and unlocked pool components
#### [](#IPoolService-closeBundle-NftId-)
`closeBundle(NftId bundleNftId)` external
closes the specified bundle only open bundles (active or locked) may be closed to close a bundle it may not have any non-closed polices attached to it bundle fees and remaining capital (after deduction of the performance fee) will be transferred to the bundle owner may only be called by registered and unlocked pool components
#### [](#IPoolService-withdrawBundleFees-NftId-Amount-)
`withdrawBundleFees(NftId bundleNftId, Amount amount) → Amount withdrawnAmount` external
Withdraw bundle feeds for the specified bundle.
#### [](#IPoolService-processFundedClaim-NftId-ClaimId-Amount-)
`processFundedClaim(NftId policyNftId, ClaimId claimId, Amount availableAmount)` external
Informs product about available funds to process a confirmed claim. The function triggers a callback to the product component when the product’s property isProcessingFundedClaims is set.
#### [](#IPoolService-fundPoolWallet-Amount-)
`fundPoolWallet(Amount amount)` external
Fund the pool wallet with the provided amount. This function will collect the amount from the pool owner and transfers it to the pool wallet. The function will not update balance amounts managed by the framework. Only available for externally managed pools.
#### [](#IPoolService-defundPoolWallet-Amount-)
`defundPoolWallet(Amount amount)` external
Defund the specified pool wallet with the provided amount. This function will transfer the amount from the pool wallet to the pool owner. The function will not update balance amounts managed by the framework. Only available for externally managed pools.
#### [](#IPoolService-processSale-NftId-struct-IPolicy-PremiumInfo-)
`processSale(NftId bundleNftId, struct IPolicy.PremiumInfo premium)` external
processes the sale of a bundle and track the pool fee and bundle fee amounts
#### [](#IPoolService-LogPoolServiceMaxBalanceAmountUpdated-NftId-Amount-Amount-)
`LogPoolServiceMaxBalanceAmountUpdated(NftId indexed poolNftId, Amount previousMaxCapitalAmount, Amount currentMaxCapitalAmount)` event
#### [](#IPoolService-LogPoolServiceWalletFunded-NftId-address-Amount-)
`LogPoolServiceWalletFunded(NftId indexed poolNftId, address indexed poolOwner, Amount amount)` event
#### [](#IPoolService-LogPoolServiceWalletDefunded-NftId-address-Amount-)
`LogPoolServiceWalletDefunded(NftId indexed poolNftId, address indexed poolOwner, Amount amount)` event
#### [](#IPoolService-LogPoolServiceBundleCreated-NftId-NftId-NftId-)
`LogPoolServiceBundleCreated(NftId indexed instanceNftId, NftId indexed poolNftId, NftId indexed bundleNftId)` event
#### [](#IPoolService-LogPoolServiceBundleClosed-NftId-NftId-NftId-Amount-Amount-)
`LogPoolServiceBundleClosed(NftId indexed instanceNftId, NftId indexed poolNftId, NftId indexed bundleNftId, Amount balanceAmount, Amount feeAmount)` event
#### [](#IPoolService-LogPoolServiceBundleStaked-NftId-NftId-NftId-Amount-Amount-)
`LogPoolServiceBundleStaked(NftId indexed instanceNftId, NftId indexed poolNftId, NftId indexed bundleNftId, Amount amount, Amount netAmount)` event
#### [](#IPoolService-LogPoolServiceBundleUnstaked-NftId-NftId-NftId-Amount-Amount-)
`LogPoolServiceBundleUnstaked(NftId indexed instanceNftId, NftId indexed poolNftId, NftId indexed bundleNftId, Amount amount, Amount netAmount)` event
#### [](#IPoolService-LogPoolServiceFeesWithdrawn-NftId-address-Amount-address-)
`LogPoolServiceFeesWithdrawn(NftId indexed bundleNftId, address indexed recipient, Amount amount, address indexed tokenAddress)` event
#### [](#IPoolService-LogPoolServiceProcessFundedClaim-NftId-ClaimId-Amount-)
`LogPoolServiceProcessFundedClaim(NftId indexed policyNftId, ClaimId indexed claimId, Amount availableAmount)` event
#### [](#IPoolService-LogPoolServiceApplicationVerified-NftId-NftId-NftId-Amount-)
`LogPoolServiceApplicationVerified(NftId indexed poolNftId, NftId indexed bundleNftId, NftId indexed applicationNftId, Amount totalCollateralAmount)` event
#### [](#IPoolService-LogPoolServiceCollateralLocked-NftId-NftId-NftId-Amount-Amount-)
`LogPoolServiceCollateralLocked(NftId indexed poolNftId, NftId indexed bundleNftId, NftId indexed applicationNftId, Amount totalCollateralAmount, Amount lockedCollateralAmount)` event
#### [](#IPoolService-LogPoolServiceCollateralReleased-NftId-NftId-Amount-)
`LogPoolServiceCollateralReleased(NftId indexed bundleNftId, NftId indexed policyNftId, Amount releasedCollateralAmount)` event
#### [](#IPoolService-LogPoolServiceSaleProcessed-NftId-NftId-Amount-Amount-Amount-)
`LogPoolServiceSaleProcessed(NftId indexed poolNftId, NftId indexed bundleNftId, Amount bundleNetAmount, Amount bundleFeeAmount, Amount poolFeeAmount)` event
#### [](#IPoolService-LogPoolServicePayoutProcessed-NftId-NftId-NftId-PayoutId-Amount-Amount-address-)
`LogPoolServicePayoutProcessed(NftId indexed poolNftId, NftId indexed bundleNftId, NftId indexed policyNftId, PayoutId payoutId, Amount netPayoutAmount, Amount processingFeeAmount, address payoutBeneficiary)` event
### [](#IBundleService)
`IBundleService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/IBundleService.sol)
import "@etherisc/gif-next/contracts/pool/IBundleService.sol";
Functions
* \[`create(owner, fee, lifetime, filter)`\]
* \[`stake(instanceReader, instanceStore, bundleNftId, amount)`\]
* \[`unstake(instanceStore, bundleNftId, amount)`\]
* \[`extend(bundleNftId, lifetimeExtension)`\]
* \[`setLocked(bundleNftId, locked)`\]
* \[`close(instance, bundleNftId)`\]
* \[`setFee(bundleNftId, fee)`\]
* \[`lockCollateral(instance, policyNftId, bundleNftId, collateralAmount)`\]
* \[`releaseCollateral(instanceStore, policyNftId, bundleNftId, collateralAmount)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogBundleServiceBundleCreated(bundleNftId, poolNftId, lifetime, fixedFee, fractionalFee)`\]
* \[`LogBundleServiceBundleClosed(bundleNftId)`\]
* \[`LogBundleServiceBundleLocked(bundleNftId, locked)`\]
* \[`LogBundleServiceBundleExtended(bundleNftId, lifetimeExtension, extendedExpiredAt)`\]
* \[`LogBundleServiceBundleFeeUpdated(bundleNftId, fixedFee, fractionalFee)`\]
* \[`LogBundleServiceCollateralLocked(bundleNftId, policyNftId, collateralAmount)`\]
* \[`LogBundleServiceCollateralReleased(bundleNftId, policyNftId, collateralAmount)`\]
* \[`LogBundleServiceBundleStaked(bundleNftId, amount)`\]
* \[`LogBundleServiceBundleUnstaked(bundleNftId, amount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IBundleService-create-address-struct-Fee-Seconds-bytes-)
`create(address owner, struct Fee fee, Seconds lifetime, bytes filter) → NftId bundleNftId` external
Create a new bundle for the specified attributes.
#### [](#IBundleService-stake-contract-InstanceReader-contract-InstanceStore-NftId-Amount-)
`stake(contract InstanceReader instanceReader, contract InstanceStore instanceStore, NftId bundleNftId, Amount amount)` external
increase bundle stakes by the specified amount. bundle must not be expired or closed may only be called by the pool service
#### [](#IBundleService-unstake-contract-InstanceStore-NftId-Amount-)
`unstake(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount) → Amount unstakedAmount` external
decrease bundle stakes by the specified amount may only be called by the pool service
#### [](#IBundleService-extend-NftId-Seconds-)
`extend(NftId bundleNftId, Seconds lifetimeExtension) → Timestamp extendedExpiredAt` external
extend the lifetime of the bundle by the specified time in seconds
#### [](#IBundleService-setLocked-NftId-bool-)
`setLocked(NftId bundleNftId, bool locked)` external
locks/unlocks the specified bundle. locked bundles are not available to collateralize new policies. may only be called by registered and unlocked pool components.
#### [](#IBundleService-close-contract-IInstance-NftId-)
`close(contract IInstance instance, NftId bundleNftId) → Amount balanceAmount, Amount feeAmount` external
closes the specified bundle only open bundles (active or locked) may be closed to close a bundle it may not have any non-closed polices attached to it may only be called by registered and unlocked pool components
#### [](#IBundleService-setFee-NftId-struct-Fee-)
`setFee(NftId bundleNftId, struct Fee fee)` external
set bundle fee to provided value may only be called by registered and unlocked pool components
#### [](#IBundleService-lockCollateral-contract-IInstance-NftId-NftId-Amount-)
`lockCollateral(contract IInstance instance, NftId policyNftId, NftId bundleNftId, Amount collateralAmount)` external
locks the specified collateral in the bundle the locked collateral is added to the bundle locked capital the bundles' fees are updated with the fees for this premium the premium (minus bundle fee) is added to the bundle capital may only be called by pool service
#### [](#IBundleService-releaseCollateral-contract-InstanceStore-NftId-NftId-Amount-)
`releaseCollateral(contract InstanceStore instanceStore, NftId policyNftId, NftId bundleNftId, Amount collateralAmount)` external
releases the specified collateral in the bundle may only be called by pool service
#### [](#IBundleService-LogBundleServiceBundleCreated-NftId-NftId-Seconds-Amount-UFixed-)
`LogBundleServiceBundleCreated(NftId indexed bundleNftId, NftId indexed poolNftId, Seconds lifetime, Amount fixedFee, UFixed fractionalFee)` event
#### [](#IBundleService-LogBundleServiceBundleClosed-NftId-)
`LogBundleServiceBundleClosed(NftId indexed bundleNftId)` event
#### [](#IBundleService-LogBundleServiceBundleLocked-NftId-bool-)
`LogBundleServiceBundleLocked(NftId indexed bundleNftId, bool indexed locked)` event
#### [](#IBundleService-LogBundleServiceBundleExtended-NftId-Seconds-Timestamp-)
`LogBundleServiceBundleExtended(NftId indexed bundleNftId, Seconds lifetimeExtension, Timestamp extendedExpiredAt)` event
#### [](#IBundleService-LogBundleServiceBundleFeeUpdated-NftId-Amount-UFixed-)
`LogBundleServiceBundleFeeUpdated(NftId indexed bundleNftId, Amount fixedFee, UFixed fractionalFee)` event
#### [](#IBundleService-LogBundleServiceCollateralLocked-NftId-NftId-Amount-)
`LogBundleServiceCollateralLocked(NftId indexed bundleNftId, NftId indexed policyNftId, Amount collateralAmount)` event
#### [](#IBundleService-LogBundleServiceCollateralReleased-NftId-NftId-Amount-)
`LogBundleServiceCollateralReleased(NftId indexed bundleNftId, NftId indexed policyNftId, Amount collateralAmount)` event
#### [](#IBundleService-LogBundleServiceBundleStaked-NftId-Amount-)
`LogBundleServiceBundleStaked(NftId indexed bundleNftId, Amount amount)` event
#### [](#IBundleService-LogBundleServiceBundleUnstaked-NftId-Amount-)
`LogBundleServiceBundleUnstaked(NftId indexed bundleNftId, Amount amount)` event
### [](#Pool)
`Pool`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/Pool.sol)
import "@etherisc/gif-next/contracts/pool/Pool.sol";
Modifiers
* [`onlyBundleOwner(bundleNftId)`](#Pool-onlyBundleOwner-NftId-)
Functions
* \[`getContractLocation(name)`\]
* \[`verifyApplication(applicationNftId, bundleNftId, collateralizationAmount)`\]
* \[`processConfirmedClaim(policyNftId, claimId, amount)`\]
* \[`applicationMatchesBundle(applicationNftId, applicationData, bundleNftId, bundleFilter, collateralizationAmount)`\]
* \[`getInitialPoolInfo()`\]
* \[`__Pool_init(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`_setPoolFees(poolFee, stakingFee, performanceFee)`\]
* \[`_setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`_fundPoolWallet(amount)`\]
* \[`_defundPoolWallet(amount)`\]
* \[`_createBundle(bundleOwner, fee, lifetime, filter)`\]
* \[`_setBundleFee(bundleNftId, fee)`\]
* \[`_stake(bundleNftId, amount)`\]
* \[`_unstake(bundleNftId, amount)`\]
* \[`_extend(bundleNftId, lifetimeExtension)`\]
* \[`_setBundleLocked(bundleNftId, locked)`\]
* \[`_closeBundle(bundleNftId)`\]
* \[`_withdrawBundleFees(bundleNftId, amount)`\]
* \[`_processFundedClaim(policyNftId, claimId, availableAmount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IPoolComponent
* \[`LogPoolVerifiedByPool(pool, applicationNftId, collateralizationAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Pool-onlyBundleOwner-NftId-)
`onlyBundleOwner(NftId bundleNftId)` modifier
#### [](#Pool-getContractLocation-bytes-)
`getContractLocation(bytes name) → bytes32 hash` external
#### [](#Pool-verifyApplication-NftId-NftId-Amount-)
`verifyApplication(NftId applicationNftId, NftId bundleNftId, Amount collateralizationAmount)` public
see {IPoolComponent.verifyApplication}
#### [](#Pool-processConfirmedClaim-NftId-ClaimId-Amount-)
`processConfirmedClaim(NftId policyNftId, ClaimId claimId, Amount amount)` public
see {IPoolComponent.processConfirmedClaim}
#### [](#Pool-applicationMatchesBundle-NftId-bytes-NftId-bytes-Amount-)
`applicationMatchesBundle(NftId applicationNftId, bytes applicationData, NftId bundleNftId, bytes bundleFilter, Amount collateralizationAmount) → bool isMatching` public
see {IPoolComponent.applicationMatchesBundle} Default implementation always returns true. Override this function to implement any custom application verification. Calling super.applicationMatchesBundle will ensure validation of application and bundle nft ids.
#### [](#Pool-getInitialPoolInfo--)
`getInitialPoolInfo() → struct IComponents.PoolInfo poolInfo` public
Returns initial pool specific infos for this pool
#### [](#Pool-__Pool_init-address-NftId-string-struct-IComponents-PoolInfo-contract-IAuthorization-address-)
`__Pool_init(address registry, NftId productNftId, string name, struct IComponents.PoolInfo poolInfo, contract IAuthorization authorization, address initialOwner)` internal
#### [](#Pool-_setPoolFees-struct-Fee-struct-Fee-struct-Fee-)
`_setPoolFees(struct Fee poolFee, struct Fee stakingFee, struct Fee performanceFee)` internal
Update pool fees to the specified values. Pool fee: are deducted from the premium amount and goes to the pool owner. Staking fee: are deducted from the staked tokens by a bundle owner and goes to the pool owner. Performance fee: when a bundle is closed a bundle specific profit is calculated. The performance fee is deducted from this profit and goes to the pool owner.
#### [](#Pool-_setMaxBalanceAmount-Amount-)
`_setMaxBalanceAmount(Amount maxBalanceAmount)` internal
Sets the maximum balance amound held by this pool. Function may only be called by pool owner.
#### [](#Pool-_fundPoolWallet-Amount-)
`_fundPoolWallet(Amount amount)` internal
Fund the pool wallet with the specified amount. Function is only available for externally managed pools.
#### [](#Pool-_defundPoolWallet-Amount-)
`_defundPoolWallet(Amount amount)` internal
Withdraw the specified amount from the pool wallet. Function is only available for externally managed pools.
#### [](#Pool-_createBundle-address-struct-Fee-Seconds-bytes-)
`_createBundle(address bundleOwner, struct Fee fee, Seconds lifetime, bytes filter) → NftId bundleNftId` internal
Creates a new empty bundle using the provided parameter values.
#### [](#Pool-_setBundleFee-NftId-struct-Fee-)
`_setBundleFee(NftId bundleNftId, struct Fee fee)` internal
Sets the fee for the specified bundle. The fee is added on top of the poolFee and deducted from the premium amounts Via these fees individual bundler owner may earn income per policy in the context of peer to peer pools.
#### [](#Pool-_stake-NftId-Amount-)
`_stake(NftId bundleNftId, Amount amount) → Amount` internal
increases the staked tokens by the specified amount bundle MUST be in active or locked state
#### [](#Pool-_unstake-NftId-Amount-)
`_unstake(NftId bundleNftId, Amount amount) → Amount netAmount` internal
decreases the staked tokens by the specified amount bundle MUST be in active, locked or closed state
#### [](#Pool-_extend-NftId-Seconds-)
`_extend(NftId bundleNftId, Seconds lifetimeExtension) → Timestamp extendedExpiredAt` internal
extends the bundle lifetime of the bundle by the specified time bundle MUST be in active or locked state
#### [](#Pool-_setBundleLocked-NftId-bool-)
`_setBundleLocked(NftId bundleNftId, bool locked)` internal
Locks the specified bundle. A bundle to be locked MUST be in active state. Locked bundles may not be used to collateralize any new policy.
#### [](#Pool-_closeBundle-NftId-)
`_closeBundle(NftId bundleNftId)` internal
Close the specified bundle. A bundle to be closed MUST be in active or locked state. To close a bundle all all linked policies MUST be in closed state as well. Closing a bundle finalizes the bundle bookkeeping including overall profit calculation. Once a bundle is closed this action cannot be reversed.
#### [](#Pool-_withdrawBundleFees-NftId-Amount-)
`_withdrawBundleFees(NftId bundleNftId, Amount amount) → Amount withdrawnAmount` internal
Withdraws the specified amount of fees from the bundle.
#### [](#Pool-_processFundedClaim-NftId-ClaimId-Amount-)
`_processFundedClaim(NftId policyNftId, ClaimId claimId, Amount availableAmount)` internal
### [](#BasicPool)
`BasicPool`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/BasicPool.sol)
import "@etherisc/gif-next/contracts/pool/BasicPool.sol";
Functions
* \[`_initializeBasicPool(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`stake(bundleNftId, amount)`\]
* \[`unstake(bundleNftId, amount)`\]
* \[`extend(bundleNftId, lifetimeExtension)`\]
* \[`setBundleLocked(bundleNftId, locked)`\]
* \[`closeBundle(bundleNftId)`\]
* \[`setBundleFee(bundleNftId, fee)`\]
* \[`withdrawBundleFees(bundleNftId, amount)`\]
* \[`setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`setFees(poolFee, stakingFee, performanceFee)`\]
Pool
* \[`getContractLocation(name)`\]
* \[`verifyApplication(applicationNftId, bundleNftId, collateralizationAmount)`\]
* \[`processConfirmedClaim(policyNftId, claimId, amount)`\]
* \[`applicationMatchesBundle(applicationNftId, applicationData, bundleNftId, bundleFilter, collateralizationAmount)`\]
* \[`getInitialPoolInfo()`\]
* \[`__Pool_init(registry, productNftId, name, poolInfo, authorization, initialOwner)`\]
* \[`_setPoolFees(poolFee, stakingFee, performanceFee)`\]
* \[`_setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`_fundPoolWallet(amount)`\]
* \[`_defundPoolWallet(amount)`\]
* \[`_createBundle(bundleOwner, fee, lifetime, filter)`\]
* \[`_setBundleFee(bundleNftId, fee)`\]
* \[`_stake(bundleNftId, amount)`\]
* \[`_unstake(bundleNftId, amount)`\]
* \[`_extend(bundleNftId, lifetimeExtension)`\]
* \[`_setBundleLocked(bundleNftId, locked)`\]
* \[`_closeBundle(bundleNftId)`\]
* \[`_withdrawBundleFees(bundleNftId, amount)`\]
* \[`_processFundedClaim(policyNftId, claimId, availableAmount)`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IPoolComponent
* \[`LogPoolVerifiedByPool(pool, applicationNftId, collateralizationAmount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BasicPool-_initializeBasicPool-address-NftId-string-struct-IComponents-PoolInfo-contract-IAuthorization-address-)
`_initializeBasicPool(address registry, NftId productNftId, string name, struct IComponents.PoolInfo poolInfo, contract IAuthorization authorization, address initialOwner)` internal
#### [](#BasicPool-stake-NftId-Amount-)
`stake(NftId bundleNftId, Amount amount)` public
#### [](#BasicPool-unstake-NftId-Amount-)
`unstake(NftId bundleNftId, Amount amount)` public
#### [](#BasicPool-extend-NftId-Seconds-)
`extend(NftId bundleNftId, Seconds lifetimeExtension) → Timestamp newExpiredAt` public
#### [](#BasicPool-setBundleLocked-NftId-bool-)
`setBundleLocked(NftId bundleNftId, bool locked)` public
#### [](#BasicPool-closeBundle-NftId-)
`closeBundle(NftId bundleNftId)` public
#### [](#BasicPool-setBundleFee-NftId-struct-Fee-)
`setBundleFee(NftId bundleNftId, struct Fee fee)` public
Updates the bundle feeds to the specified values.
#### [](#BasicPool-withdrawBundleFees-NftId-Amount-)
`withdrawBundleFees(NftId bundleNftId, Amount amount) → Amount withdrawnAmount` external
Withdraw bundle feeds for the given bundle.
#### [](#BasicPool-setMaxBalanceAmount-Amount-)
`setMaxBalanceAmount(Amount maxBalanceAmount)` public
#### [](#BasicPool-setFees-struct-Fee-struct-Fee-struct-Fee-)
`setFees(struct Fee poolFee, struct Fee stakingFee, struct Fee performanceFee)` public
### [](#BasicPoolAuthorization)
`BasicPoolAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/BasicPoolAuthorization.sol)
import "@etherisc/gif-next/contracts/pool/BasicPoolAuthorization.sol";
Functions
* \[`constructor(poolName)`\]
* \[`_setupServiceTargets()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
* \[`_setupTargetAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#BasicPoolAuthorization-constructor-string-)
`constructor(string poolName)` public
#### [](#BasicPoolAuthorization-_setupServiceTargets--)
`_setupServiceTargets()` internal
Sets up the relevant service targets for the component. Overwrite this function for use case specific authorizations.
#### [](#BasicPoolAuthorization-_setupTokenHandlerAuthorizations--)
`_setupTokenHandlerAuthorizations()` internal
Sets up the relevant component’s token handler authorizations. Overwrite this function for use case specific authorizations.
#### [](#BasicPoolAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#PoolService)
`PoolService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/PoolService.sol)
import "@etherisc/gif-next/contracts/pool/PoolService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`setMaxBalanceAmount(maxBalanceAmount)`\]
* \[`closeBundle(bundleNftId)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`stake(bundleNftId, amount)`\]
* \[`unstake(bundleNftId, amount)`\]
* \[`fundPoolWallet(amount)`\]
* \[`defundPoolWallet(amount)`\]
* \[`processSale(bundleNftId, premium)`\]
* \[`lockCollateral(instance, token, productNftId, applicationNftId, bundleNftId, sumInsuredAmount)`\]
* \[`processPayout(instanceReader, instanceStore, productNftId, policyNftId, bundleNftId, payoutId, payoutAmount, payoutBeneficiary)`\]
* \[`withdrawBundleFees(bundleNftId, amount)`\]
* \[`releaseCollateral(instance, policyNftId, policyInfo)`\]
* \[`_getAndVerifyActivePool()`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IPoolService
* \[`LogPoolServiceMaxBalanceAmountUpdated(poolNftId, previousMaxCapitalAmount, currentMaxCapitalAmount)`\]
* \[`LogPoolServiceWalletFunded(poolNftId, poolOwner, amount)`\]
* \[`LogPoolServiceWalletDefunded(poolNftId, poolOwner, amount)`\]
* \[`LogPoolServiceBundleCreated(instanceNftId, poolNftId, bundleNftId)`\]
* \[`LogPoolServiceBundleClosed(instanceNftId, poolNftId, bundleNftId, balanceAmount, feeAmount)`\]
* \[`LogPoolServiceBundleStaked(instanceNftId, poolNftId, bundleNftId, amount, netAmount)`\]
* \[`LogPoolServiceBundleUnstaked(instanceNftId, poolNftId, bundleNftId, amount, netAmount)`\]
* \[`LogPoolServiceFeesWithdrawn(bundleNftId, recipient, amount, tokenAddress)`\]
* \[`LogPoolServiceProcessFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`LogPoolServiceApplicationVerified(poolNftId, bundleNftId, applicationNftId, totalCollateralAmount)`\]
* \[`LogPoolServiceCollateralLocked(poolNftId, bundleNftId, applicationNftId, totalCollateralAmount, lockedCollateralAmount)`\]
* \[`LogPoolServiceCollateralReleased(bundleNftId, policyNftId, releasedCollateralAmount)`\]
* \[`LogPoolServiceSaleProcessed(poolNftId, bundleNftId, bundleNetAmount, bundleFeeAmount, poolFeeAmount)`\]
* \[`LogPoolServicePayoutProcessed(poolNftId, bundleNftId, policyNftId, payoutId, netPayoutAmount, processingFeeAmount, payoutBeneficiary)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#PoolService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#PoolService-setMaxBalanceAmount-Amount-)
`setMaxBalanceAmount(Amount maxBalanceAmount)` external
sets the max balance amount for the calling pool
#### [](#PoolService-closeBundle-NftId-)
`closeBundle(NftId bundleNftId)` external
closes the specified bundle only open bundles (active or locked) may be closed to close a bundle it may not have any non-closed polices attached to it bundle fees and remaining capital (after deduction of the performance fee) will be transferred to the bundle owner may only be called by registered and unlocked pool components
#### [](#PoolService-processFundedClaim-NftId-ClaimId-Amount-)
`processFundedClaim(NftId policyNftId, ClaimId claimId, Amount availableAmount)` external
Informs product about available funds to process a confirmed claim. The function triggers a callback to the product component when the product’s property isProcessingFundedClaims is set.
#### [](#PoolService-stake-NftId-Amount-)
`stake(NftId bundleNftId, Amount amount) → Amount netAmount` external
increase stakes for bundle staking fees will be deducted by the pool service from the staking amount may only be called by registered and unlocked pool components
#### [](#PoolService-unstake-NftId-Amount-)
`unstake(NftId bundleNftId, Amount amount) → Amount netAmount` external
decrease stakes for bundle performance fees will be deducted by the pool service from the staking amount may only be called by registered and unlocked pool components
#### [](#PoolService-fundPoolWallet-Amount-)
`fundPoolWallet(Amount amount)` external
Fund the pool wallet with the provided amount. This function will collect the amount from the pool owner and transfers it to the pool wallet. The function will not update balance amounts managed by the framework. Only available for externally managed pools.
#### [](#PoolService-defundPoolWallet-Amount-)
`defundPoolWallet(Amount amount)` external
Defund the specified pool wallet with the provided amount. This function will transfer the amount from the pool wallet to the pool owner. The function will not update balance amounts managed by the framework. Only available for externally managed pools.
#### [](#PoolService-processSale-NftId-struct-IPolicy-PremiumInfo-)
`processSale(NftId bundleNftId, struct IPolicy.PremiumInfo premium)` external
processes the sale of a bundle and track the pool fee and bundle fee amounts
#### [](#PoolService-lockCollateral-contract-IInstance-address-NftId-NftId-NftId-Amount-)
`lockCollateral(contract IInstance instance, address token, NftId productNftId, NftId applicationNftId, NftId bundleNftId, Amount sumInsuredAmount) → Amount totalCollateralAmount, Amount localCollateralAmount` external
locks required collateral to cover the specified application (and turn it into a policy) - retention level == 1: the full collateral amount will be locked by the specified bundle - retention level < 1: a part of the coverage is provided by the specified bundle, the rest by the pool component in which case the pool component might hold a re-insurance policy may only be called by the policy service for unlocked pool components
#### [](#PoolService-processPayout-contract-InstanceReader-contract-InstanceStore-NftId-NftId-NftId-PayoutId-Amount-address-)
`processPayout(contract InstanceReader instanceReader, contract InstanceStore instanceStore, NftId productNftId, NftId policyNftId, NftId bundleNftId, PayoutId payoutId, Amount payoutAmount, address payoutBeneficiary) → Amount netPayoutAmount, Amount processingFeeAmount` external
reduces the locked collateral in the bundle associated with the specified policy and updates pool/bundle counters every payout of a policy reduces the collateral by the payout amount may only be called by the claim service for unlocked pool components
#### [](#PoolService-withdrawBundleFees-NftId-Amount-)
`withdrawBundleFees(NftId bundleNftId, Amount amount) → Amount withdrawnAmount` public
Withdraw bundle feeds for the specified bundle.
#### [](#PoolService-releaseCollateral-contract-IInstance-NftId-struct-IPolicy-PolicyInfo-)
`releaseCollateral(contract IInstance instance, NftId policyNftId, struct IPolicy.PolicyInfo policyInfo)` external
releases the remaining collateral linked to the specified policy may only be called by the policy service for unlocked pool components
#### [](#PoolService-_getAndVerifyActivePool--)
`_getAndVerifyActivePool() → NftId poolNftId, contract IInstance instance` internal
#### [](#PoolService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#BundleService)
`BundleService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/BundleService.sol)
import "@etherisc/gif-next/contracts/pool/BundleService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`setFee(bundleNftId, fee)`\]
* \[`create(owner, bundleFee, lifetime, filter)`\]
* \[`lockCollateral(instance, policyNftId, bundleNftId, collateralAmount)`\]
* \[`setLocked(bundleNftId, locked)`\]
* \[`close(instance, bundleNftId)`\]
* \[`stake(instanceReader, instanceStore, bundleNftId, amount)`\]
* \[`unstake(instanceStore, bundleNftId, amount)`\]
* \[`extend(bundleNftId, lifetimeExtension)`\]
* \[`releaseCollateral(instanceStore, policyNftId, bundleNftId, collateralAmount)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IBundleService
* \[`LogBundleServiceBundleCreated(bundleNftId, poolNftId, lifetime, fixedFee, fractionalFee)`\]
* \[`LogBundleServiceBundleClosed(bundleNftId)`\]
* \[`LogBundleServiceBundleLocked(bundleNftId, locked)`\]
* \[`LogBundleServiceBundleExtended(bundleNftId, lifetimeExtension, extendedExpiredAt)`\]
* \[`LogBundleServiceBundleFeeUpdated(bundleNftId, fixedFee, fractionalFee)`\]
* \[`LogBundleServiceCollateralLocked(bundleNftId, policyNftId, collateralAmount)`\]
* \[`LogBundleServiceCollateralReleased(bundleNftId, policyNftId, collateralAmount)`\]
* \[`LogBundleServiceBundleStaked(bundleNftId, amount)`\]
* \[`LogBundleServiceBundleUnstaked(bundleNftId, amount)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BundleService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#BundleService-setFee-NftId-struct-Fee-)
`setFee(NftId bundleNftId, struct Fee fee)` external
set bundle fee to provided value may only be called by registered and unlocked pool components
#### [](#BundleService-create-address-struct-Fee-Seconds-bytes-)
`create(address owner, struct Fee bundleFee, Seconds lifetime, bytes filter) → NftId bundleNftId` external
#### [](#BundleService-lockCollateral-contract-IInstance-NftId-NftId-Amount-)
`lockCollateral(contract IInstance instance, NftId policyNftId, NftId bundleNftId, Amount collateralAmount)` external
locks the specified collateral in the bundle the locked collateral is added to the bundle locked capital the bundles' fees are updated with the fees for this premium the premium (minus bundle fee) is added to the bundle capital may only be called by pool service
#### [](#BundleService-setLocked-NftId-bool-)
`setLocked(NftId bundleNftId, bool locked)` external
locks/unlocks the specified bundle. locked bundles are not available to collateralize new policies. may only be called by registered and unlocked pool components.
#### [](#BundleService-close-contract-IInstance-NftId-)
`close(contract IInstance instance, NftId bundleNftId) → Amount unstakedAmount, Amount feeAmount` external
closes the specified bundle only open bundles (active or locked) may be closed to close a bundle it may not have any non-closed polices attached to it may only be called by registered and unlocked pool components
#### [](#BundleService-stake-contract-InstanceReader-contract-InstanceStore-NftId-Amount-)
`stake(contract InstanceReader instanceReader, contract InstanceStore instanceStore, NftId bundleNftId, Amount amount)` external
increase bundle stakes by the specified amount. bundle must not be expired or closed may only be called by the pool service
#### [](#BundleService-unstake-contract-InstanceStore-NftId-Amount-)
`unstake(contract InstanceStore instanceStore, NftId bundleNftId, Amount amount) → Amount unstakedAmount` external
decrease bundle stakes by the specified amount may only be called by the pool service
#### [](#BundleService-extend-NftId-Seconds-)
`extend(NftId bundleNftId, Seconds lifetimeExtension) → Timestamp extendedExpiredAt` external
extend the lifetime of the bundle by the specified time in seconds
#### [](#BundleService-releaseCollateral-contract-InstanceStore-NftId-NftId-Amount-)
`releaseCollateral(contract InstanceStore instanceStore, NftId policyNftId, NftId bundleNftId, Amount collateralAmount)` external
releases the specified collateral in the bundle may only be called by pool service
#### [](#BundleService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#PoolServiceManager)
`PoolServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/PoolServiceManager.sol)
import "@etherisc/gif-next/contracts/pool/PoolServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getPoolService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#PoolServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with pool service implementation
#### [](#PoolServiceManager-getPoolService--)
`getPoolService() → contract PoolService poolService` external
### [](#BundleServiceManager)
`BundleServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/pool/BundleServiceManager.sol)
import "@etherisc/gif-next/contracts/pool/BundleServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getBundleService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BundleServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with pool service implementation
#### [](#BundleServiceManager-getBundleService--)
`getBundleService() → contract BundleService` external
[← oracle](/gif-next/3.x/api/oracle)
[product →](/gif-next/3.x/api/product)
---
# Product - Etherisc Docs
Product
=======
Contains interfaces and contracts related to products.
[](#contracts)
Contracts
------------------------
### [](#IProductComponent)
`IProductComponent`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/IProductComponent.sol)
import "@etherisc/gif-next/contracts/product/IProductComponent.sol";
Functions
* \[`registerComponent(component)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`calculatePremium(sumInsuredAmount, riskId, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`calculateNetPremium(sumInsuredAmount, riskId, lifetime, applicationData)`\]
* \[`getInitialProductInfo()`\]
* \[`getInitialFeeInfo()`\]
IInstanceLinkedComponent
* \[`withdrawFees(amount)`\]
* \[`getInstance()`\]
IAuthorizedComponent
* \[`getAuthorization()`\]
IComponent
* \[`getName()`\]
* \[`getToken()`\]
* \[`getTokenHandler()`\]
* \[`getWallet()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
ITransferInterceptor
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IProductComponent-registerComponent-address-)
`registerComponent(address component) → NftId componentNftId` external
#### [](#IProductComponent-processFundedClaim-NftId-ClaimId-Amount-)
`processFundedClaim(NftId policyNftId, ClaimId claimId, Amount availableAmount)` external
Callback function to inform product compnent about arrival of funding for a claim. The callback is called by the pool service after the corresponding pool triggers this function. The callback is only called when the product’s property isProcessingFundedClaims is set.
#### [](#IProductComponent-calculatePremium-Amount-RiskId-Seconds-bytes-NftId-ReferralId-)
`calculatePremium(Amount sumInsuredAmount, RiskId riskId, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → Amount premiumAmount` external
Calculates the premium amount for the provided application data. The returned premium amounts takes into account potential discounts and fees.
#### [](#IProductComponent-calculateNetPremium-Amount-RiskId-Seconds-bytes-)
`calculateNetPremium(Amount sumInsuredAmount, RiskId riskId, Seconds lifetime, bytes applicationData) → Amount netPremiumAmount` external
Calculates the net premium amount for the provided application data. The returned net premium amounts only covers the cost of collateralizing the application. This amount purely depends on the use case specific risk and does not include any fees/commission.
#### [](#IProductComponent-getInitialProductInfo--)
`getInitialProductInfo() → struct IComponents.ProductInfo info` external
returns initial product specific infos
#### [](#IProductComponent-getInitialFeeInfo--)
`getInitialFeeInfo() → struct IComponents.FeeInfo info` external
returns initial fee infos
### [](#IApplicationService)
`IApplicationService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/IApplicationService.sol)
import "@etherisc/gif-next/contracts/product/IApplicationService.sol";
gif service responsible for creating applications only product components may call transaction functions
Functions
* \[`create(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`adjust(applicationNftId, riskId, bundleNftId, referralId, sumInsuredAmount, lifetime, applicationData)`\]
* \[`renew(policyNftId, bundleNftId)`\]
* \[`revoke(policyNftId)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogApplicationServiceApplicationCreated(applicationNftId, productNftId, bundleNftId, riskId, referralId, applicationOwner, sumInsuredAmount, premiumAmount, lifetime)`\]
* \[`LogApplicationServiceApplicationRenewed(policyNftId, bundleNftId)`\]
* \[`LogApplicationServiceApplicationAdjusted(applicationNftId, bundleNftId, riskId, referralId, sumInsuredAmount, lifetime)`\]
* \[`LogApplicationServiceApplicationRevoked(applicationNftId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IApplicationService-create-address-RiskId-Amount-Amount-Seconds-NftId-ReferralId-bytes-)
`create(address applicationOwner, RiskId riskId, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime, NftId bundleNftId, ReferralId referralId, bytes applicationData) → NftId applicationNftId` external
creates a new application based on the specified attributes may only be called by a product component
#### [](#IApplicationService-adjust-NftId-RiskId-NftId-ReferralId-Amount-Seconds-bytes-)
`adjust(NftId applicationNftId, RiskId riskId, NftId bundleNftId, ReferralId referralId, Amount sumInsuredAmount, Seconds lifetime, bytes applicationData)` external
updates application attributes may only be called while the application is in applied state may only be called by the referenced product related to applicationNftId
#### [](#IApplicationService-renew-NftId-NftId-)
`renew(NftId policyNftId, NftId bundleNftId) → NftId applicationNftId` external
creates a new application that extends the provided policy lifetime will seamlessly extend referenced policy, for closed policies lifetime will start at underwriting time product will need to limit the time window for renewal as underwriting will lock the collateral at underwriting time which might be earlier than activation time policyNftId needs to refer to an underwritten (or active or closed) policy may only be called by the referenced product related to policyNftId
#### [](#IApplicationService-revoke-NftId-)
`revoke(NftId policyNftId)` external
revokes the application represented by {policyNftId} an application can only be revoked in applied state only the application holder may revoke an application
#### [](#IApplicationService-LogApplicationServiceApplicationCreated-NftId-NftId-NftId-RiskId-ReferralId-address-Amount-Amount-Seconds-)
`LogApplicationServiceApplicationCreated(NftId indexed applicationNftId, NftId indexed productNftId, NftId indexed bundleNftId, RiskId riskId, ReferralId referralId, address applicationOwner, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime)` event
#### [](#IApplicationService-LogApplicationServiceApplicationRenewed-NftId-NftId-)
`LogApplicationServiceApplicationRenewed(NftId indexed policyNftId, NftId indexed bundleNftId)` event
#### [](#IApplicationService-LogApplicationServiceApplicationAdjusted-NftId-NftId-RiskId-ReferralId-Amount-Seconds-)
`LogApplicationServiceApplicationAdjusted(NftId indexed applicationNftId, NftId indexed bundleNftId, RiskId indexed riskId, ReferralId referralId, Amount sumInsuredAmount, Seconds lifetime)` event
#### [](#IApplicationService-LogApplicationServiceApplicationRevoked-NftId-)
`LogApplicationServiceApplicationRevoked(NftId indexed applicationNftId)` event
### [](#IPricingService)
`IPricingService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/IPricingService.sol)
import "@etherisc/gif-next/contracts/product/IPricingService.sol";
Functions
* \[`calculatePremium(productNftId, riskId, sumInsuredAmount, lifetime, applicationData, bundleNftId, referralId)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IPricingService-calculatePremium-NftId-RiskId-Amount-Seconds-bytes-NftId-ReferralId-)
`calculatePremium(NftId productNftId, RiskId riskId, Amount sumInsuredAmount, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → struct IPolicy.PremiumInfo premium` external
### [](#Product)
`Product`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/Product.sol)
import "@etherisc/gif-next/contracts/product/Product.sol";
Functions
* \[`registerComponent(component)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`calculatePremium(sumInsuredAmount, riskId, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`calculateNetPremium(sumInsuredAmount, , , )`\]
* \[`getInitialProductInfo()`\]
* \[`getInitialFeeInfo()`\]
* \[`__Product_init(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`_setFees(productFee, processingFee)`\]
* \[`_createRisk(id, data)`\]
* \[`_updateRisk(id, data)`\]
* \[`_setRiskLocked(id, locked)`\]
* \[`_closeRisk(id)`\]
* \[`_createApplication(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`_revoke(applicationNftId)`\]
* \[`_createPolicy(applicationNftId, activateAt, maxPremiumAmount)`\]
* \[`_decline(policyNftId)`\]
* \[`_expire(policyNftId, expireAt)`\]
* \[`_adjustActivation(policyNftId, activateAt)`\]
* \[`_collectPremium(policyNftId, activateAt)`\]
* \[`_activate(policyNftId, activateAt)`\]
* \[`_close(policyNftId)`\]
* \[`_submitClaim(policyNftId, claimAmount, claimData)`\]
* \[`_revokeClaim(policyNftId, claimId)`\]
* \[`_confirmClaim(policyNftId, claimId, confirmedAmount, data)`\]
* \[`_declineClaim(policyNftId, claimId, data)`\]
* \[`_cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`_createPayout(policyNftId, claimId, amount, data)`\]
* \[`_createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`_processPayout(policyNftId, payoutId)`\]
* \[`_cancelPayout(policyNftId, payoutId)`\]
* \[`_getProductStorage()`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Product-registerComponent-address-)
`registerComponent(address component) → NftId componentNftId` external
#### [](#Product-processFundedClaim-NftId-ClaimId-Amount-)
`processFundedClaim(NftId policyNftId, ClaimId claimId, Amount availableAmount)` external
Callback function to inform product compnent about arrival of funding for a claim. The callback is called by the pool service after the corresponding pool triggers this function. The callback is only called when the product’s property isProcessingFundedClaims is set.
#### [](#Product-calculatePremium-Amount-RiskId-Seconds-bytes-NftId-ReferralId-)
`calculatePremium(Amount sumInsuredAmount, RiskId riskId, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → Amount premiumAmount` public
Calculates the premium amount for the provided application data. The returned premium amounts takes into account potential discounts and fees.
#### [](#Product-calculateNetPremium-Amount-RiskId-Seconds-bytes-)
`calculateNetPremium(Amount sumInsuredAmount, RiskId, Seconds, bytes) → Amount netPremiumAmount` external
#### [](#Product-getInitialProductInfo--)
`getInitialProductInfo() → struct IComponents.ProductInfo poolInfo` public
returns initial product specific infos
#### [](#Product-getInitialFeeInfo--)
`getInitialFeeInfo() → struct IComponents.FeeInfo feeInfo` public
returns initial fee infos
#### [](#Product-__Product_init-address-NftId-string-struct-IComponents-ProductInfo-struct-IComponents-FeeInfo-contract-IAuthorization-address-)
`__Product_init(address registry, NftId instanceNftId, string name, struct IComponents.ProductInfo productInfo, struct IComponents.FeeInfo feeInfo, contract IAuthorization authorization, address initialOwner)` internal
#### [](#Product-_setFees-struct-Fee-struct-Fee-)
`_setFees(struct Fee productFee, struct Fee processingFee)` internal
#### [](#Product-_createRisk-bytes32-bytes-)
`_createRisk(bytes32 id, bytes data) → RiskId riskId` internal
#### [](#Product-_updateRisk-RiskId-bytes-)
`_updateRisk(RiskId id, bytes data)` internal
#### [](#Product-_setRiskLocked-RiskId-bool-)
`_setRiskLocked(RiskId id, bool locked)` internal
#### [](#Product-_closeRisk-RiskId-)
`_closeRisk(RiskId id)` internal
#### [](#Product-_createApplication-address-RiskId-Amount-Amount-Seconds-NftId-ReferralId-bytes-)
`_createApplication(address applicationOwner, RiskId riskId, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime, NftId bundleNftId, ReferralId referralId, bytes applicationData) → NftId applicationNftId` internal
#### [](#Product-_revoke-NftId-)
`_revoke(NftId applicationNftId)` internal
#### [](#Product-_createPolicy-NftId-Timestamp-Amount-)
`_createPolicy(NftId applicationNftId, Timestamp activateAt, Amount maxPremiumAmount) → Amount premiumAmount` internal
#### [](#Product-_decline-NftId-)
`_decline(NftId policyNftId)` internal
#### [](#Product-_expire-NftId-Timestamp-)
`_expire(NftId policyNftId, Timestamp expireAt) → Timestamp expiredAt` internal
#### [](#Product-_adjustActivation-NftId-Timestamp-)
`_adjustActivation(NftId policyNftId, Timestamp activateAt)` internal
adjust the activation date of the policy. The policy must already have an activation date set. Allowed values are from the current blocktime to the expiration date of the policy.
#### [](#Product-_collectPremium-NftId-Timestamp-)
`_collectPremium(NftId policyNftId, Timestamp activateAt)` internal
#### [](#Product-_activate-NftId-Timestamp-)
`_activate(NftId policyNftId, Timestamp activateAt)` internal
#### [](#Product-_close-NftId-)
`_close(NftId policyNftId)` internal
#### [](#Product-_submitClaim-NftId-Amount-bytes-)
`_submitClaim(NftId policyNftId, Amount claimAmount, bytes claimData) → ClaimId` internal
#### [](#Product-_revokeClaim-NftId-ClaimId-)
`_revokeClaim(NftId policyNftId, ClaimId claimId)` internal
#### [](#Product-_confirmClaim-NftId-ClaimId-Amount-bytes-)
`_confirmClaim(NftId policyNftId, ClaimId claimId, Amount confirmedAmount, bytes data)` internal
#### [](#Product-_declineClaim-NftId-ClaimId-bytes-)
`_declineClaim(NftId policyNftId, ClaimId claimId, bytes data)` internal
#### [](#Product-_cancelConfirmedClaim-NftId-ClaimId-)
`_cancelConfirmedClaim(NftId policyNftId, ClaimId claimId)` internal
#### [](#Product-_createPayout-NftId-ClaimId-Amount-bytes-)
`_createPayout(NftId policyNftId, ClaimId claimId, Amount amount, bytes data) → PayoutId` internal
#### [](#Product-_createPayoutForBeneficiary-NftId-ClaimId-Amount-address-bytes-)
`_createPayoutForBeneficiary(NftId policyNftId, ClaimId claimId, Amount amount, address beneficiary, bytes data) → PayoutId` internal
#### [](#Product-_processPayout-NftId-PayoutId-)
`_processPayout(NftId policyNftId, PayoutId payoutId) → Amount netPayoutAmount, Amount processingFeeAmount` internal
#### [](#Product-_cancelPayout-NftId-PayoutId-)
`_cancelPayout(NftId policyNftId, PayoutId payoutId)` internal
#### [](#Product-_getProductStorage--)
`_getProductStorage() → struct Product.ProductStorage $` internal
### [](#BasicProduct)
`BasicProduct`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/BasicProduct.sol)
import "@etherisc/gif-next/contracts/product/BasicProduct.sol";
Functions
* \[`setFees(productFee, processingFee)`\]
* \[`_initializeBasicProduct(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
Product
* \[`registerComponent(component)`\]
* \[`processFundedClaim(policyNftId, claimId, availableAmount)`\]
* \[`calculatePremium(sumInsuredAmount, riskId, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`calculateNetPremium(sumInsuredAmount, , , )`\]
* \[`getInitialProductInfo()`\]
* \[`getInitialFeeInfo()`\]
* \[`__Product_init(registry, instanceNftId, name, productInfo, feeInfo, authorization, initialOwner)`\]
* \[`_setFees(productFee, processingFee)`\]
* \[`_createRisk(id, data)`\]
* \[`_updateRisk(id, data)`\]
* \[`_setRiskLocked(id, locked)`\]
* \[`_closeRisk(id)`\]
* \[`_createApplication(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`_revoke(applicationNftId)`\]
* \[`_createPolicy(applicationNftId, activateAt, maxPremiumAmount)`\]
* \[`_decline(policyNftId)`\]
* \[`_expire(policyNftId, expireAt)`\]
* \[`_adjustActivation(policyNftId, activateAt)`\]
* \[`_collectPremium(policyNftId, activateAt)`\]
* \[`_activate(policyNftId, activateAt)`\]
* \[`_close(policyNftId)`\]
* \[`_submitClaim(policyNftId, claimAmount, claimData)`\]
* \[`_revokeClaim(policyNftId, claimId)`\]
* \[`_confirmClaim(policyNftId, claimId, confirmedAmount, data)`\]
* \[`_declineClaim(policyNftId, claimId, data)`\]
* \[`_cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`_createPayout(policyNftId, claimId, amount, data)`\]
* \[`_createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`_processPayout(policyNftId, payoutId)`\]
* \[`_cancelPayout(policyNftId, payoutId)`\]
* \[`_getProductStorage()`\]
InstanceLinkedComponent
* \[`getInstance()`\]
* \[`getAuthorization()`\]
* \[`withdrawFees(amount)`\]
* \[`_sendRequest(oracleNftId, requestData, expiryAt, callbackMethod)`\]
* \[`_cancelRequest(requestId)`\]
* \[`_resendResponse(requestId)`\]
* \[`__InstanceLinkedComponent_init(registry, parentNftId, name, componentType, authorization, isInterceptor, initialOwner)`\]
* \[`_checkAndGetInstanceNftId(registryAddress, parentNftId, componentType)`\]
* \[`_checkAndGetRegistry(registryAddress, objectNftId, requiredType)`\]
* \[`_setWallet(newWallet)`\]
* \[`_getComponentInfo()`\]
* \[`_getInstanceReader()`\]
* \[`_withdrawFees(amount)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getTokenHandler()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getVersion()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setLocked(locked)`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#BasicProduct-setFees-struct-Fee-struct-Fee-)
`setFees(struct Fee productFee, struct Fee processingFee)` external
#### [](#BasicProduct-_initializeBasicProduct-address-NftId-string-struct-IComponents-ProductInfo-struct-IComponents-FeeInfo-contract-IAuthorization-address-)
`_initializeBasicProduct(address registry, NftId instanceNftId, string name, struct IComponents.ProductInfo productInfo, struct IComponents.FeeInfo feeInfo, contract IAuthorization authorization, address initialOwner)` internal
### [](#BasicProductAuthorization)
`BasicProductAuthorization`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/BasicProductAuthorization.sol)
import "@etherisc/gif-next/contracts/product/BasicProductAuthorization.sol";
Functions
* \[`constructor(componentName)`\]
* \[`_setupServiceTargets()`\]
* \[`_setupTokenHandlerAuthorizations()`\]
* \[`_setupTargetAuthorizations()`\]
Authorization
* \[`getTokenHandlerName()`\]
* \[`getTokenHandlerTarget()`\]
* \[`getTarget(targetName)`\]
* \[`getTargets()`\]
* \[`targetExists(target)`\]
* \[`_setupTargets()`\]
* \[`_setupRoles()`\]
* \[`_addCustomRole(roleId, adminRoleId, maxMemberCount, name)`\]
* \[`_addGifTarget(contractName)`\]
* \[`_addInstanceTarget(contractName)`\]
* \[`_addTarget(name)`\]
* \[`_toTargetRoleId(targetDomain)`\]
* \[`_toTargetRoleName(targetName)`\]
ServiceAuthorization
* \[`getDomain()`\]
* \[`getRelease()`\]
* \[`getCommitHash()`\]
* \[`getMainTargetName()`\]
* \[`getMainTarget()`\]
* \[`getServiceDomains()`\]
* \[`getServiceDomain(idx)`\]
* \[`getServiceTarget(serviceDomain)`\]
* \[`getServiceRole(serviceDomain)`\]
* \[`getServiceAddress(serviceDomain)`\]
* \[`getTargetRole(target)`\]
* \[`roleExists(roleId)`\]
* \[`getRoles()`\]
* \[`getRoleInfo(roleId)`\]
* \[`getRoleName(roleId)`\]
* \[`getAuthorizedRoles(target)`\]
* \[`getAuthorizedFunctions(target, roleId)`\]
* \[`_setupDomains()`\]
* \[`_setupDomainAuthorizations()`\]
* \[`_authorizeServiceDomain(serviceDomain, serviceAddress)`\]
* \[`_addTargetWithRole(targetName, roleId, roleName)`\]
* \[`_addRole(roleId, info)`\]
* \[`_authorizeForService(serviceDomain, authorizedDomain)`\]
* \[`_authorizeForTarget(target, authorizedRoleId)`\]
* \[`_authorize(functions, selector, name)`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#BasicProductAuthorization-constructor-string-)
`constructor(string componentName)` public
#### [](#BasicProductAuthorization-_setupServiceTargets--)
`_setupServiceTargets()` internal
Sets up the relevant service targets for the component. Overwrite this function for use case specific authorizations.
#### [](#BasicProductAuthorization-_setupTokenHandlerAuthorizations--)
`_setupTokenHandlerAuthorizations()` internal
Sets up the relevant component’s token handler authorizations. Overwrite this function for use case specific authorizations.
#### [](#BasicProductAuthorization-_setupTargetAuthorizations--)
`_setupTargetAuthorizations()` internal
Sets up the relevant target authorizations for the component. Overwrite this function for use case specific authorizations.
### [](#ApplicationService)
`ApplicationService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/ApplicationService.sol)
import "@etherisc/gif-next/contracts/product/ApplicationService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`_checkLinkedApplicationParameters(instanceReader, productNftId, riskId, referralId, bundleNftId)`\]
* \[`_registerApplication(productNftId, applicationOwner)`\]
* \[`_calculatePremiumAmount(info)`\]
* \[`create(applicationOwner, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`_emitApplicationCreatedEvent(applicationNftId, applicationOwner, applicationInfo)`\]
* \[`_createApplicationInfo(productNftId, riskId, sumInsuredAmount, premiumAmount, lifetime, bundleNftId, referralId, applicationData)`\]
* \[`renew(policyNftId, bundleNftId)`\]
* \[`adjust(applicationNftId, riskId, bundleNftId, referralId, sumInsuredAmount, lifetime, applicationData)`\]
* \[`revoke(applicationNftId)`\]
* \[`_getAndVerifyActiveProduct()`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IApplicationService
* \[`LogApplicationServiceApplicationCreated(applicationNftId, productNftId, bundleNftId, riskId, referralId, applicationOwner, sumInsuredAmount, premiumAmount, lifetime)`\]
* \[`LogApplicationServiceApplicationRenewed(policyNftId, bundleNftId)`\]
* \[`LogApplicationServiceApplicationAdjusted(applicationNftId, bundleNftId, riskId, referralId, sumInsuredAmount, lifetime)`\]
* \[`LogApplicationServiceApplicationRevoked(applicationNftId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#ApplicationService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#ApplicationService-_checkLinkedApplicationParameters-contract-InstanceReader-NftId-RiskId-ReferralId-NftId-)
`_checkLinkedApplicationParameters(contract InstanceReader instanceReader, NftId productNftId, RiskId riskId, ReferralId referralId, NftId bundleNftId)` internal
#### [](#ApplicationService-_registerApplication-NftId-address-)
`_registerApplication(NftId productNftId, address applicationOwner) → NftId applicationNftId` internal
#### [](#ApplicationService-_calculatePremiumAmount-struct-IPolicy-PolicyInfo-)
`_calculatePremiumAmount(struct IPolicy.PolicyInfo info) → Amount premiumAmount` internal
#### [](#ApplicationService-create-address-RiskId-Amount-Amount-Seconds-NftId-ReferralId-bytes-)
`create(address applicationOwner, RiskId riskId, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime, NftId bundleNftId, ReferralId referralId, bytes applicationData) → NftId applicationNftId` external
creates a new application based on the specified attributes may only be called by a product component
#### [](#ApplicationService-_emitApplicationCreatedEvent-NftId-address-struct-IPolicy-PolicyInfo-)
`_emitApplicationCreatedEvent(NftId applicationNftId, address applicationOwner, struct IPolicy.PolicyInfo applicationInfo)` internal
#### [](#ApplicationService-_createApplicationInfo-NftId-RiskId-Amount-Amount-Seconds-NftId-ReferralId-bytes-)
`_createApplicationInfo(NftId productNftId, RiskId riskId, Amount sumInsuredAmount, Amount premiumAmount, Seconds lifetime, NftId bundleNftId, ReferralId referralId, bytes applicationData) → struct IPolicy.PolicyInfo applicationInfo` internal
#### [](#ApplicationService-renew-NftId-NftId-)
`renew(NftId policyNftId, NftId bundleNftId) → NftId applicationNftId` external
creates a new application that extends the provided policy lifetime will seamlessly extend referenced policy, for closed policies lifetime will start at underwriting time product will need to limit the time window for renewal as underwriting will lock the collateral at underwriting time which might be earlier than activation time policyNftId needs to refer to an underwritten (or active or closed) policy may only be called by the referenced product related to policyNftId
#### [](#ApplicationService-adjust-NftId-RiskId-NftId-ReferralId-Amount-Seconds-bytes-)
`adjust(NftId applicationNftId, RiskId riskId, NftId bundleNftId, ReferralId referralId, Amount sumInsuredAmount, Seconds lifetime, bytes applicationData)` external
updates application attributes may only be called while the application is in applied state may only be called by the referenced product related to applicationNftId
#### [](#ApplicationService-revoke-NftId-)
`revoke(NftId applicationNftId)` external
#### [](#ApplicationService-_getAndVerifyActiveProduct--)
`_getAndVerifyActiveProduct() → NftId productNftId, contract IInstance instance` internal
#### [](#ApplicationService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#PricingService)
`PricingService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/PricingService.sol)
import "@etherisc/gif-next/contracts/product/PricingService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`calculatePremium(productNftId, riskId, sumInsuredAmount, lifetime, applicationData, bundleNftId, referralId)`\]
* \[`_getFixedFeeAmounts(netPremiumAmount, feeInfo, bundleInfo)`\]
* \[`_calculateVariableFeeAmounts(premium, feeInfo, bundleInfo)`\]
* \[`_calculateDistributionOwnerFeeAmount(premium, feeInfo, distributionNftId, referralId, reader)`\]
* \[`_calculateTargetWalletAmounts(premium)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#PricingService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#PricingService-calculatePremium-NftId-RiskId-Amount-Seconds-bytes-NftId-ReferralId-)
`calculatePremium(NftId productNftId, RiskId riskId, Amount sumInsuredAmount, Seconds lifetime, bytes applicationData, NftId bundleNftId, ReferralId referralId) → struct IPolicy.PremiumInfo premium` external
calculates the premium amount for the specified attributes also returns the various fee components involved with creating a policy
#### [](#PricingService-_getFixedFeeAmounts-Amount-struct-IComponents-FeeInfo-struct-IBundle-BundleInfo-)
`_getFixedFeeAmounts(Amount netPremiumAmount, struct IComponents.FeeInfo feeInfo, struct IBundle.BundleInfo bundleInfo) → struct IPolicy.PremiumInfo premium` internal
#### [](#PricingService-_calculateVariableFeeAmounts-struct-IPolicy-PremiumInfo-struct-IComponents-FeeInfo-struct-IBundle-BundleInfo-)
`_calculateVariableFeeAmounts(struct IPolicy.PremiumInfo premium, struct IComponents.FeeInfo feeInfo, struct IBundle.BundleInfo bundleInfo) → struct IPolicy.PremiumInfo intermadiatePremium` internal
#### [](#PricingService-_calculateDistributionOwnerFeeAmount-struct-IPolicy-PremiumInfo-struct-IComponents-FeeInfo-NftId-ReferralId-contract-InstanceReader-)
`_calculateDistributionOwnerFeeAmount(struct IPolicy.PremiumInfo premium, struct IComponents.FeeInfo feeInfo, NftId distributionNftId, ReferralId referralId, contract InstanceReader reader) → struct IPolicy.PremiumInfo finalPremium` internal
#### [](#PricingService-_calculateTargetWalletAmounts-struct-IPolicy-PremiumInfo-)
`_calculateTargetWalletAmounts(struct IPolicy.PremiumInfo premium) → struct IPolicy.PremiumInfo premiumWithTargetWalletAmounts` internal
#### [](#PricingService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#ClaimService)
`ClaimService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/ClaimService.sol)
import "@etherisc/gif-next/contracts/product/ClaimService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`submit(policyNftId, claimAmount, claimData)`\]
* \[`confirm(policyNftId, claimId, confirmedAmount, data)`\]
* \[`decline(policyNftId, claimId, data)`\]
* \[`revoke(policyNftId, claimId)`\]
* \[`cancelConfirmedClaim(policyNftId, claimId)`\]
* \[`createPayoutForBeneficiary(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`createPayout(policyNftId, claimId, amount, data)`\]
* \[`processPayout(policyNftId, payoutId)`\]
* \[`cancelPayout(policyNftId, payoutId)`\]
* \[`_checkClaimAmount(policyNftId, policyInfo, claimAmount)`\]
* \[`_createPayout(policyNftId, claimId, amount, beneficiary, data)`\]
* \[`_verifyCallerWithPolicy(policyNftId)`\]
* \[`_getAndVerifyActiveProduct()`\]
* \[`_verifyClaim(instanceReader, policyNftId, claimId, expectedState)`\]
* \[`_processConfirmedClaimByPool(instanceReader, productNftId, policyNftId, claimId, amount)`\]
* \[`_policyHolderClaimConfirmed(policyNftId, claimId, confirmedAmount)`\]
* \[`_getPolicyHolder(policyNftId)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IClaimService
* \[`LogClaimServiceClaimSubmitted(policyNftId, claimId, claimAmount)`\]
* \[`LogClaimServiceClaimConfirmed(policyNftId, claimId, confirmedAmount)`\]
* \[`LogClaimServiceClaimDeclined(policyNftId, claimId)`\]
* \[`LogClaimServiceClaimRevoked(policyNftId, claimId)`\]
* \[`LogClaimServiceClaimCancelled(policyNftId, claimId)`\]
* \[`LogClaimServicePayoutCreated(policyNftId, claimId, payoutId, amount, beneficiary)`\]
* \[`LogClaimServicePayoutProcessed(policyNftId, payoutId, amount)`\]
* \[`LogClaimServicePayoutCancelled(policyNftId, payoutId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#ClaimService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#ClaimService-submit-NftId-Amount-bytes-)
`submit(NftId policyNftId, Amount claimAmount, bytes claimData) → ClaimId claimId` external
create a new claim for the specified policy returns the id of the newly created claim function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-confirm-NftId-ClaimId-Amount-bytes-)
`confirm(NftId policyNftId, ClaimId claimId, Amount confirmedAmount, bytes data)` external
confirms the specified claim and specifies the payout amount function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-decline-NftId-ClaimId-bytes-)
`decline(NftId policyNftId, ClaimId claimId, bytes data)` external
declines the specified claim function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-revoke-NftId-ClaimId-)
`revoke(NftId policyNftId, ClaimId claimId)` external
revokes the specified claim function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-cancelConfirmedClaim-NftId-ClaimId-)
`cancelConfirmedClaim(NftId policyNftId, ClaimId claimId)` external
cancels a confirmed claim before it has been fully paid out. Can only be called when there are not pending payouts function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-createPayoutForBeneficiary-NftId-ClaimId-Amount-address-bytes-)
`createPayoutForBeneficiary(NftId policyNftId, ClaimId claimId, Amount amount, address beneficiary, bytes data) → PayoutId payoutId` external
Creates a new payout for the specified claim and beneficiary. returns the id of the newly created payout, this id is unique for the specified policy function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-createPayout-NftId-ClaimId-Amount-bytes-)
`createPayout(NftId policyNftId, ClaimId claimId, Amount amount, bytes data) → PayoutId payoutId` external
Creates a new payout for the specified claim. The beneficiary is the holder of the policy NFT returns the id of the newly created payout, this id is unique for the specified policy function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-processPayout-NftId-PayoutId-)
`processPayout(NftId policyNftId, PayoutId payoutId) → Amount netPayoutAmount, Amount processingFeeAmount` external
processes the specified payout this includes moving the payout token to the beneficiary (default: policy holder) function can only be called by product, policy needs to match with calling product
#### [](#ClaimService-cancelPayout-NftId-PayoutId-)
`cancelPayout(NftId policyNftId, PayoutId payoutId)` external
cancels the specified payout. no tokens are moved, payout is set to cancelled.
#### [](#ClaimService-_checkClaimAmount-NftId-struct-IPolicy-PolicyInfo-Amount-)
`_checkClaimAmount(NftId policyNftId, struct IPolicy.PolicyInfo policyInfo, Amount claimAmount)` internal
#### [](#ClaimService-_createPayout-NftId-ClaimId-Amount-address-bytes-)
`_createPayout(NftId policyNftId, ClaimId claimId, Amount amount, address beneficiary, bytes data) → PayoutId payoutId` internal
#### [](#ClaimService-_verifyCallerWithPolicy-NftId-)
`_verifyCallerWithPolicy(NftId policyNftId) → NftId productNftId, contract IInstance instance, struct IInstance.InstanceContracts instanceContracts, struct IPolicy.PolicyInfo policyInfo` internal
Verifies the caller is a product and the policy is active. Returns the product nft id, instance, instance contracts and policy info. in InstanceContracts only the contracts instanceReader, instanceStore and productStore are set.
#### [](#ClaimService-_getAndVerifyActiveProduct--)
`_getAndVerifyActiveProduct() → NftId productNftId, contract IInstance instance` internal
#### [](#ClaimService-_verifyClaim-contract-InstanceReader-NftId-ClaimId-StateId-)
`_verifyClaim(contract InstanceReader instanceReader, NftId policyNftId, ClaimId claimId, StateId expectedState) → struct IPolicy.ClaimInfo claimInfo` internal
#### [](#ClaimService-_processConfirmedClaimByPool-contract-InstanceReader-NftId-NftId-ClaimId-Amount-)
`_processConfirmedClaimByPool(contract InstanceReader instanceReader, NftId productNftId, NftId policyNftId, ClaimId claimId, Amount amount)` internal
#### [](#ClaimService-_policyHolderClaimConfirmed-NftId-ClaimId-Amount-)
`_policyHolderClaimConfirmed(NftId policyNftId, ClaimId claimId, Amount confirmedAmount)` internal
#### [](#ClaimService-_getPolicyHolder-NftId-)
`_getPolicyHolder(NftId policyNftId) → contract IPolicyHolder policyHolder` internal
#### [](#ClaimService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#ApplicationServiceManager)
`ApplicationServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/ApplicationServiceManager.sol)
import "@etherisc/gif-next/contracts/product/ApplicationServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getApplicationService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#ApplicationServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with service implementation
#### [](#ApplicationServiceManager-getApplicationService--)
`getApplicationService() → contract ApplicationService` external
### [](#PricingServiceManager)
`PricingServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/PricingServiceManager.sol)
import "@etherisc/gif-next/contracts/product/PricingServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getPricingService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#PricingServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with pricing service implementation and deploys instance
#### [](#PricingServiceManager-getPricingService--)
`getPricingService() → contract PricingService` external
### [](#ClaimServiceManager)
`ClaimServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/product/ClaimServiceManager.sol)
import "@etherisc/gif-next/contracts/product/ClaimServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getClaimService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#ClaimServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with service implementation
#### [](#ClaimServiceManager-getClaimService--)
`getClaimService() → contract ClaimService` external
[← pool](/gif-next/3.x/api/pool)
[registry →](/gif-next/3.x/api/registry)
---
# Registry - Etherisc Docs
Registry
========
Contains interfaces and contracts related to the registry.
[](#contracts)
Contracts
------------------------
### [](#IRegistry)
`IRegistry`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/IRegistry.sol)
import "@etherisc/gif-next/contracts/registry/IRegistry.sol";
Functions
* \[`registerRegistry(nftId, chainId, chainRegistryAddress)`\]
* \[`registerService(serviceInfo, serviceVersion, serviceDomain)`\]
* \[`register(info)`\]
* \[`registerWithCustomType(info)`\]
* \[`getInitialRelease()`\]
* \[`getNextRelease()`\]
* \[`getLatestRelease()`\]
* \[`getReleaseInfo(release)`\]
* \[`chainIds()`\]
* \[`getChainId(idx)`\]
* \[`getRegistryNftId(chainId)`\]
* \[`getObjectCount()`\]
* \[`getNftIdForAddress(objectAddress)`\]
* \[`ownerOf(nftId)`\]
* \[`isOwnerOf(nftId, expectedOwner)`\]
* \[`ownerOf(contractAddress)`\]
* \[`getObjectInfo(nftId)`\]
* \[`getParentNftId(nftId)`\]
* \[`isObjectType(nftId, expectedObjectType)`\]
* \[`isObjectType(contractAddress, expectedObjectType)`\]
* \[`getObjectAddress(nftId)`\]
* \[`getObjectInfo(object)`\]
* \[`isRegistered(nftId)`\]
* \[`isRegistered(contractAddress)`\]
* \[`isRegisteredService(contractAddress)`\]
* \[`isRegisteredComponent(object)`\]
* \[`isActiveRelease(version)`\]
* \[`getServiceAddress(serviceDomain, releaseVersion)`\]
* \[`getProtocolNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`getChainNftAddress()`\]
* \[`getReleaseRegistryAddress()`\]
* \[`getStakingAddress()`\]
* \[`getTokenRegistryAddress()`\]
* \[`getRegistryAdminAddress()`\]
* \[`getAuthority()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
Events
* \[`LogRegistryObjectRegistered(nftId, parentNftId, objectType, isInterceptor, objectAddress, initialOwner)`\]
* \[`LogRegistryServiceRegistered(nftId, majorVersion, domain)`\]
* \[`LogRegistryChainRegistryRegistered(nftId, chainId, chainRegistryAddress)`\]
#### [](#IRegistry-registerRegistry-NftId-ChainId-address-)
`registerRegistry(NftId nftId, ChainId chainId, address chainRegistryAddress)` external
Registers a registry contract for a specified chain. Only one chain registry may be registered per chain
#### [](#IRegistry-registerService-struct-IRegistry-ObjectInfo-VersionPart-ObjectType-)
`registerService(struct IRegistry.ObjectInfo serviceInfo, VersionPart serviceVersion, ObjectType serviceDomain) → NftId nftId` external
Register a service with using the provided domain and version. The function returns a newly minted service NFT ID. May only be used to register services.
#### [](#IRegistry-register-struct-IRegistry-ObjectInfo-)
`register(struct IRegistry.ObjectInfo info) → NftId nftId` external
Register an object with a known core type. The function returns a newly minted object NFT ID. May not be used to register services.
#### [](#IRegistry-registerWithCustomType-struct-IRegistry-ObjectInfo-)
`registerWithCustomType(struct IRegistry.ObjectInfo info) → NftId nftId` external
Register an object with a custom type. The function returns a newly minted object NFT ID. This function is reserved for GIF releases > 3. May not be used to register known core types.
#### [](#IRegistry-getInitialRelease--)
`getInitialRelease() → VersionPart` external
#### [](#IRegistry-getNextRelease--)
`getNextRelease() → VersionPart` external
#### [](#IRegistry-getLatestRelease--)
`getLatestRelease() → VersionPart` external
#### [](#IRegistry-getReleaseInfo-VersionPart-)
`getReleaseInfo(VersionPart release) → struct IRelease.ReleaseInfo` external
#### [](#IRegistry-chainIds--)
`chainIds() → uint256` external
Returns the number of supported chains.
#### [](#IRegistry-getChainId-uint256-)
`getChainId(uint256 idx) → ChainId` external
Returns the chain id at the specified index.
#### [](#IRegistry-getRegistryNftId-ChainId-)
`getRegistryNftId(ChainId chainId) → NftId nftId` external
Returns the NFT ID of the registry for the specified chain.
#### [](#IRegistry-getObjectCount--)
`getObjectCount() → uint256` external
#### [](#IRegistry-getNftIdForAddress-address-)
`getNftIdForAddress(address objectAddress) → NftId nftId` external
#### [](#IRegistry-ownerOf-NftId-)
`ownerOf(NftId nftId) → address` external
#### [](#IRegistry-isOwnerOf-NftId-address-)
`isOwnerOf(NftId nftId, address expectedOwner) → bool` external
#### [](#IRegistry-ownerOf-address-)
`ownerOf(address contractAddress) → address` external
#### [](#IRegistry-getObjectInfo-NftId-)
`getObjectInfo(NftId nftId) → struct IRegistry.ObjectInfo info` external
#### [](#IRegistry-getParentNftId-NftId-)
`getParentNftId(NftId nftId) → NftId parentNftId` external
#### [](#IRegistry-isObjectType-NftId-ObjectType-)
`isObjectType(NftId nftId, ObjectType expectedObjectType) → bool` external
#### [](#IRegistry-isObjectType-address-ObjectType-)
`isObjectType(address contractAddress, ObjectType expectedObjectType) → bool` external
#### [](#IRegistry-getObjectAddress-NftId-)
`getObjectAddress(NftId nftId) → address objectAddress` external
#### [](#IRegistry-getObjectInfo-address-)
`getObjectInfo(address object) → struct IRegistry.ObjectInfo info` external
Returns the object info for the specified object address.
#### [](#IRegistry-isRegistered-NftId-)
`isRegistered(NftId nftId) → bool` external
#### [](#IRegistry-isRegistered-address-)
`isRegistered(address contractAddress) → bool` external
#### [](#IRegistry-isRegisteredService-address-)
`isRegisteredService(address contractAddress) → bool` external
#### [](#IRegistry-isRegisteredComponent-address-)
`isRegisteredComponent(address object) → bool` external
#### [](#IRegistry-isActiveRelease-VersionPart-)
`isActiveRelease(VersionPart version) → bool` external
#### [](#IRegistry-getServiceAddress-ObjectType-VersionPart-)
`getServiceAddress(ObjectType serviceDomain, VersionPart releaseVersion) → address serviceAddress` external
#### [](#IRegistry-getProtocolNftId--)
`getProtocolNftId() → NftId protocolNftId` external
#### [](#IRegistry-getNftId--)
`getNftId() → NftId nftId` external
#### [](#IRegistry-getOwner--)
`getOwner() → address` external
#### [](#IRegistry-getChainNftAddress--)
`getChainNftAddress() → address` external
#### [](#IRegistry-getReleaseRegistryAddress--)
`getReleaseRegistryAddress() → address` external
#### [](#IRegistry-getStakingAddress--)
`getStakingAddress() → address` external
#### [](#IRegistry-getTokenRegistryAddress--)
`getTokenRegistryAddress() → address` external
#### [](#IRegistry-getRegistryAdminAddress--)
`getRegistryAdminAddress() → address` external
#### [](#IRegistry-getAuthority--)
`getAuthority() → address` external
#### [](#IRegistry-LogRegistryObjectRegistered-NftId-NftId-ObjectType-bool-address-address-)
`LogRegistryObjectRegistered(NftId indexed nftId, NftId indexed parentNftId, ObjectType indexed objectType, bool isInterceptor, address objectAddress, address initialOwner)` event
#### [](#IRegistry-LogRegistryServiceRegistered-NftId-VersionPart-ObjectType-)
`LogRegistryServiceRegistered(NftId indexed nftId, VersionPart indexed majorVersion, ObjectType indexed domain)` event
#### [](#IRegistry-LogRegistryChainRegistryRegistered-NftId-ChainId-address-)
`LogRegistryChainRegistryRegistered(NftId indexed nftId, ChainId indexed chainId, address indexed chainRegistryAddress)` event
### [](#IRegistryService)
`IRegistryService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/IRegistryService.sol)
import "@etherisc/gif-next/contracts/registry/IRegistryService.sol";
Functions
* \[`registerStake(info)`\]
* \[`registerInstance(instance, owner)`\]
* \[`registerProduct(product, owner)`\]
* \[`registerProductLinkedComponent(component, objectType, owner)`\]
* \[`registerDistributor(info)`\]
* \[`registerPolicy(info)`\]
* \[`registerBundle(info)`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IRegistryService-registerStake-struct-IRegistry-ObjectInfo-)
`registerStake(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#IRegistryService-registerInstance-contract-IRegisterable-address-)
`registerInstance(contract IRegisterable instance, address owner) → struct IRegistry.ObjectInfo info` external
#### [](#IRegistryService-registerProduct-contract-IComponent-address-)
`registerProduct(contract IComponent product, address owner) → struct IRegistry.ObjectInfo info` external
#### [](#IRegistryService-registerProductLinkedComponent-contract-IComponent-ObjectType-address-)
`registerProductLinkedComponent(contract IComponent component, ObjectType objectType, address owner) → struct IRegistry.ObjectInfo info` external
#### [](#IRegistryService-registerDistributor-struct-IRegistry-ObjectInfo-)
`registerDistributor(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#IRegistryService-registerPolicy-struct-IRegistry-ObjectInfo-)
`registerPolicy(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#IRegistryService-registerBundle-struct-IRegistry-ObjectInfo-)
`registerBundle(struct IRegistry.ObjectInfo info) → NftId nftId` external
### [](#ITransferInterceptor)
`ITransferInterceptor`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/ITransferInterceptor.sol)
import "@etherisc/gif-next/contracts/registry/ITransferInterceptor.sol";
Functions
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
#### [](#ITransferInterceptor-nftTransferFrom-address-address-uint256-address-)
`nftTransferFrom(address from, address to, uint256 tokenId, address operator)` external
### [](#ChainNft)
`ChainNft`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/ChainNft.sol)
import "@etherisc/gif-next/contracts/registry/ChainNft.sol";
Modifiers
* [`onlyRegistry()`](#ChainNft-onlyRegistry--)
Functions
* \[`constructor(registry)`\]
* \[`mint(to, tokenId)`\]
* \[`mint(to, interceptor, uri)`\]
* \[`transferFrom(from, to, tokenId)`\]
* \[`burn(tokenId)`\]
* \[`setURI(tokenId, uri)`\]
* \[`exists(tokenId)`\]
* \[`tokenURI(tokenId)`\]
* \[`getInterceptor(tokenId)`\]
* \[`getRegistryAddress()`\]
* \[`totalMinted()`\]
* \[`calculateTokenId(idIndex, chainId)`\]
* \[`calculateTokenId(idIndex)`\]
* \[`getNextTokenId()`\]
ERC721Enumerable
* \[`supportsInterface(interfaceId)`\]
* \[`tokenOfOwnerByIndex(owner, index)`\]
* \[`totalSupply()`\]
* \[`tokenByIndex(index)`\]
* \[`_update(to, tokenId, auth)`\]
* \[`_increaseBalance(account, amount)`\]
ERC721
* \[`balanceOf(owner)`\]
* \[`ownerOf(tokenId)`\]
* \[`name()`\]
* \[`symbol()`\]
* \[`_baseURI()`\]
* \[`approve(to, tokenId)`\]
* \[`getApproved(tokenId)`\]
* \[`setApprovalForAll(operator, approved)`\]
* \[`isApprovedForAll(owner, operator)`\]
* \[`safeTransferFrom(from, to, tokenId)`\]
* \[`safeTransferFrom(from, to, tokenId, data)`\]
* \[`_ownerOf(tokenId)`\]
* \[`_getApproved(tokenId)`\]
* \[`_isAuthorized(owner, spender, tokenId)`\]
* \[`_checkAuthorized(owner, spender, tokenId)`\]
* \[`_mint(to, tokenId)`\]
* \[`_safeMint(to, tokenId)`\]
* \[`_safeMint(to, tokenId, data)`\]
* \[`_burn(tokenId)`\]
* \[`_transfer(from, to, tokenId)`\]
* \[`_safeTransfer(from, to, tokenId)`\]
* \[`_safeTransfer(from, to, tokenId, data)`\]
* \[`_approve(to, tokenId, auth)`\]
* \[`_approve(to, tokenId, auth, emitEvent)`\]
* \[`_setApprovalForAll(owner, operator, approved)`\]
* \[`_requireOwned(tokenId)`\]
Events
* \[`LogTokenInterceptorAddress(tokenId, interceptor)`\]
IERC721
* \[`Transfer(from, to, tokenId)`\]
* \[`Approval(owner, approved, tokenId)`\]
* \[`ApprovalForAll(owner, operator, approved)`\]
#### [](#ChainNft-onlyRegistry--)
`onlyRegistry()` modifier
#### [](#ChainNft-constructor-address-)
`constructor(address registry)` public
#### [](#ChainNft-mint-address-uint256-)
`mint(address to, uint256 tokenId)` external
mints a token for a specified token id not part of the IRegistry interface only needed for initial registry setup (protocol and global registry objects)
#### [](#ChainNft-mint-address-address-string-)
`mint(address to, address interceptor, string uri) → uint256 tokenId` public
mints the next token to register new objects non-zero transferInterceptors are recorded and called during nft token transfers. the contract receiving such a notification may decides to revert or record the transfer
#### [](#ChainNft-transferFrom-address-address-uint256-)
`transferFrom(address from, address to, uint256 tokenId)` public
Amend the open zeppelin transferFrom function by an interceptor call if such an interceptor is defined for the nft token id. This allows distribution, product and pool components to be notified when distributors, policies and bundles are transferred.
#### [](#ChainNft-burn-uint256-)
`burn(uint256 tokenId)` external
#### [](#ChainNft-setURI-uint256-string-)
`setURI(uint256 tokenId, string uri)` external
#### [](#ChainNft-exists-uint256-)
`exists(uint256 tokenId) → bool` external
#### [](#ChainNft-tokenURI-uint256-)
`tokenURI(uint256 tokenId) → string` public
See {IERC721Metadata-tokenURI}.
#### [](#ChainNft-getInterceptor-uint256-)
`getInterceptor(uint256 tokenId) → address` external
#### [](#ChainNft-getRegistryAddress--)
`getRegistryAddress() → address` external
#### [](#ChainNft-totalMinted--)
`totalMinted() → uint256` external
#### [](#ChainNft-calculateTokenId-uint256-ChainId-)
`calculateTokenId(uint256 idIndex, ChainId chainId) → uint256 id` public
token id calculation based on an index value that is supposed to increase with every minted token
requirement: each chain registry produces token ids that are guaranteed to not collide with any token id genereated on a different chain
format concat(counter,chainid,2 digits for len-of-chain-id) restriction chainid up to 99 digits decode: from right to left: - 2 right most digits encode length of chainid - move number of digits to left as determined above (→ chainid) - the reminder to the left is the counter
special cases 1101 → decentralized insurance protocol 2102 → global registry 2xxxxx → chain registry, where xxxxx =
examples 1101 ^^ ^ || - 1-digit chain id |-- chain id = 1 (mainnet) +-- 1st token id on mainnet (1 \* 10 **1 + 1) \* 100 + 1 42987654321010 ^ ^ ^ | | +- 10-digit chain id | +-- chain id = 9876543210 (hypothetical chainid) +-- 42nd token id on this chain (42 \* 10** 10 + 9876543210) \* 100 + 10 (index \* 10 \*\* digits + chainid) \* 100 + digits (1 < digits < 100)
#### [](#ChainNft-calculateTokenId-uint256-)
`calculateTokenId(uint256 idIndex) → uint256` public
#### [](#ChainNft-getNextTokenId--)
`getNextTokenId() → uint256` external
#### [](#ChainNft-LogTokenInterceptorAddress-uint256-address-)
`LogTokenInterceptorAddress(uint256 indexed tokenId, address indexed interceptor)` event
### [](#Registry)
`Registry`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/Registry.sol)
import "@etherisc/gif-next/contracts/registry/Registry.sol";
Chain Registry contract implementing IRegistry. IRegistry for method details.
Modifiers
* [`onlyDeployer()`](#Registry-onlyDeployer--)
Functions
* \[`constructor(admin, globalRegistry)`\]
* \[`initialize(releaseRegistry, tokenRegistry, staking)`\]
* \[`registerRegistry(nftId, chainId, registryAddress)`\]
* \[`registerService(info, version, domain)`\]
* \[`register(info)`\]
* \[`registerWithCustomType(info)`\]
* \[`getInitialRelease()`\]
* \[`getNextRelease()`\]
* \[`getLatestRelease()`\]
* \[`getReleaseInfo(release)`\]
* \[`chainIds()`\]
* \[`getChainId(idx)`\]
* \[`getRegistryNftId(chainId)`\]
* \[`getObjectCount()`\]
* \[`getNftId()`\]
* \[`getProtocolNftId()`\]
* \[`getNftIdForAddress(object)`\]
* \[`ownerOf(nftId)`\]
* \[`isOwnerOf(nftId, expectedOwner)`\]
* \[`ownerOf(contractAddress)`\]
* \[`getObjectInfo(nftId)`\]
* \[`getParentNftId(nftId)`\]
* \[`isObjectType(contractAddress, expectedObjectType)`\]
* \[`isObjectType(nftId, expectedObjectType)`\]
* \[`getObjectAddress(nftId)`\]
* \[`getObjectInfo(object)`\]
* \[`isRegistered(nftId)`\]
* \[`isRegistered(object)`\]
* \[`isRegisteredService(object)`\]
* \[`isRegisteredComponent(object)`\]
* \[`isActiveRelease(version)`\]
* \[`getStakingAddress()`\]
* \[`getTokenRegistryAddress()`\]
* \[`getServiceAddress(serviceDomain, releaseVersion)`\]
* \[`getReleaseRegistryAddress()`\]
* \[`getChainNftAddress()`\]
* \[`getRegistryAdminAddress()`\]
* \[`getAuthority()`\]
* \[`getOwner()`\]
* \[`supportsInterface(interfaceId)`\]
* \[`_register(info)`\]
* \[`_getInterceptor(isInterceptor, objectType, objectAddress, parentIsInterceptor, parentObjectAddress)`\]
* \[`_registerRegistry()`\]
* \[`_registerForNft(info, updateAddressLookup)`\]
* \[`_setAddressForNftId(nftId, objectAddress)`\]
* \[`_getGlobalRegistryAddress(globalRegistry)`\]
AccessManaged
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IRegistry
* \[`LogRegistryObjectRegistered(nftId, parentNftId, objectType, isInterceptor, objectAddress, initialOwner)`\]
* \[`LogRegistryServiceRegistered(nftId, majorVersion, domain)`\]
* \[`LogRegistryChainRegistryRegistered(nftId, chainId, chainRegistryAddress)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Registry-onlyDeployer--)
`onlyDeployer()` modifier
#### [](#Registry-constructor-contract-RegistryAdmin-address-)
`constructor(contract RegistryAdmin admin, address globalRegistry)` public
Creates the registry contract and populates it with the protocol and registry objects. Internally deploys the ChainNft contract.
#### [](#Registry-initialize-address-address-address-)
`initialize(address releaseRegistry, address tokenRegistry, address staking)` external
Wires release registry, token registry and staking contract to this registry. MUST be called by release registry.
#### [](#Registry-registerRegistry-NftId-ChainId-address-)
`registerRegistry(NftId nftId, ChainId chainId, address registryAddress)` external
Registers a registry contract for a specified chain. Only one chain registry may be registered per chain
#### [](#Registry-registerService-struct-IRegistry-ObjectInfo-VersionPart-ObjectType-)
`registerService(struct IRegistry.ObjectInfo info, VersionPart version, ObjectType domain) → NftId nftId` external
Register a service with using the provided domain and version. The function returns a newly minted service NFT ID. May only be used to register services.
#### [](#Registry-register-struct-IRegistry-ObjectInfo-)
`register(struct IRegistry.ObjectInfo info) → NftId nftId` external
Register an object with a known core type. The function returns a newly minted object NFT ID. May not be used to register services.
#### [](#Registry-registerWithCustomType-struct-IRegistry-ObjectInfo-)
`registerWithCustomType(struct IRegistry.ObjectInfo info) → NftId nftId` external
Register an object with a custom type. The function returns a newly minted object NFT ID. This function is reserved for GIF releases > 3. May not be used to register known core types.
#### [](#Registry-getInitialRelease--)
`getInitialRelease() → VersionPart` external
earliest GIF major version
#### [](#Registry-getNextRelease--)
`getNextRelease() → VersionPart` external
next GIF release version to be released
#### [](#Registry-getLatestRelease--)
`getLatestRelease() → VersionPart` external
latest active GIF release version
#### [](#Registry-getReleaseInfo-VersionPart-)
`getReleaseInfo(VersionPart release) → struct IRelease.ReleaseInfo` external
#### [](#Registry-chainIds--)
`chainIds() → uint256` public
Returns the number of supported chains.
#### [](#Registry-getChainId-uint256-)
`getChainId(uint256 idx) → ChainId` public
Returns the chain id at the specified index.
#### [](#Registry-getRegistryNftId-ChainId-)
`getRegistryNftId(ChainId chainId) → NftId nftId` public
Returns the NFT ID of the registry for the specified chain.
#### [](#Registry-getObjectCount--)
`getObjectCount() → uint256` external
#### [](#Registry-getNftId--)
`getNftId() → NftId nftId` external
#### [](#Registry-getProtocolNftId--)
`getProtocolNftId() → NftId nftId` external
#### [](#Registry-getNftIdForAddress-address-)
`getNftIdForAddress(address object) → NftId id` external
#### [](#Registry-ownerOf-NftId-)
`ownerOf(NftId nftId) → address` public
#### [](#Registry-isOwnerOf-NftId-address-)
`isOwnerOf(NftId nftId, address expectedOwner) → bool` public
#### [](#Registry-ownerOf-address-)
`ownerOf(address contractAddress) → address` public
#### [](#Registry-getObjectInfo-NftId-)
`getObjectInfo(NftId nftId) → struct IRegistry.ObjectInfo` external
#### [](#Registry-getParentNftId-NftId-)
`getParentNftId(NftId nftId) → NftId parentNftId` external
#### [](#Registry-isObjectType-address-ObjectType-)
`isObjectType(address contractAddress, ObjectType expectedObjectType) → bool` external
#### [](#Registry-isObjectType-NftId-ObjectType-)
`isObjectType(NftId nftId, ObjectType expectedObjectType) → bool` public
#### [](#Registry-getObjectAddress-NftId-)
`getObjectAddress(NftId nftId) → address` external
#### [](#Registry-getObjectInfo-address-)
`getObjectInfo(address object) → struct IRegistry.ObjectInfo` external
Returns the object info for the specified object address.
#### [](#Registry-isRegistered-NftId-)
`isRegistered(NftId nftId) → bool` public
#### [](#Registry-isRegistered-address-)
`isRegistered(address object) → bool` external
#### [](#Registry-isRegisteredService-address-)
`isRegisteredService(address object) → bool` external
#### [](#Registry-isRegisteredComponent-address-)
`isRegisteredComponent(address object) → bool` external
#### [](#Registry-isActiveRelease-VersionPart-)
`isActiveRelease(VersionPart version) → bool` external
#### [](#Registry-getStakingAddress--)
`getStakingAddress() → address staking` external
#### [](#Registry-getTokenRegistryAddress--)
`getTokenRegistryAddress() → address tokenRegistry` external
#### [](#Registry-getServiceAddress-ObjectType-VersionPart-)
`getServiceAddress(ObjectType serviceDomain, VersionPart releaseVersion) → address service` external
#### [](#Registry-getReleaseRegistryAddress--)
`getReleaseRegistryAddress() → address` external
#### [](#Registry-getChainNftAddress--)
`getChainNftAddress() → address` external
#### [](#Registry-getRegistryAdminAddress--)
`getRegistryAdminAddress() → address` external
#### [](#Registry-getAuthority--)
`getAuthority() → address` external
#### [](#Registry-getOwner--)
`getOwner() → address owner` public
#### [](#Registry-supportsInterface-bytes4-)
`supportsInterface(bytes4 interfaceId) → bool` external
Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding [ERC section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
to learn more about how these ids are created.
This function call must use less than 30 000 gas.
#### [](#Registry-_register-struct-IRegistry-ObjectInfo-)
`_register(struct IRegistry.ObjectInfo info) → NftId nftId` internal
registry protects only against tampering existing records, registering with invalid types pairs and 0 parent address
#### [](#Registry-_getInterceptor-bool-ObjectType-address-bool-address-)
`_getInterceptor(bool isInterceptor, ObjectType objectType, address objectAddress, bool parentIsInterceptor, address parentObjectAddress) → address interceptor` internal
obtain interceptor address for this nft if applicable, address(0) otherwise special case: STAKES (parent may be any type) → no intercept call default case:
#### [](#Registry-_registerRegistry--)
`_registerRegistry() → NftId registryNftId` internal
register this registry
#### [](#Registry-_registerForNft-struct-IRegistry-ObjectInfo-bool-)
`_registerForNft(struct IRegistry.ObjectInfo info, bool updateAddressLookup)` internal
Register the provided object info for the specified NFT ID.
#### [](#Registry-_setAddressForNftId-NftId-address-)
`_setAddressForNftId(NftId nftId, address objectAddress)` internal
#### [](#Registry-_getGlobalRegistryAddress-address-)
`_getGlobalRegistryAddress(address globalRegistry) → address` internal
### [](#RegistryAdmin)
`RegistryAdmin`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/RegistryAdmin.sol)
import "@etherisc/gif-next/contracts/registry/RegistryAdmin.sol";
The RegistryAdmin contract implements the central authorization for the GIF core contracts. These are the release independent registry and staking contracts and their respective helper contracts. The RegistryAdmin also manages the access from service contracts to the GIF core contracts
Functions
* \[`constructor()`\]
* \[`completeSetup(registry, authorization, release, gifAdmin, gifManager)`\]
* \[`grantServiceRoleForAllVersions(service, domain)`\]
* \[`getGifAdminRole()`\]
* \[`getGifManagerRole()`\]
* \[`_createCoreTargets(registryTargetName)`\]
* \[`_createTargetAuthorizations(authorization)`\]
AccessAdmin
* \[`initialize(authority, adminName)`\]
* \[`__AccessAdmin_init(authority, adminName)`\]
* \[`getRelease()`\]
* \[`getRegistry()`\]
* \[`getLinkedNftId()`\]
* \[`getAuthorization()`\]
* \[`isLocked()`\]
* \[`roles()`\]
* \[`getRoleId(idx)`\]
* \[`getAdminRole()`\]
* \[`getPublicRole()`\]
* \[`roleExists(roleId)`\]
* \[`getRoleForName(name)`\]
* \[`getRoleInfo(roleId)`\]
* \[`isRoleActive(roleId)`\]
* \[`isRoleCustom(roleId)`\]
* \[`roleMembers(roleId)`\]
* \[`getRoleMember(roleId, idx)`\]
* \[`isRoleMember(roleId, account)`\]
* \[`isRoleAdmin(roleId, account)`\]
* \[`targetExists(target)`\]
* \[`targets()`\]
* \[`getTargetAddress(idx)`\]
* \[`getTargetInfo(target)`\]
* \[`getTargetForName(name)`\]
* \[`isTargetLocked(target)`\]
* \[`authorizedFunctions(target)`\]
* \[`getAuthorizedFunction(target, idx)`\]
* \[`getFunctionInfo(target, selector)`\]
* \[`_linkToNftOwnable(registerable)`\]
* \[`_createRoles(authorization)`\]
* \[`_createRole(roleId, info, revertOnExistingRole)`\]
* \[`_setRoleActive(roleId, active)`\]
* \[`_grantRoleToAccount(roleId, account)`\]
* \[`_revokeRoleFromAccount(roleId, account)`\]
* \[`_getOrCreateTargetRoleIdAndName(target, targetName, targetType)`\]
* \[`_createTarget(target, targetName, targetType, checkAuthority)`\]
* \[`_createTargetUnchecked(target, targetName, targetType, managed)`\]
* \[`_setTargetLocked(target, locked)`\]
* \[`_authorizeFunctions(authorization, target, roleId)`\]
* \[`_authorizeTargetFunctions(target, roleId, functions, onlyComponentOrContractTargets, addFunctions)`\]
* \[`_updateFunctionAccess(target, roleId, func, addFunction)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IAccessAdmin
* \[`LogAccessAdminRoleCreated(roleId, roleAdminId, targetType, name, admin)`\]
* \[`LogAccessAdminTargetCreated(target, roleId, managed, name, admin)`\]
* \[`LogAccessAdminRoleActivatedSet(roleId, active, admin, lastUpdateIn)`\]
* \[`LogAccessAdminRoleGranted(account, roleName, admin)`\]
* \[`LogAccessAdminRoleRevoked(account, roleName, admin)`\]
* \[`LogAccessAdminTargetLockedSet(target, locked, admin, lastUpdateIn)`\]
* \[`LogAccessAdminFunctionGranted(target, selector, roleId, func, admin, lastUpdateIn)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#RegistryAdmin-constructor--)
`constructor()` public
#### [](#RegistryAdmin-completeSetup-address-address-VersionPart-address-address-)
`completeSetup(address registry, address authorization, VersionPart release, address gifAdmin, address gifManager)` public
#### [](#RegistryAdmin-grantServiceRoleForAllVersions-contract-IService-ObjectType-)
`grantServiceRoleForAllVersions(contract IService service, ObjectType domain)` external
#### [](#RegistryAdmin-getGifAdminRole--)
`getGifAdminRole() → RoleId` external
#### [](#RegistryAdmin-getGifManagerRole--)
`getGifManagerRole() → RoleId` external
#### [](#RegistryAdmin-_createCoreTargets-string-)
`_createCoreTargets(string registryTargetName)` internal
#### [](#RegistryAdmin-_createTargetAuthorizations-contract-IAuthorization-)
`_createTargetAuthorizations(contract IAuthorization authorization)` internal
### [](#ReleaseRegistry)
`ReleaseRegistry`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/ReleaseRegistry.sol)
import "@etherisc/gif-next/contracts/registry/ReleaseRegistry.sol";
The ReleaseRegistry manages the lifecycle of major GIF releases and their services. The creation of a new GIF release is a multi-step process: 1. The creation of a new GIF release is initiated by the GIF admin. 2. A GIF manager then prepares the release by setting up the service authorization contract. 3. The GIF manager deploys and registers all related service contracts with the release registry. 4. The GIF admin verifies and activates the release. 3. The GIF admin may pause and resume a release.
Functions
* \[`constructor(registry)`\]
* \[`createNextRelease()`\]
* \[`prepareNextRelease(serviceAuthorization, salt)`\]
* \[`registerService(service)`\]
* \[`activateNextRelease()`\]
* \[`setActive(release, active)`\]
* \[`predictDeterministicAddress(implementation, salt, deployer)`\]
* \[`isActiveRelease(release)`\]
* \[`getReleaseInfo(release)`\]
* \[`releases()`\]
* \[`getVersion(idx)`\]
* \[`getNextVersion()`\]
* \[`getLatestVersion()`\]
* \[`getState(release)`\]
* \[`getRemainingServicesToRegister()`\]
* \[`getServiceAuthorization(release)`\]
* \[`getRegistryAdmin()`\]
* \[`getRegistry()`\]
* \[`_verifyService(service, expectedAuthority, expectedVersion, expectedDomain)`\]
* \[`_verifyServiceInfo(service, info, expectedOwner)`\]
ReleaseLifecycle
* \[`_setupLifecycle()`\]
Lifecycle
* \[`setInitialState(ttype, state)`\]
* \[`setStateTransition(ttype, oldState, newState)`\]
* \[`hasLifecycle(objectType)`\]
* \[`getInitialState(objectType)`\]
* \[`checkTransition(stateId, objectType, expectedFromId, toId)`\]
* \[`isValidTransition(objectType, fromId, toId)`\]
AccessManaged
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
Events
* \[`LogReleaseCreated(releaseAdmin, release, salt)`\]
* \[`LogReleaseActivated(release)`\]
* \[`LogReleaseEnabled(release, active)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#ReleaseRegistry-constructor-contract-Registry-)
`constructor(contract Registry registry)` public
#### [](#ReleaseRegistry-createNextRelease--)
`createNextRelease() → VersionPart` external
Initiates the creation of a new GIF release by the GIF admin. Sets previous release into SKIPPED state if it was created but not activated. Sets the new release into state SCHEDULED.
#### [](#ReleaseRegistry-prepareNextRelease-contract-IServiceAuthorization-bytes32-)
`prepareNextRelease(contract IServiceAuthorization serviceAuthorization, bytes32 salt) → contract ReleaseAdmin releaseAdmin, VersionPart releaseVersion, bytes32 releaseSalt` external
#### [](#ReleaseRegistry-registerService-contract-IService-)
`registerService(contract IService service) → NftId nftId` external
#### [](#ReleaseRegistry-activateNextRelease--)
`activateNextRelease()` external
#### [](#ReleaseRegistry-setActive-VersionPart-bool-)
`setActive(VersionPart release, bool active)` public
stop/resume operations with restricted functions
#### [](#ReleaseRegistry-predictDeterministicAddress-address-bytes32-address-)
`predictDeterministicAddress(address implementation, bytes32 salt, address deployer) → address predicted` external
#### [](#ReleaseRegistry-isActiveRelease-VersionPart-)
`isActiveRelease(VersionPart release) → bool` public
#### [](#ReleaseRegistry-getReleaseInfo-VersionPart-)
`getReleaseInfo(VersionPart release) → struct IRelease.ReleaseInfo` external
#### [](#ReleaseRegistry-releases--)
`releases() → uint256` external
Returns the number of created releases. Releases might be in another state than ACTIVE.
#### [](#ReleaseRegistry-getVersion-uint256-)
`getVersion(uint256 idx) → VersionPart release` external
Returns the n-th release version. Valid values for idx \[0 .. releases() - 1\]
#### [](#ReleaseRegistry-getNextVersion--)
`getNextVersion() → VersionPart` public
#### [](#ReleaseRegistry-getLatestVersion--)
`getLatestVersion() → VersionPart` external
Returns the latest activated relase version. There is no guarantee that the release is not currently paused.
#### [](#ReleaseRegistry-getState-VersionPart-)
`getState(VersionPart release) → StateId stateId` external
#### [](#ReleaseRegistry-getRemainingServicesToRegister--)
`getRemainingServicesToRegister() → uint256 services` external
#### [](#ReleaseRegistry-getServiceAuthorization-VersionPart-)
`getServiceAuthorization(VersionPart release) → contract IServiceAuthorization serviceAuthorization` external
#### [](#ReleaseRegistry-getRegistryAdmin--)
`getRegistryAdmin() → address` external
#### [](#ReleaseRegistry-getRegistry--)
`getRegistry() → contract IRegistry` external
#### [](#ReleaseRegistry-_verifyService-contract-IService-address-VersionPart-ObjectType-)
`_verifyService(contract IService service, address expectedAuthority, VersionPart expectedVersion, ObjectType expectedDomain) → struct IRegistry.ObjectInfo serviceInfo, ObjectType serviceDomain, VersionPart serviceVersion` internal
#### [](#ReleaseRegistry-_verifyServiceInfo-contract-IService-struct-IRegistry-ObjectInfo-address-)
`_verifyServiceInfo(contract IService service, struct IRegistry.ObjectInfo info, address expectedOwner)` internal
#### [](#ReleaseRegistry-LogReleaseCreated-address-VersionPart-bytes32-)
`LogReleaseCreated(address indexed releaseAdmin, VersionPart indexed release, bytes32 indexed salt)` event
#### [](#ReleaseRegistry-LogReleaseActivated-VersionPart-)
`LogReleaseActivated(VersionPart indexed release)` event
#### [](#ReleaseRegistry-LogReleaseEnabled-VersionPart-bool-)
`LogReleaseEnabled(VersionPart indexed release, bool indexed active)` event
### [](#TokenRegistry)
`TokenRegistry`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/TokenRegistry.sol)
import "@etherisc/gif-next/contracts/registry/TokenRegistry.sol";
The TokenRegistry contract is used to whitelist/manage ERC-20 of tokens per major release. Only whitelisted tokens can be used as default tokens for products, distribution and pools components.
Modifiers
* [`onlyRegisteredToken(chainId, token)`](#TokenRegistry-onlyRegisteredToken-ChainId-address-)
Functions
* \[`constructor(registry, dipToken)`\]
* \[`registerToken(tokenAddress)`\]
* \[`registerRemoteToken(chainId, token, decimals, symbol)`\]
* \[`setActive(chainId, token, active)`\]
* \[`setActiveForVersion(chainId, token, release, active)`\]
* \[`setActiveWithVersionCheck(chainId, token, release, active, enforceVersionCheck)`\]
* \[`_setActiveWithVersionCheck(chainId, token, release, active, enforceVersionCheck)`\]
* \[`getDipToken()`\]
* \[`tokens()`\]
* \[`getTokenInfo(idx)`\]
* \[`getTokenInfo(chainId, token)`\]
* \[`isRegistered(chainId, token)`\]
* \[`isActive(chainId, token, release)`\]
* \[`getDipTokenAddress()`\]
* \[`getRegistry()`\]
* \[`_verifyOnchainToken(tokenAddress)`\]
* \[`_implementsErc20Functions(token)`\]
* \[`_registerToken(chainId, token, decimals, symbol)`\]
AccessManaged
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
Events
* \[`LogTokenRegistryTokenRegistered(chainId, token, decimals, symbol)`\]
* \[`LogTokenRegistryTokenGlobalStateSet(chainId, token, active)`\]
* \[`LogTokenRegistryTokenStateSet(chainId, token, release, active)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#TokenRegistry-onlyRegisteredToken-ChainId-address-)
`onlyRegisteredToken(ChainId chainId, address token)` modifier
enforces msg.sender is owner of nft (or initial owner of nft ownable)
#### [](#TokenRegistry-constructor-contract-IRegistry-contract-IERC20Metadata-)
`constructor(contract IRegistry registry, contract IERC20Metadata dipToken)` public
#### [](#TokenRegistry-registerToken-address-)
`registerToken(address tokenAddress)` external
register an onchain token. this function verifies that the provided token address is a contract that implements the non optional erc20 view functions.
#### [](#TokenRegistry-registerRemoteToken-ChainId-address-uint8-string-)
`registerRemoteToken(ChainId chainId, address token, uint8 decimals, string symbol)` external
register the remote token with the provided attributes. this function may not be used for tokens when chainId == block.chainid.
#### [](#TokenRegistry-setActive-ChainId-address-bool-)
`setActive(ChainId chainId, address token, bool active)` external
set active flag on token itself. when setting a token to active=false isActive will return false regardless of release specific active value.
#### [](#TokenRegistry-setActiveForVersion-ChainId-address-VersionPart-bool-)
`setActiveForVersion(ChainId chainId, address token, VersionPart release, bool active)` external
sets active state for specified token and release (major version). internally calls setActiveWithVersionCheck() with enforcing version check. token state is informative, registry have no clue about used tokens component owner is responsible for token selection and operations service MUST deny registration of component with inactive token.
#### [](#TokenRegistry-setActiveWithVersionCheck-ChainId-address-VersionPart-bool-bool-)
`setActiveWithVersionCheck(ChainId chainId, address token, VersionPart release, bool active, bool enforceVersionCheck)` external
as setActiveForVersion() with the option to skip the version check. enforcing the version check checks if the provided major version with the release manager. the function reverts if the provided release is unknown to the release manager.
#### [](#TokenRegistry-_setActiveWithVersionCheck-ChainId-address-VersionPart-bool-bool-)
`_setActiveWithVersionCheck(ChainId chainId, address token, VersionPart release, bool active, bool enforceVersionCheck)` internal
#### [](#TokenRegistry-getDipToken--)
`getDipToken() → contract IERC20Metadata dipToken` external
returns the dip token for this chain
#### [](#TokenRegistry-tokens--)
`tokens() → uint256` external
returns the number of registered tokens
#### [](#TokenRegistry-getTokenInfo-uint256-)
`getTokenInfo(uint256 idx) → struct TokenRegistry.TokenInfo tokenInfo` external
returns the token info for the specified index position \[0 .. tokens() - 1\].
#### [](#TokenRegistry-getTokenInfo-ChainId-address-)
`getTokenInfo(ChainId chainId, address token) → struct TokenRegistry.TokenInfo tokenInfo` external
returns the token info for the specified token coordinates.
#### [](#TokenRegistry-isRegistered-ChainId-address-)
`isRegistered(ChainId chainId, address token) → bool` public
returns true iff the specified token has been registered for this TokenRegistry contract.
#### [](#TokenRegistry-isActive-ChainId-address-VersionPart-)
`isActive(ChainId chainId, address token, VersionPart release) → bool` external
returns true iff both the token is active for the specfied release and the global token state is active
#### [](#TokenRegistry-getDipTokenAddress--)
`getDipTokenAddress() → address` external
#### [](#TokenRegistry-getRegistry--)
`getRegistry() → contract IRegistry` public
returns the dip token for this chain
#### [](#TokenRegistry-_verifyOnchainToken-address-)
`_verifyOnchainToken(address tokenAddress) → contract IERC20Metadata token` internal
checks if provided token address refers to a smart contract that implements erc20 functionality (via its non-optional functions)
#### [](#TokenRegistry-_implementsErc20Functions-contract-IERC20Metadata-)
`_implementsErc20Functions(contract IERC20Metadata token) → bool implementsErc20Functions` internal
checks availability of non-optional view functions [https://eips.ethereum.org/EIPS/eip-20#methods](https://eips.ethereum.org/EIPS/eip-20#methods)
#### [](#TokenRegistry-_registerToken-ChainId-address-uint8-string-)
`_registerToken(ChainId chainId, address token, uint8 decimals, string symbol)` internal
some sanity checks to prevent unintended registration: - token not yet registered - chainId not zero - token address not zero
#### [](#TokenRegistry-LogTokenRegistryTokenRegistered-ChainId-address-uint256-string-)
`LogTokenRegistryTokenRegistered(ChainId indexed chainId, address indexed token, uint256 decimals, string symbol)` event
#### [](#TokenRegistry-LogTokenRegistryTokenGlobalStateSet-ChainId-address-bool-)
`LogTokenRegistryTokenGlobalStateSet(ChainId indexed chainId, address indexed token, bool indexed active)` event
#### [](#TokenRegistry-LogTokenRegistryTokenStateSet-ChainId-address-VersionPart-bool-)
`LogTokenRegistryTokenStateSet(ChainId indexed chainId, address indexed token, VersionPart indexed release, bool active)` event
### [](#RegistryService)
`RegistryService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/RegistryService.sol)
import "@etherisc/gif-next/contracts/registry/RegistryService.sol";
Functions
* \[`_initialize(owner, data)`\]
* \[`registerStaking(staking, owner)`\]
* \[`registerInstance(instance, owner)`\]
* \[`registerProduct(product, initialOwner)`\]
* \[`registerProductLinkedComponent(component, objectType, initialOwner)`\]
* \[`registerDistributor(info)`\]
* \[`registerPolicy(info)`\]
* \[`registerBundle(info)`\]
* \[`registerStake(info)`\]
* \[`_getAndVerifyContractInfo(registerable, expectedType, expectedOwner)`\]
* \[`_verifyObjectInfo(info, expectedType)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#RegistryService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
top level initializer
#### [](#RegistryService-registerStaking-contract-IRegisterable-address-)
`registerStaking(contract IRegisterable staking, address owner) → struct IRegistry.ObjectInfo info` external
#### [](#RegistryService-registerInstance-contract-IRegisterable-address-)
`registerInstance(contract IRegisterable instance, address owner) → struct IRegistry.ObjectInfo info` external
#### [](#RegistryService-registerProduct-contract-IComponent-address-)
`registerProduct(contract IComponent product, address initialOwner) → struct IRegistry.ObjectInfo info` external
#### [](#RegistryService-registerProductLinkedComponent-contract-IComponent-ObjectType-address-)
`registerProductLinkedComponent(contract IComponent component, ObjectType objectType, address initialOwner) → struct IRegistry.ObjectInfo info` external
#### [](#RegistryService-registerDistributor-struct-IRegistry-ObjectInfo-)
`registerDistributor(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#RegistryService-registerPolicy-struct-IRegistry-ObjectInfo-)
`registerPolicy(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#RegistryService-registerBundle-struct-IRegistry-ObjectInfo-)
`registerBundle(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#RegistryService-registerStake-struct-IRegistry-ObjectInfo-)
`registerStake(struct IRegistry.ObjectInfo info) → NftId nftId` external
#### [](#RegistryService-_getAndVerifyContractInfo-contract-IRegisterable-ObjectType-address-)
`_getAndVerifyContractInfo(contract IRegisterable registerable, ObjectType expectedType, address expectedOwner) → struct IRegistry.ObjectInfo info` internal
#### [](#RegistryService-_verifyObjectInfo-struct-IRegistry-ObjectInfo-ObjectType-)
`_verifyObjectInfo(struct IRegistry.ObjectInfo info, ObjectType expectedType)` internal
#### [](#RegistryService-_getDomain--)
`_getDomain() → ObjectType serviceDomain` internal
### [](#RegistryServiceManager)
`RegistryServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/registry/RegistryServiceManager.sol)
import "@etherisc/gif-next/contracts/registry/RegistryServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getRegistryService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#RegistryServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with registry service implementation and deploys registry
#### [](#RegistryServiceManager-getRegistryService--)
`getRegistryService() → contract RegistryService registryService` external
[← product](/gif-next/3.x/api/product)
[shared →](/gif-next/3.x/api/shared)
---
# Staking - Etherisc Docs
Staking
=======
Contains all staking related interfaces and contracts.
[](#contracts)
Contracts
------------------------
### [](#IStaking)
`IStaking`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/IStaking.sol)
import "@etherisc/gif-next/contracts/staking/IStaking.sol";
Functions
* \[`initializeTokenHandler()`\]
* \[`setSupportInfo(targetType, isSupported, allowNewTargets, allowCrossChain, minStakingAmount, maxStakingAmount, minLockingPeriod, maxLockingPeriod, minRewardRate, maxRewardRate)`\]
* \[`setUpdateTriggers(tvlUpdatesTrigger, minTvlRatioTrigger)`\]
* \[`setProtocolLockingPeriod(lockingPeriod)`\]
* \[`setProtocolRewardRate(rewardRate)`\]
* \[`setStakingRate(chainId, token, stakingRate)`\]
* \[`setStakingService(release)`\]
* \[`setStakingReader(stakingReader)`\]
* \[`addToken(chainId, token)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`refillRewardReserves(targetNftId, dipAmount)`\]
* \[`withdrawRewardReserves(targetNftId, dipAmount)`\]
* \[`registerTarget(targetNftId, expectedObjectType, initialLockingPeriod, initialRewardRate)`\]
* \[`setLockingPeriod(targetNftId, lockingPeriod)`\]
* \[`setRewardRate(targetNftId, rewardRate)`\]
* \[`setTargetLimits(targetNftId, marginAmount, limitAmount)`\]
* \[`setMaxStakedAmount(targetNftId, stakeLimitAmount)`\]
* \[`addTargetToken(targetNftId, token)`\]
* \[`increaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`decreaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`updateRemoteTvl(targetNftId, token, amount)`\]
* \[`refillRewardReservesByService(targetNftId, dipAmount, transferFrom)`\]
* \[`withdrawRewardReservesByService(targetNftId, dipAmount, transferTo)`\]
* \[`updateTargetLimit(targetNftId)`\]
* \[`createStake(targetNftId, dipAmount, stakeOwner)`\]
* \[`stake(stakeNftId, dipAmount)`\]
* \[`unstake(stakeNftId)`\]
* \[`restake(stakeNftId, newTargetNftId)`\]
* \[`updateRewards(stakeNftId)`\]
* \[`claimRewards(stakeNftId)`\]
* \[`getTargetHandler()`\]
* \[`getStakingStore()`\]
* \[`getStakingReader()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IComponent
* \[`getName()`\]
* \[`getToken()`\]
* \[`getTokenHandler()`\]
* \[`getWallet()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
ITransferInterceptor
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogStakingTokenHandlerDeployed(componentNftId, tokenHandler, token)`\]
* \[`LogStakingStakingRateSet(chainId, token, oldStakingRate, newStakingRate, lastUpdateIn)`\]
* \[`LogStakingStakingServiceSet(oldStakingService, stakingService, release)`\]
* \[`LogStakingStakingReaderSet(oldStakingReader, stakingReader)`\]
* \[`LogStakingTargetHandlerSet(oldTargetHandler, targetManager)`\]
* \[`LogStakingTokenHandlerApproved(oldApprovalAmount, approvalAmount, token)`\]
* \[`LogStakingTokenAdded(chainId, token)`\]
* \[`LogStakingTargetTokenAdded(targetNftId, token)`\]
* \[`LogStakingTvlIncreased(targetNftId, token, amount, newBalance, lastUpdateIn)`\]
* \[`LogStakingTvlDecreased(targetNftId, token, amount, newBalance, lastUpdateIn)`\]
* \[`LogStakingSupportInfoSet(objectType, isSupported, allowNewTargets, allowCrossChain, minStakingAmount, maxStakingAmount, minLockingPeriod, maxLockingPeriod, minRewardRate, maxRewardRate, lastUpdateIn)`\]
* \[`LogStakingTargetCreated(targetNftId, objectType, lockingPeriod, rewardRate)`\]
* \[`LogStakingLimitsSet(targetNftId, marginAmount, hardLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitsUpdated(targetNftId, marginAmount, hardLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitUpdated(targetNftId, limitAmount, hardLimitAmount, requiredStakeAmount, actualStakeAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLockingPeriodSet(targetNftId, oldLockingPeriod, lockingPeriod, lastUpdateIn)`\]
* \[`LogStakingTargetRewardRateSet(targetNftId, oldRewardRate, rewardRate, lastUpdateIn)`\]
* \[`LogStakingTargetMaxStakedAmountSet(targetNftId, stakeLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitsSet(targetNftId, stakeLimitAmount, marginAmount, limitAmount)`\]
* \[`LogStakingRewardReservesRefilled(targetNftId, dipAmount, targetOwner, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingRewardReservesWithdrawn(targetNftId, dipAmount, targetOwner, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingRewardReservesSpent(targetNftId, dipAmount, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingStakeCreated(stakeNftId, targetNftId, stakeAmount, lockedUntil, stakeOwner)`\]
* \[`LogStakingStakeRewardsUpdated(stakeNftId, rewardIncrementAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingRewardsRestaked(stakeNftId, restakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingStaked(stakeNftId, stakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingUnstaked(stakeNftId, unstakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingRewardsClaimed(stakeNftId, claimedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingStakeRestaked(stakeNftId, targetNftId, stakeAmount, owner, oldStakeNftId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IStaking-initializeTokenHandler--)
`initializeTokenHandler()` external
#### [](#IStaking-setSupportInfo-ObjectType-bool-bool-bool-Amount-Amount-Seconds-Seconds-UFixed-UFixed-)
`setSupportInfo(ObjectType targetType, bool isSupported, bool allowNewTargets, bool allowCrossChain, Amount minStakingAmount, Amount maxStakingAmount, Seconds minLockingPeriod, Seconds maxLockingPeriod, UFixed minRewardRate, UFixed maxRewardRate)` external
Enable/disable the staking support for the specified target type. Defines the degrees of freedom for creating staking targets per target type.
#### [](#IStaking-setUpdateTriggers-uint16-UFixed-)
`setUpdateTriggers(uint16 tvlUpdatesTrigger, UFixed minTvlRatioTrigger)` external
Set the trigger values to determine when to update limit amount in TargetInfo. Changes in the TvlInfo may trigger an update of the limit amount in the TargetInfo based on these settings. The value tvlUpdatesTrigger suppresses any updates if the number of TVL updates is below this value. The value minTvlRatioTrigger defines the minimal TVL ratio above which the limit amount is updated. The ratio is calulated as current TVL / baseline TVL (or baseline TVL / current TVL).
#### [](#IStaking-setProtocolLockingPeriod-Seconds-)
`setProtocolLockingPeriod(Seconds lockingPeriod)` external
Set the stake locking period for protocol stakes to the specified duration.
#### [](#IStaking-setProtocolRewardRate-UFixed-)
`setProtocolRewardRate(UFixed rewardRate)` external
Set the protocol reward rate.
#### [](#IStaking-setStakingRate-ChainId-address-UFixed-)
`setStakingRate(ChainId chainId, address token, UFixed stakingRate)` external
Set the staking rate for the specified chain and token. The staking rate defines the amount of staked dips required to back up 1 token of total value locked.
#### [](#IStaking-setStakingService-VersionPart-)
`setStakingService(VersionPart release)` external
Sets/updates the staking service contract to the staking service of the specified release.
#### [](#IStaking-setStakingReader-address-)
`setStakingReader(address stakingReader)` external
Sets/updates the staking reader contract.
#### [](#IStaking-addToken-ChainId-address-)
`addToken(ChainId chainId, address token)` external
Registers a token for recording staking rate and total value locked.
#### [](#IStaking-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
Set the approval to the token handler. Defines the max allowance from the staking wallet to the token handler.
#### [](#IStaking-refillRewardReserves-NftId-Amount-)
`refillRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target Unpermissioned: anybody may fill up staking reward reserves
#### [](#IStaking-withdrawRewardReserves-NftId-Amount-)
`withdrawRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: only the owner may call this function
#### [](#IStaking-registerTarget-NftId-ObjectType-Seconds-UFixed-)
`registerTarget(NftId targetNftId, ObjectType expectedObjectType, Seconds initialLockingPeriod, UFixed initialRewardRate)` external
Register a new target for staking. Permissioned: only the staking service may call this function
#### [](#IStaking-setLockingPeriod-NftId-Seconds-)
`setLockingPeriod(NftId targetNftId, Seconds lockingPeriod)` external
Set the stake locking period to the specified duration. Permissioned: only the staking service may call this function
#### [](#IStaking-setRewardRate-NftId-UFixed-)
`setRewardRate(NftId targetNftId, UFixed rewardRate)` external
Update the target specific reward rate. Permissioned: only the staking service may call this function
#### [](#IStaking-setTargetLimits-NftId-Amount-Amount-)
`setTargetLimits(NftId targetNftId, Amount marginAmount, Amount limitAmount)` external
Set the staking limits for the specified target. The margin amount allows staker to stake over the current required stakes by this amount. The limit amount restricts stakers to ever stake more than this amount. Permissioned: only the target owner may call this function
#### [](#IStaking-setMaxStakedAmount-NftId-Amount-)
`setMaxStakedAmount(NftId targetNftId, Amount stakeLimitAmount)` external
Set the maximum staked amount for the specified target. Permissioned: only the staking service may call this function
#### [](#IStaking-addTargetToken-NftId-address-)
`addTargetToken(NftId targetNftId, address token)` external
Register a token for the specified target. Used for instance targets. Each product may introduce its own token. Permissioned: only the staking service may call this function
#### [](#IStaking-increaseTotalValueLocked-NftId-address-Amount-)
`increaseTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Increases the total value locked amount for the specified target by the provided token amount. function is called when a new policy is collateralized. function restricted to the pool service.
#### [](#IStaking-decreaseTotalValueLocked-NftId-address-Amount-)
`decreaseTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Decreases the total value locked amount for the specified target by the provided token amount. function is called when a new policy is closed or payouts are executed. function restricted to the pool service.
#### [](#IStaking-updateRemoteTvl-NftId-address-Amount-)
`updateRemoteTvl(NftId targetNftId, address token, Amount amount)` external
#### [](#IStaking-refillRewardReservesByService-NftId-Amount-address-)
`refillRewardReservesByService(NftId targetNftId, Amount dipAmount, address transferFrom) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target Unpermissioned: anybody may fill up staking reward reserves
#### [](#IStaking-withdrawRewardReservesByService-NftId-Amount-address-)
`withdrawRewardReservesByService(NftId targetNftId, Amount dipAmount, address transferTo) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: only the owner may call this function
#### [](#IStaking-updateTargetLimit-NftId-)
`updateTargetLimit(NftId targetNftId)` external
Updates the current limit amount for the specified target. The function takes into account the current TVL amount per token and the current staking rate for the token to calculate the required stake amount. Based on this required stake amount and the targets margin and hard limit (from LimitInfo) the function updates the target limit amount (in the target info)
#### [](#IStaking-createStake-NftId-Amount-address-)
`createStake(NftId targetNftId, Amount dipAmount, address stakeOwner) → NftId stakeNftId` external
Creates a new stake to the specified target over the given DIP amount. The stake owner is provided as an argument and becomes the stake NFT holder. This function is permissionless and may be called by any user.
#### [](#IStaking-stake-NftId-Amount-)
`stake(NftId stakeNftId, Amount dipAmount) → Amount newStakeBalance` external
Increase the staked DIP by dipAmount for the specified stake. Staking rewards are updated and added to the staked DIP amount as well. The function returns the new total amount of staked dips.
#### [](#IStaking-unstake-NftId-)
`unstake(NftId stakeNftId) → Amount unstakedAmount` external
Pays the specified DIP amount to the holder of the stake NFT ID. permissioned: only staking service may call this function.
#### [](#IStaking-restake-NftId-NftId-)
`restake(NftId stakeNftId, NftId newTargetNftId) → NftId newStakeNftId, Amount newStakeBalance` external
restakes the dips to a new target. the sum of the staked dips and the accumulated rewards will be restaked. permissioned: only staking service may call this function.
#### [](#IStaking-updateRewards-NftId-)
`updateRewards(NftId stakeNftId) → Amount newRewardAmount` external
update stake rewards for current time. may be called before an announement of a decrease of a reward rate reduction. calling this functions ensures that reward balance is updated using the current (higher) reward rate. unpermissioned.
#### [](#IStaking-claimRewards-NftId-)
`claimRewards(NftId stakeNftId) → Amount rewardsClaimedAmount` external
transfers all rewards accumulated so far to the holder of the specified stake nft. permissioned: only staking service may call this function.
#### [](#IStaking-getTargetHandler--)
`getTargetHandler() → contract TargetHandler targetHandler` external
#### [](#IStaking-getStakingStore--)
`getStakingStore() → contract StakingStore stakingStore` external
#### [](#IStaking-getStakingReader--)
`getStakingReader() → contract StakingReader reader` external
#### [](#IStaking-LogStakingTokenHandlerDeployed-NftId-address-address-)
`LogStakingTokenHandlerDeployed(NftId indexed componentNftId, address indexed tokenHandler, address indexed token)` event
#### [](#IStaking-LogStakingStakingRateSet-ChainId-address-UFixed-UFixed-Blocknumber-)
`LogStakingStakingRateSet(ChainId indexed chainId, address indexed token, UFixed oldStakingRate, UFixed newStakingRate, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingStakingServiceSet-address-address-VersionPart-)
`LogStakingStakingServiceSet(address indexed oldStakingService, address indexed stakingService, VersionPart indexed release)` event
#### [](#IStaking-LogStakingStakingReaderSet-address-address-)
`LogStakingStakingReaderSet(address indexed oldStakingReader, address indexed stakingReader)` event
#### [](#IStaking-LogStakingTargetHandlerSet-address-address-)
`LogStakingTargetHandlerSet(address indexed oldTargetHandler, address indexed targetManager)` event
#### [](#IStaking-LogStakingTokenHandlerApproved-Amount-Amount-address-)
`LogStakingTokenHandlerApproved(Amount oldApprovalAmount, Amount approvalAmount, address indexed token)` event
#### [](#IStaking-LogStakingTokenAdded-ChainId-address-)
`LogStakingTokenAdded(ChainId indexed chainId, address indexed token)` event
#### [](#IStaking-LogStakingTargetTokenAdded-NftId-address-)
`LogStakingTargetTokenAdded(NftId indexed targetNftId, address indexed token)` event
#### [](#IStaking-LogStakingTvlIncreased-NftId-address-Amount-Amount-Blocknumber-)
`LogStakingTvlIncreased(NftId indexed targetNftId, address indexed token, Amount amount, Amount newBalance, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTvlDecreased-NftId-address-Amount-Amount-Blocknumber-)
`LogStakingTvlDecreased(NftId indexed targetNftId, address indexed token, Amount amount, Amount newBalance, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingSupportInfoSet-ObjectType-bool-bool-bool-Amount-Amount-Seconds-Seconds-UFixed-UFixed-Blocknumber-)
`LogStakingSupportInfoSet(ObjectType indexed objectType, bool indexed isSupported, bool indexed allowNewTargets, bool allowCrossChain, Amount minStakingAmount, Amount maxStakingAmount, Seconds minLockingPeriod, Seconds maxLockingPeriod, UFixed minRewardRate, UFixed maxRewardRate, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetCreated-NftId-ObjectType-Seconds-UFixed-)
`LogStakingTargetCreated(NftId indexed targetNftId, ObjectType indexed objectType, Seconds lockingPeriod, UFixed rewardRate)` event
#### [](#IStaking-LogStakingLimitsSet-NftId-Amount-Amount-Blocknumber-)
`LogStakingLimitsSet(NftId indexed targetNftId, Amount marginAmount, Amount hardLimitAmount, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetLimitsUpdated-NftId-Amount-Amount-Blocknumber-)
`LogStakingTargetLimitsUpdated(NftId indexed targetNftId, Amount marginAmount, Amount hardLimitAmount, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetLimitUpdated-NftId-Amount-Amount-Amount-Amount-Blocknumber-)
`LogStakingTargetLimitUpdated(NftId indexed targetNftId, Amount limitAmount, Amount hardLimitAmount, Amount requiredStakeAmount, Amount actualStakeAmount, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetLockingPeriodSet-NftId-Seconds-Seconds-Blocknumber-)
`LogStakingTargetLockingPeriodSet(NftId indexed targetNftId, Seconds oldLockingPeriod, Seconds lockingPeriod, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetRewardRateSet-NftId-UFixed-UFixed-Blocknumber-)
`LogStakingTargetRewardRateSet(NftId indexed targetNftId, UFixed oldRewardRate, UFixed rewardRate, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetMaxStakedAmountSet-NftId-Amount-Blocknumber-)
`LogStakingTargetMaxStakedAmountSet(NftId indexed targetNftId, Amount stakeLimitAmount, Blocknumber indexed lastUpdateIn)` event
#### [](#IStaking-LogStakingTargetLimitsSet-NftId-Amount-Amount-Amount-)
`LogStakingTargetLimitsSet(NftId indexed targetNftId, Amount stakeLimitAmount, Amount marginAmount, Amount limitAmount)` event
#### [](#IStaking-LogStakingRewardReservesRefilled-NftId-Amount-address-Amount-Blocknumber-)
`LogStakingRewardReservesRefilled(NftId indexed targetNftId, Amount dipAmount, address indexed targetOwner, Amount reserveBalance, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingRewardReservesWithdrawn-NftId-Amount-address-Amount-Blocknumber-)
`LogStakingRewardReservesWithdrawn(NftId indexed targetNftId, Amount dipAmount, address indexed targetOwner, Amount reserveBalance, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingRewardReservesSpent-NftId-Amount-Amount-Blocknumber-)
`LogStakingRewardReservesSpent(NftId indexed targetNftId, Amount dipAmount, Amount reserveBalance, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingStakeCreated-NftId-NftId-Amount-Timestamp-address-)
`LogStakingStakeCreated(NftId indexed stakeNftId, NftId indexed targetNftId, Amount stakeAmount, Timestamp lockedUntil, address stakeOwner)` event
#### [](#IStaking-LogStakingStakeRewardsUpdated-NftId-Amount-Amount-Amount-Timestamp-Blocknumber-)
`LogStakingStakeRewardsUpdated(NftId indexed stakeNftId, Amount rewardIncrementAmount, Amount stakeBalance, Amount rewardBalance, Timestamp lockedUntil, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingRewardsRestaked-NftId-Amount-Amount-Amount-Timestamp-Blocknumber-)
`LogStakingRewardsRestaked(NftId indexed stakeNftId, Amount restakedAmount, Amount stakeBalance, Amount rewardBalance, Timestamp lockedUntil, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingStaked-NftId-Amount-Amount-Amount-Timestamp-Blocknumber-)
`LogStakingStaked(NftId indexed stakeNftId, Amount stakedAmount, Amount stakeBalance, Amount rewardBalance, Timestamp lockedUntil, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingUnstaked-NftId-Amount-Amount-Amount-Timestamp-Blocknumber-)
`LogStakingUnstaked(NftId indexed stakeNftId, Amount unstakedAmount, Amount stakeBalance, Amount rewardBalance, Timestamp lockedUntil, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingRewardsClaimed-NftId-Amount-Amount-Amount-Timestamp-Blocknumber-)
`LogStakingRewardsClaimed(NftId indexed stakeNftId, Amount claimedAmount, Amount stakeBalance, Amount rewardBalance, Timestamp lockedUntil, Blocknumber lastUpdateIn)` event
#### [](#IStaking-LogStakingStakeRestaked-NftId-NftId-Amount-address-NftId-)
`LogStakingStakeRestaked(NftId indexed stakeNftId, NftId indexed targetNftId, Amount stakeAmount, address owner, NftId oldStakeNftId)` event
### [](#IStakingService)
`IStakingService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/IStakingService.sol)
import "@etherisc/gif-next/contracts/staking/IStakingService.sol";
Functions
* \[`createInstanceTarget(targetNftId, initialLockingPeriod, initialRewardRate)`\]
* \[`setInstanceLockingPeriod(instanceNftId, lockingPeriod)`\]
* \[`setInstanceRewardRate(instanceNftId, rewardRate)`\]
* \[`setInstanceMaxStakedAmount(instanceNftId, maxStakingAmount)`\]
* \[`refillInstanceRewardReserves(instanceNftId, rewardProvider, dipAmount)`\]
* \[`withdrawInstanceRewardReserves(instanceNftId, dipAmount)`\]
* \[`setTotalValueLocked(targetNftId, token, amount)`\]
* \[`createStakeObject(targetNftId, initialOwner)`\]
* \[`pullDipToken(dipAmount, stakeOwner)`\]
* \[`pushDipToken(dipAmount, stakeOwner)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`getDipToken()`\]
* \[`getTokenHandler()`\]
* \[`getStaking()`\]
IService
* \[`getDomain()`\]
* \[`getRoleId()`\]
IVersionable
* \[`initializeVersionable(activatedBy, activationData)`\]
* \[`upgradeVersionable(upgradeData)`\]
* \[`getVersion()`\]
IRegisterable
* \[`isActive()`\]
* \[`getInitialInfo()`\]
IRelease
* \[`getRelease()`\]
INftOwnable
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
IRegistryLinked
* \[`getRegistry()`\]
IERC165
* \[`supportsInterface(interfaceId)`\]
IAccessManaged
* \[`authority()`\]
* \[`setAuthority()`\]
* \[`isConsumingScheduledOp()`\]
Events
* \[`LogStakingServiceProtocolTargetRegistered(protocolNftId)`\]
* \[`LogStakingServiceInstanceTargetRegistered(instanceNftId, initialLockingPeriod, initialRewardRate)`\]
* \[`LogStakingServiceRewardReservesIncreased(targetNftId, rewardProvider, dipAmount, newBalance)`\]
* \[`LogStakingServiceRewardReservesDecreased(targetNftId, targetOwner, dipAmount, newBalance)`\]
* \[`LogStakingServiceStakeCreated(stakeNftId, targetNftId, stakeOwner)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
#### [](#IStakingService-createInstanceTarget-NftId-Seconds-UFixed-)
`createInstanceTarget(NftId targetNftId, Seconds initialLockingPeriod, UFixed initialRewardRate)` external
Creates/registers an on-chain instance staking target. Permissioned: Only instance service
#### [](#IStakingService-setInstanceLockingPeriod-NftId-Seconds-)
`setInstanceLockingPeriod(NftId instanceNftId, Seconds lockingPeriod)` external
Set the instance stake locking period to the specified duration. Permissioned: Only instance service
#### [](#IStakingService-setInstanceRewardRate-NftId-UFixed-)
`setInstanceRewardRate(NftId instanceNftId, UFixed rewardRate)` external
Set the instance reward rate to the specified value. Permissioned: Only instance service
#### [](#IStakingService-setInstanceMaxStakedAmount-NftId-Amount-)
`setInstanceMaxStakedAmount(NftId instanceNftId, Amount maxStakingAmount)` external
Set the instance max staked amount to the specified value. Permissioned: Only instance service
#### [](#IStakingService-refillInstanceRewardReserves-NftId-address-Amount-)
`refillInstanceRewardReserves(NftId instanceNftId, address rewardProvider, Amount dipAmount) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target using the dips provided by the reward provider. Permissioned: Only instance service
#### [](#IStakingService-withdrawInstanceRewardReserves-NftId-Amount-)
`withdrawInstanceRewardReserves(NftId instanceNftId, Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: Only instance service
#### [](#IStakingService-setTotalValueLocked-NftId-address-Amount-)
`setTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Sets total value locked data for a target contract on a different chain. this is done via CCIP (cross chain communication)
#### [](#IStakingService-createStakeObject-NftId-address-)
`createStakeObject(NftId targetNftId, address initialOwner) → NftId stakeNftId` external
Creates a new stake object for the specified target via the registry service. Permissioned: only the staking component may call this function
#### [](#IStakingService-pullDipToken-Amount-address-)
`pullDipToken(Amount dipAmount, address stakeOwner)` external
Collect DIP token from stake owner. Permissioned: only the staking component may call this function
#### [](#IStakingService-pushDipToken-Amount-address-)
`pushDipToken(Amount dipAmount, address stakeOwner)` external
Transfer DIP token to stake owner. Permissioned: only the staking component may call this function
#### [](#IStakingService-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
Approves the staking token handler. Permissioned: only the staking component may call this function
#### [](#IStakingService-getDipToken--)
`getDipToken() → contract IERC20Metadata dip` external
#### [](#IStakingService-getTokenHandler--)
`getTokenHandler() → contract TokenHandler tokenHandler` external
#### [](#IStakingService-getStaking--)
`getStaking() → contract IStaking staking` external
#### [](#IStakingService-LogStakingServiceProtocolTargetRegistered-NftId-)
`LogStakingServiceProtocolTargetRegistered(NftId indexed protocolNftId)` event
#### [](#IStakingService-LogStakingServiceInstanceTargetRegistered-NftId-Seconds-UFixed-)
`LogStakingServiceInstanceTargetRegistered(NftId indexed instanceNftId, Seconds initialLockingPeriod, UFixed initialRewardRate)` event
#### [](#IStakingService-LogStakingServiceRewardReservesIncreased-NftId-address-Amount-Amount-)
`LogStakingServiceRewardReservesIncreased(NftId indexed targetNftId, address indexed rewardProvider, Amount dipAmount, Amount newBalance)` event
#### [](#IStakingService-LogStakingServiceRewardReservesDecreased-NftId-address-Amount-Amount-)
`LogStakingServiceRewardReservesDecreased(NftId indexed targetNftId, address indexed targetOwner, Amount dipAmount, Amount newBalance)` event
#### [](#IStakingService-LogStakingServiceStakeCreated-NftId-NftId-address-)
`LogStakingServiceStakeCreated(NftId indexed stakeNftId, NftId indexed targetNftId, address indexed stakeOwner)` event
### [](#Staking)
`Staking`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/Staking.sol)
import "@etherisc/gif-next/contracts/staking/Staking.sol";
Modifiers
* [`onlyStakeOwner(stakeNftId)`](#Staking-onlyStakeOwner-NftId-)
* [`onlyTarget(targetNftId)`](#Staking-onlyTarget-NftId-)
* [`onlyTargetOwner(targetNftId)`](#Staking-onlyTargetOwner-NftId-)
Functions
* \[`initializeTokenHandler()`\]
* \[`setSupportInfo(targetType, isSupported, allowNewTargets, allowCrossChain, minStakingAmount, maxStakingAmount, minLockingPeriod, maxLockingPeriod, minRewardRate, maxRewardRate)`\]
* \[`setUpdateTriggers(tvlUpdatesTrigger, minTvlRatioTrigger)`\]
* \[`setProtocolLockingPeriod(newLockingPeriod)`\]
* \[`setProtocolRewardRate(newRewardRate)`\]
* \[`setStakingRate(chainId, token, stakingRate)`\]
* \[`setStakingService(release)`\]
* \[`setStakingReader(reader)`\]
* \[`addToken(chainId, token)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`refillRewardReserves(targetNftId, dipAmount)`\]
* \[`withdrawRewardReserves(targetNftId, dipAmount)`\]
* \[`refillRewardReservesByService(targetNftId, dipAmount, transferFrom)`\]
* \[`withdrawRewardReservesByService(targetNftId, dipAmount, transferTo)`\]
* \[`registerTarget(targetNftId, expectedObjectType, initialLockingPeriod, initialRewardRate)`\]
* \[`setLockingPeriod(targetNftId, lockingPeriod)`\]
* \[`setRewardRate(targetNftId, rewardRate)`\]
* \[`setMaxStakedAmount(targetNftId, stakeLimitAmount)`\]
* \[`setTargetLimits(targetNftId, marginAmount, limitAmount)`\]
* \[`addTargetToken(targetNftId, token)`\]
* \[`increaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`decreaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`registerRemoteTarget(targetNftId, targetInfo)`\]
* \[`updateRemoteTvl(targetNftId, token, amount)`\]
* \[`updateTargetLimit(targetNftId)`\]
* \[`createStake(targetNftId, stakeAmount, stakeOwner)`\]
* \[`stake(stakeNftId, stakeAmount)`\]
* \[`unstake(stakeNftId)`\]
* \[`restake(stakeNftId, newTargetNftId)`\]
* \[`updateRewards(stakeNftId)`\]
* \[`claimRewards(stakeNftId)`\]
* \[`getStakingReader()`\]
* \[`getTargetHandler()`\]
* \[`getStakingStore()`\]
* \[`getTokenRegistryAddress()`\]
* \[`getTokenHandler()`\]
* \[`getRelease()`\]
* \[`getVersion()`\]
* \[`_refillRewardReserves(targetNftId, dipAmount, transferFrom)`\]
* \[`_withdrawRewardReserves(targetNftId, dipAmount, transferTo)`\]
* \[`_addToken($, chainId, token)`\]
* \[`_initialize(owner, data)`\]
* \[`_checkTypeAndOwner(nftId, expectedObjectType, checkOwner)`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Component
* \[`__Component_init(authority, registry, parentNftId, name, componentType, isInterceptor, initialOwner, registryData)`\]
* \[`nftTransferFrom(from, to, tokenId, operator)`\]
* \[`getWallet()`\]
* \[`getToken()`\]
* \[`getName()`\]
* \[`getComponentInfo()`\]
* \[`getInitialComponentInfo()`\]
* \[`isNftInterceptor()`\]
* \[`isRegistered()`\]
* \[`_approveTokenHandler(token, amount)`\]
* \[`_nftTransferFrom(from, to, tokenId, operator)`\]
* \[`_setWallet(newWallet)`\]
* \[`_setLocked(locked)`\]
* \[`_getComponentInfo()`\]
* \[`_getServiceAddress(domain)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IStaking
* \[`LogStakingTokenHandlerDeployed(componentNftId, tokenHandler, token)`\]
* \[`LogStakingStakingRateSet(chainId, token, oldStakingRate, newStakingRate, lastUpdateIn)`\]
* \[`LogStakingStakingServiceSet(oldStakingService, stakingService, release)`\]
* \[`LogStakingStakingReaderSet(oldStakingReader, stakingReader)`\]
* \[`LogStakingTargetHandlerSet(oldTargetHandler, targetManager)`\]
* \[`LogStakingTokenHandlerApproved(oldApprovalAmount, approvalAmount, token)`\]
* \[`LogStakingTokenAdded(chainId, token)`\]
* \[`LogStakingTargetTokenAdded(targetNftId, token)`\]
* \[`LogStakingTvlIncreased(targetNftId, token, amount, newBalance, lastUpdateIn)`\]
* \[`LogStakingTvlDecreased(targetNftId, token, amount, newBalance, lastUpdateIn)`\]
* \[`LogStakingSupportInfoSet(objectType, isSupported, allowNewTargets, allowCrossChain, minStakingAmount, maxStakingAmount, minLockingPeriod, maxLockingPeriod, minRewardRate, maxRewardRate, lastUpdateIn)`\]
* \[`LogStakingTargetCreated(targetNftId, objectType, lockingPeriod, rewardRate)`\]
* \[`LogStakingLimitsSet(targetNftId, marginAmount, hardLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitsUpdated(targetNftId, marginAmount, hardLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitUpdated(targetNftId, limitAmount, hardLimitAmount, requiredStakeAmount, actualStakeAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLockingPeriodSet(targetNftId, oldLockingPeriod, lockingPeriod, lastUpdateIn)`\]
* \[`LogStakingTargetRewardRateSet(targetNftId, oldRewardRate, rewardRate, lastUpdateIn)`\]
* \[`LogStakingTargetMaxStakedAmountSet(targetNftId, stakeLimitAmount, lastUpdateIn)`\]
* \[`LogStakingTargetLimitsSet(targetNftId, stakeLimitAmount, marginAmount, limitAmount)`\]
* \[`LogStakingRewardReservesRefilled(targetNftId, dipAmount, targetOwner, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingRewardReservesWithdrawn(targetNftId, dipAmount, targetOwner, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingRewardReservesSpent(targetNftId, dipAmount, reserveBalance, lastUpdateIn)`\]
* \[`LogStakingStakeCreated(stakeNftId, targetNftId, stakeAmount, lockedUntil, stakeOwner)`\]
* \[`LogStakingStakeRewardsUpdated(stakeNftId, rewardIncrementAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingRewardsRestaked(stakeNftId, restakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingStaked(stakeNftId, stakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingUnstaked(stakeNftId, unstakedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingRewardsClaimed(stakeNftId, claimedAmount, stakeBalance, rewardBalance, lockedUntil, lastUpdateIn)`\]
* \[`LogStakingStakeRestaked(stakeNftId, targetNftId, stakeAmount, owner, oldStakeNftId)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#Staking-onlyStakeOwner-NftId-)
`onlyStakeOwner(NftId stakeNftId)` modifier
#### [](#Staking-onlyTarget-NftId-)
`onlyTarget(NftId targetNftId)` modifier
#### [](#Staking-onlyTargetOwner-NftId-)
`onlyTargetOwner(NftId targetNftId)` modifier
#### [](#Staking-initializeTokenHandler--)
`initializeTokenHandler()` external
#### [](#Staking-setSupportInfo-ObjectType-bool-bool-bool-Amount-Amount-Seconds-Seconds-UFixed-UFixed-)
`setSupportInfo(ObjectType targetType, bool isSupported, bool allowNewTargets, bool allowCrossChain, Amount minStakingAmount, Amount maxStakingAmount, Seconds minLockingPeriod, Seconds maxLockingPeriod, UFixed minRewardRate, UFixed maxRewardRate)` external
Enable/disable the staking support for the specified target type. Defines the degrees of freedom for creating staking targets per target type.
#### [](#Staking-setUpdateTriggers-uint16-UFixed-)
`setUpdateTriggers(uint16 tvlUpdatesTrigger, UFixed minTvlRatioTrigger)` external
Set the trigger values to determine when to update limit amount in TargetInfo. Changes in the TvlInfo may trigger an update of the limit amount in the TargetInfo based on these settings. The value tvlUpdatesTrigger suppresses any updates if the number of TVL updates is below this value. The value minTvlRatioTrigger defines the minimal TVL ratio above which the limit amount is updated. The ratio is calulated as current TVL / baseline TVL (or baseline TVL / current TVL).
#### [](#Staking-setProtocolLockingPeriod-Seconds-)
`setProtocolLockingPeriod(Seconds newLockingPeriod)` external
Set the stake locking period for protocol stakes to the specified duration.
#### [](#Staking-setProtocolRewardRate-UFixed-)
`setProtocolRewardRate(UFixed newRewardRate)` external
Set the protocol reward rate.
#### [](#Staking-setStakingRate-ChainId-address-UFixed-)
`setStakingRate(ChainId chainId, address token, UFixed stakingRate)` external
Set the staking rate for the specified chain and token. The staking rate defines the amount of staked dips required to back up 1 token of total value locked.
#### [](#Staking-setStakingService-VersionPart-)
`setStakingService(VersionPart release)` external
Sets/updates the staking service contract to the staking service of the specified release.
#### [](#Staking-setStakingReader-address-)
`setStakingReader(address reader)` external
Sets/updates the staking reader contract.
#### [](#Staking-addToken-ChainId-address-)
`addToken(ChainId chainId, address token)` external
Registers a token for recording staking rate and total value locked.
#### [](#Staking-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` public
Set the approval to the token handler. Defines the max allowance from the staking wallet to the token handler.
#### [](#Staking-refillRewardReserves-NftId-Amount-)
`refillRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target Unpermissioned: anybody may fill up staking reward reserves
#### [](#Staking-withdrawRewardReserves-NftId-Amount-)
`withdrawRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: only the owner may call this function
#### [](#Staking-refillRewardReservesByService-NftId-Amount-address-)
`refillRewardReservesByService(NftId targetNftId, Amount dipAmount, address transferFrom) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target Unpermissioned: anybody may fill up staking reward reserves
#### [](#Staking-withdrawRewardReservesByService-NftId-Amount-address-)
`withdrawRewardReservesByService(NftId targetNftId, Amount dipAmount, address transferTo) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: only the owner may call this function
#### [](#Staking-registerTarget-NftId-ObjectType-Seconds-UFixed-)
`registerTarget(NftId targetNftId, ObjectType expectedObjectType, Seconds initialLockingPeriod, UFixed initialRewardRate)` external
Register a new target for staking. Permissioned: only the staking service may call this function
#### [](#Staking-setLockingPeriod-NftId-Seconds-)
`setLockingPeriod(NftId targetNftId, Seconds lockingPeriod)` external
Set the stake locking period to the specified duration. Permissioned: only the staking service may call this function
#### [](#Staking-setRewardRate-NftId-UFixed-)
`setRewardRate(NftId targetNftId, UFixed rewardRate)` external
Update the target specific reward rate. Permissioned: only the staking service may call this function
#### [](#Staking-setMaxStakedAmount-NftId-Amount-)
`setMaxStakedAmount(NftId targetNftId, Amount stakeLimitAmount)` external
Set the maximum staked amount for the specified target. Permissioned: only the staking service may call this function
#### [](#Staking-setTargetLimits-NftId-Amount-Amount-)
`setTargetLimits(NftId targetNftId, Amount marginAmount, Amount limitAmount)` external
Set the staking limits for the specified target. The margin amount allows staker to stake over the current required stakes by this amount. The limit amount restricts stakers to ever stake more than this amount. Permissioned: only the target owner may call this function
#### [](#Staking-addTargetToken-NftId-address-)
`addTargetToken(NftId targetNftId, address token)` external
Register a token for the specified target. Used for instance targets. Each product may introduce its own token. Permissioned: only the staking service may call this function
#### [](#Staking-increaseTotalValueLocked-NftId-address-Amount-)
`increaseTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Increases the total value locked amount for the specified target by the provided token amount. function is called when a new policy is collateralized. function restricted to the pool service.
#### [](#Staking-decreaseTotalValueLocked-NftId-address-Amount-)
`decreaseTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Decreases the total value locked amount for the specified target by the provided token amount. function is called when a new policy is closed or payouts are executed. function restricted to the pool service.
#### [](#Staking-registerRemoteTarget-NftId-struct-IStaking-TargetInfo-)
`registerRemoteTarget(NftId targetNftId, struct IStaking.TargetInfo targetInfo)` external
#### [](#Staking-updateRemoteTvl-NftId-address-Amount-)
`updateRemoteTvl(NftId targetNftId, address token, Amount amount)` external
#### [](#Staking-updateTargetLimit-NftId-)
`updateTargetLimit(NftId targetNftId)` external
Updates the current limit amount for the specified target. The function takes into account the current TVL amount per token and the current staking rate for the token to calculate the required stake amount. Based on this required stake amount and the targets margin and hard limit (from LimitInfo) the function updates the target limit amount (in the target info)
#### [](#Staking-createStake-NftId-Amount-address-)
`createStake(NftId targetNftId, Amount stakeAmount, address stakeOwner) → NftId stakeNftId` external
Creates a new stake to the specified target over the given DIP amount. The stake owner is provided as an argument and becomes the stake NFT holder. This function is permissionless and may be called by any user.
#### [](#Staking-stake-NftId-Amount-)
`stake(NftId stakeNftId, Amount stakeAmount) → Amount newStakeBalance` external
Increase the staked DIP by dipAmount for the specified stake. Staking rewards are updated and added to the staked DIP amount as well. The function returns the new total amount of staked dips.
#### [](#Staking-unstake-NftId-)
`unstake(NftId stakeNftId) → Amount unstakedAmount` external
Pays the specified DIP amount to the holder of the stake NFT ID. permissioned: only staking service may call this function.
#### [](#Staking-restake-NftId-NftId-)
`restake(NftId stakeNftId, NftId newTargetNftId) → NftId newStakeNftId, Amount newStakedAmount` external
restakes the dips to a new target. the sum of the staked dips and the accumulated rewards will be restaked. permissioned: only staking service may call this function.
#### [](#Staking-updateRewards-NftId-)
`updateRewards(NftId stakeNftId) → Amount newRewardAmount` external
update stake rewards for current time. may be called before an announement of a decrease of a reward rate reduction. calling this functions ensures that reward balance is updated using the current (higher) reward rate. unpermissioned.
#### [](#Staking-claimRewards-NftId-)
`claimRewards(NftId stakeNftId) → Amount claimedAmount` external
transfers all rewards accumulated so far to the holder of the specified stake nft. permissioned: only staking service may call this function.
#### [](#Staking-getStakingReader--)
`getStakingReader() → contract StakingReader reader` public
#### [](#Staking-getTargetHandler--)
`getTargetHandler() → contract TargetHandler targetHandler` external
#### [](#Staking-getStakingStore--)
`getStakingStore() → contract StakingStore stakingStore` external
#### [](#Staking-getTokenRegistryAddress--)
`getTokenRegistryAddress() → address tokenRegistry` external
#### [](#Staking-getTokenHandler--)
`getTokenHandler() → contract TokenHandler tokenHandler` public
#### [](#Staking-getRelease--)
`getRelease() → VersionPart` public
#### [](#Staking-getVersion--)
`getVersion() → Version` public
#### [](#Staking-_refillRewardReserves-NftId-Amount-address-)
`_refillRewardReserves(NftId targetNftId, Amount dipAmount, address transferFrom) → Amount newBalance` internal
#### [](#Staking-_withdrawRewardReserves-NftId-Amount-address-)
`_withdrawRewardReserves(NftId targetNftId, Amount dipAmount, address transferTo) → Amount newBalance` internal
#### [](#Staking-_addToken-struct-Staking-StakingStorage-ChainId-address-)
`_addToken(struct Staking.StakingStorage $, ChainId chainId, address token)` internal
#### [](#Staking-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
top level initializer (upgradable contract)
#### [](#Staking-_checkTypeAndOwner-NftId-ObjectType-bool-)
`_checkTypeAndOwner(NftId nftId, ObjectType expectedObjectType, bool checkOwner)` internal
### [](#StakingStore)
`StakingStore`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingStore.sol)
import "@etherisc/gif-next/contracts/staking/StakingStore.sol";
Functions
* \[`constructor(registry, reader)`\]
* \[`_createInitialSetup()`\]
* \[`initialize(targetLimitHandler)`\]
* \[`setStakingReader(reader)`\]
* \[`setTargetLimitHandler(targetLimitHandler)`\]
* \[`setSupportInfo(targetType, isSupported, allowNewTargets, allowCrossChain, minStakingAmount, maxStakingAmount, minLockingPeriod, maxLockingPeriod, minRewardRate, maxRewardRate)`\]
* \[`getSupportInfo(targetType)`\]
* \[`addToken(chainId, token)`\]
* \[`setStakingRate(chainId, token, stakingRate)`\]
* \[`createTarget(targetNftId, objectType, lockingPeriod, rewardRate)`\]
* \[`setLockingPeriod(targetNftId, lockingPeriod)`\]
* \[`setRewardRate(targetNftId, rewardRate)`\]
* \[`setMaxStakedAmount(targetNftId, stakeLimitAmount)`\]
* \[`setTargetLimits(targetNftId, marginAmount, hardLimitAmount)`\]
* \[`addTargetToken(targetNftId, token)`\]
* \[`refillRewardReserves(targetNftId, dipAmount)`\]
* \[`withdrawRewardReserves(targetNftId, dipAmount)`\]
* \[`increaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`decreaseTotalValueLocked(targetNftId, token, amount)`\]
* \[`updateTargetLimit(targetNftId)`\]
* \[`_checkAndUpdateTargetLimit(targetNftId, token, tvlInfo)`\]
* \[`_updateTargetLimit(targetNftId)`\]
* \[`createStake(stakeNftId, targetNftId, stakeOwner, stakeAmount)`\]
* \[`stake(stakeNftId, updateRewards, restakeRewards, additionalLockingPeriod, stakeAmount)`\]
* \[`unstake(stakeNftId, updateRewards, restakeRewards, maxUnstakeAmount)`\]
* \[`updateRewards(stakeNftId)`\]
* \[`restakeRewards(stakeNftId, updateRewards)`\]
* \[`claimRewards(stakeNftId, updateRewards, maxClaimAmount)`\]
* \[`getStakingReader()`\]
* \[`getTargetManager()`\]
* \[`exists(stakeNftId)`\]
* \[`getRequiredStakeBalance(targetNftId, includeTargetTypeRequirements)`\]
* \[`isStakeLocked(stakeNftId)`\]
* \[`getStakeInfo(stakeNftId)`\]
* \[`getStakeTarget(stakeNftId)`\]
* \[`getTargetInfo(targetNftId)`\]
* \[`getLimitInfo(targetNftId)`\]
* \[`getTvlInfo(targetNftId, token)`\]
* \[`getTokenInfo(chainId, token)`\]
* \[`hasTokenInfo(chainId, token)`\]
* \[`getTargetSet()`\]
* \[`_updateRewards(stakeNftId, stakeInfo, targetInfo)`\]
* \[`_restakeRewards(stakeNftId, stakeInfo, targetInfo)`\]
* \[`_stake(stakeNftId, stakeInfo, targetInfo, maxAdditionalLockingPeriod, stakeAmount)`\]
* \[`_claimRewards(stakeNftId, stakeInfo, targetInfo, maxClaimAmount)`\]
* \[`_unstake(stakeNftId, stakeInfo, targetInfo, maxUnstakeAmount)`\]
* \[`_setLastUpdatesToCurrent(stakeInfo, targetInfo)`\]
* \[`_setStakeLastUpdatesToCurrent(stakeInfo)`\]
AccessManaged
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#StakingStore-constructor-contract-IRegistry-contract-StakingReader-)
`constructor(contract IRegistry registry, contract StakingReader reader)` public
#### [](#StakingStore-_createInitialSetup--)
`_createInitialSetup()` internal
#### [](#StakingStore-initialize-address-)
`initialize(address targetLimitHandler)` external
#### [](#StakingStore-setStakingReader-address-)
`setStakingReader(address reader)` external
#### [](#StakingStore-setTargetLimitHandler-address-)
`setTargetLimitHandler(address targetLimitHandler)` external
#### [](#StakingStore-setSupportInfo-ObjectType-bool-bool-bool-Amount-Amount-Seconds-Seconds-UFixed-UFixed-)
`setSupportInfo(ObjectType targetType, bool isSupported, bool allowNewTargets, bool allowCrossChain, Amount minStakingAmount, Amount maxStakingAmount, Seconds minLockingPeriod, Seconds maxLockingPeriod, UFixed minRewardRate, UFixed maxRewardRate)` external
Generic setter for support info. Any change in any of the parameters requires to set all parameters.
#### [](#StakingStore-getSupportInfo-ObjectType-)
`getSupportInfo(ObjectType targetType) → struct IStaking.SupportInfo supportInfo` external
Returns the support info for the specified target type.
#### [](#StakingStore-addToken-ChainId-address-)
`addToken(ChainId chainId, address token)` external
Registers a token for tvl management.
#### [](#StakingStore-setStakingRate-ChainId-address-UFixed-)
`setStakingRate(ChainId chainId, address token, UFixed stakingRate) → UFixed oldStakingRate, Blocknumber lastUpdatedIn` external
Sets the staking rate for the token.
#### [](#StakingStore-createTarget-NftId-ObjectType-Seconds-UFixed-)
`createTarget(NftId targetNftId, ObjectType objectType, Seconds lockingPeriod, UFixed rewardRate)` external
#### [](#StakingStore-setLockingPeriod-NftId-Seconds-)
`setLockingPeriod(NftId targetNftId, Seconds lockingPeriod)` external
#### [](#StakingStore-setRewardRate-NftId-UFixed-)
`setRewardRate(NftId targetNftId, UFixed rewardRate)` external
#### [](#StakingStore-setMaxStakedAmount-NftId-Amount-)
`setMaxStakedAmount(NftId targetNftId, Amount stakeLimitAmount) → Amount oldLimitAmount, Blocknumber lastUpdatedIn` external
#### [](#StakingStore-setTargetLimits-NftId-Amount-Amount-)
`setTargetLimits(NftId targetNftId, Amount marginAmount, Amount hardLimitAmount)` external
#### [](#StakingStore-addTargetToken-NftId-address-)
`addTargetToken(NftId targetNftId, address token)` external
#### [](#StakingStore-refillRewardReserves-NftId-Amount-)
`refillRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newReserveBalance` external
#### [](#StakingStore-withdrawRewardReserves-NftId-Amount-)
`withdrawRewardReserves(NftId targetNftId, Amount dipAmount) → Amount newReserveBalance` external
#### [](#StakingStore-increaseTotalValueLocked-NftId-address-Amount-)
`increaseTotalValueLocked(NftId targetNftId, address token, Amount amount) → Amount newBalance` external
#### [](#StakingStore-decreaseTotalValueLocked-NftId-address-Amount-)
`decreaseTotalValueLocked(NftId targetNftId, address token, Amount amount) → Amount newBalance` external
#### [](#StakingStore-updateTargetLimit-NftId-)
`updateTargetLimit(NftId targetNftId) → Amount stakeLimitAmount` external
#### [](#StakingStore-_checkAndUpdateTargetLimit-NftId-address-struct-IStaking-TvlInfo-)
`_checkAndUpdateTargetLimit(NftId targetNftId, address token, struct IStaking.TvlInfo tvlInfo)` internal
#### [](#StakingStore-_updateTargetLimit-NftId-)
`_updateTargetLimit(NftId targetNftId) → Amount limitAmount` internal
#### [](#StakingStore-createStake-NftId-NftId-address-Amount-)
`createStake(NftId stakeNftId, NftId targetNftId, address stakeOwner, Amount stakeAmount) → Timestamp lockedUntil` external
#### [](#StakingStore-stake-NftId-bool-bool-Seconds-Amount-)
`stake(NftId stakeNftId, bool updateRewards, bool restakeRewards, Seconds additionalLockingPeriod, Amount stakeAmount)` external
#### [](#StakingStore-unstake-NftId-bool-bool-Amount-)
`unstake(NftId stakeNftId, bool updateRewards, bool restakeRewards, Amount maxUnstakeAmount) → Amount unstakedAmount` external
#### [](#StakingStore-updateRewards-NftId-)
`updateRewards(NftId stakeNftId)` external
#### [](#StakingStore-restakeRewards-NftId-bool-)
`restakeRewards(NftId stakeNftId, bool updateRewards)` external
#### [](#StakingStore-claimRewards-NftId-bool-Amount-)
`claimRewards(NftId stakeNftId, bool updateRewards, Amount maxClaimAmount) → Amount claimedAmount` external
#### [](#StakingStore-getStakingReader--)
`getStakingReader() → contract StakingReader stakingReader` external
#### [](#StakingStore-getTargetManager--)
`getTargetManager() → contract ITargetLimitHandler targetLimitHandler` external
#### [](#StakingStore-exists-NftId-)
`exists(NftId stakeNftId) → bool` external
#### [](#StakingStore-getRequiredStakeBalance-NftId-bool-)
`getRequiredStakeBalance(NftId targetNftId, bool includeTargetTypeRequirements) → Amount requiredStakeAmount` public
#### [](#StakingStore-isStakeLocked-NftId-)
`isStakeLocked(NftId stakeNftId) → bool` public
Returns true iff current stake amount is still locked
#### [](#StakingStore-getStakeInfo-NftId-)
`getStakeInfo(NftId stakeNftId) → struct IStaking.StakeInfo stakeInfo` external
Returns the stake infos for the specified stake.
#### [](#StakingStore-getStakeTarget-NftId-)
`getStakeTarget(NftId stakeNftId) → NftId targetNftId` external
Returns the stake infos for the specified stake.
#### [](#StakingStore-getTargetInfo-NftId-)
`getTargetInfo(NftId targetNftId) → struct IStaking.TargetInfo targetInfo` external
Returns the target infos for the specified target.
#### [](#StakingStore-getLimitInfo-NftId-)
`getLimitInfo(NftId targetNftId) → struct IStaking.LimitInfo limitInfo` external
Returns the target limit infos for the specified target.
#### [](#StakingStore-getTvlInfo-NftId-address-)
`getTvlInfo(NftId targetNftId, address token) → struct IStaking.TvlInfo tvlInfo` external
Returns the tvl infos for the specified target.
#### [](#StakingStore-getTokenInfo-ChainId-address-)
`getTokenInfo(ChainId chainId, address token) → struct IStaking.TokenInfo tokenInfo` external
Returns the tvl infos for the specified target.
#### [](#StakingStore-hasTokenInfo-ChainId-address-)
`hasTokenInfo(ChainId chainId, address token) → bool` external
#### [](#StakingStore-getTargetSet--)
`getTargetSet() → contract NftIdSet targetNftIdSet` external
#### [](#StakingStore-_updateRewards-NftId-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-)
`_updateRewards(NftId stakeNftId, struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo) → Amount rewardIncreaseAmount` internal
#### [](#StakingStore-_restakeRewards-NftId-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-)
`_restakeRewards(NftId stakeNftId, struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo) → Amount restakeAmount` internal
#### [](#StakingStore-_stake-NftId-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-Seconds-Amount-)
`_stake(NftId stakeNftId, struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo, Seconds maxAdditionalLockingPeriod, Amount stakeAmount)` internal
#### [](#StakingStore-_claimRewards-NftId-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-Amount-)
`_claimRewards(NftId stakeNftId, struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo, Amount maxClaimAmount) → Amount claimAmount` internal
#### [](#StakingStore-_unstake-NftId-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-Amount-)
`_unstake(NftId stakeNftId, struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo, Amount maxUnstakeAmount) → Amount unstakedAmount` internal
#### [](#StakingStore-_setLastUpdatesToCurrent-struct-IStaking-StakeInfo-struct-IStaking-TargetInfo-)
`_setLastUpdatesToCurrent(struct IStaking.StakeInfo stakeInfo, struct IStaking.TargetInfo targetInfo) → Blocknumber lastUpdateIn` internal
#### [](#StakingStore-_setStakeLastUpdatesToCurrent-struct-IStaking-StakeInfo-)
`_setStakeLastUpdatesToCurrent(struct IStaking.StakeInfo stakeInfo) → Blocknumber lastUpdateIn` internal
### [](#StakingReader)
`StakingReader`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingReader.sol)
import "@etherisc/gif-next/contracts/staking/StakingReader.sol";
Functions
* \[`constructor(registry)`\]
* \[`initialize(stakingAddress, stakingStoreAddress)`\]
* \[`getRegistry()`\]
* \[`getStaking()`\]
* \[`getProtocolNftId()`\]
* \[`isTarget(targetNftId)`\]
* \[`targets()`\]
* \[`getTargetNftId(idx)`\]
* \[`getTargetNftId(stakeNftId)`\]
* \[`getStakeInfo(stakeNftId)`\]
* \[`getTargetInfo(targetNftId)`\]
* \[`getLimitInfo(targetNftId)`\]
* \[`getTvlInfo(targetNftId, token)`\]
* \[`getTokenInfo(chainId, token)`\]
* \[`isSupportedTargetType(targetType)`\]
* \[`getSupportInfo(targetType)`\]
* \[`getTargetLockingPeriod(stakeNftId)`\]
* \[`getTargetRewardRate(stakeNftId)`\]
* \[`getTargetMaxStakedAmount(targetNftId)`\]
* \[`getLockingPeriod(targetNftId)`\]
* \[`getRewardRate(targetNftId)`\]
* \[`getReserveBalance(targetNftId)`\]
* \[`getTotalValueLocked(targetNftId, token)`\]
* \[`getRequiredStakeBalance(targetNftId)`\]
* \[`getRequiredStakeBalance(targetNftId, includeTargetTypeRequirements)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
Initializable
* \[`Initialized(version)`\]
#### [](#StakingReader-constructor-contract-IRegistry-)
`constructor(contract IRegistry registry)` public
#### [](#StakingReader-initialize-address-address-)
`initialize(address stakingAddress, address stakingStoreAddress)` external
#### [](#StakingReader-getRegistry--)
`getRegistry() → contract IRegistry registry` external
#### [](#StakingReader-getStaking--)
`getStaking() → contract IStaking staking` external
#### [](#StakingReader-getProtocolNftId--)
`getProtocolNftId() → NftId protocolNftId` external
#### [](#StakingReader-isTarget-NftId-)
`isTarget(NftId targetNftId) → bool` external
#### [](#StakingReader-targets--)
`targets() → uint256` external
#### [](#StakingReader-getTargetNftId-uint256-)
`getTargetNftId(uint256 idx) → NftId` external
#### [](#StakingReader-getTargetNftId-NftId-)
`getTargetNftId(NftId stakeNftId) → NftId targetNftId` public
#### [](#StakingReader-getStakeInfo-NftId-)
`getStakeInfo(NftId stakeNftId) → struct IStaking.StakeInfo stakeInfo` external
#### [](#StakingReader-getTargetInfo-NftId-)
`getTargetInfo(NftId targetNftId) → struct IStaking.TargetInfo info` public
#### [](#StakingReader-getLimitInfo-NftId-)
`getLimitInfo(NftId targetNftId) → struct IStaking.LimitInfo info` public
#### [](#StakingReader-getTvlInfo-NftId-address-)
`getTvlInfo(NftId targetNftId, address token) → struct IStaking.TvlInfo info` public
#### [](#StakingReader-getTokenInfo-ChainId-address-)
`getTokenInfo(ChainId chainId, address token) → struct IStaking.TokenInfo info` public
#### [](#StakingReader-isSupportedTargetType-ObjectType-)
`isSupportedTargetType(ObjectType targetType) → bool` public
#### [](#StakingReader-getSupportInfo-ObjectType-)
`getSupportInfo(ObjectType targetType) → struct IStaking.SupportInfo info` public
#### [](#StakingReader-getTargetLockingPeriod-NftId-)
`getTargetLockingPeriod(NftId stakeNftId) → NftId targetNftId, Seconds lockingPeriod` external
Get the locking period that applies to the specified stake NFT ID.
#### [](#StakingReader-getTargetRewardRate-NftId-)
`getTargetRewardRate(NftId stakeNftId) → NftId targetNftId, UFixed rewardRate` external
Get the reward rate that applies to the specified stake NFT ID.
#### [](#StakingReader-getTargetMaxStakedAmount-NftId-)
`getTargetMaxStakedAmount(NftId targetNftId) → Amount maxStakedAmount` external
Get the max staked amount allowed for the specified target NFT ID.
#### [](#StakingReader-getLockingPeriod-NftId-)
`getLockingPeriod(NftId targetNftId) → Seconds lockingPeriod` external
Get the reward rate for the specified target NFT ID.
#### [](#StakingReader-getRewardRate-NftId-)
`getRewardRate(NftId targetNftId) → UFixed rewardRate` external
Get the reward rate for the specified target NFT ID.
#### [](#StakingReader-getReserveBalance-NftId-)
`getReserveBalance(NftId targetNftId) → Amount rewardReserveBalance` external
returns the current reward reserve balance for the specified target.
#### [](#StakingReader-getTotalValueLocked-NftId-address-)
`getTotalValueLocked(NftId targetNftId, address token) → Amount totalValueLocked` external
#### [](#StakingReader-getRequiredStakeBalance-NftId-)
`getRequiredStakeBalance(NftId targetNftId) → Amount requiredStakedAmount` external
#### [](#StakingReader-getRequiredStakeBalance-NftId-bool-)
`getRequiredStakeBalance(NftId targetNftId, bool includeTargetTypeRequirements) → Amount requiredStakedAmount` external
### [](#StakingService)
`StakingService`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingService.sol)
import "@etherisc/gif-next/contracts/staking/StakingService.sol";
Modifiers
* [`onlyStaking()`](#StakingService-onlyStaking--)
Functions
* \[`createInstanceTarget(targetNftId, initialLockingPeriod, initialRewardRate)`\]
* \[`setInstanceLockingPeriod(instanceNftId, lockingPeriod)`\]
* \[`setInstanceRewardRate(instanceNftId, rewardRate)`\]
* \[`setInstanceMaxStakedAmount(instanceNftId, maxStakingAmount)`\]
* \[`refillInstanceRewardReserves(instanceNftId, rewardProvider, dipAmount)`\]
* \[`withdrawInstanceRewardReserves(instanceNftId, dipAmount)`\]
* \[`createStakeObject(targetNftId, stakeOwner)`\]
* \[`pullDipToken(dipAmount, stakeOwner)`\]
* \[`pushDipToken(dipAmount, stakeOwner)`\]
* \[`approveTokenHandler(token, amount)`\]
* \[`setTotalValueLocked(targetNftId, token, amount)`\]
* \[`getDipToken()`\]
* \[`getTokenHandler()`\]
* \[`getStaking()`\]
* \[`_initialize(owner, data)`\]
* \[`_registerStaking(stakingAddress)`\]
* \[`_getDomain()`\]
Service
* \[`__Service_init(authority, registry, initialOwner)`\]
* \[`getDomain()`\]
* \[`getVersion()`\]
* \[`getRoleId()`\]
* \[`_getServiceAddress(domain)`\]
ReentrancyGuardUpgradeable
* \[`__ReentrancyGuard_init()`\]
* \[`__ReentrancyGuard_init_unchained()`\]
* \[`_reentrancyGuardEntered()`\]
Versionable
* \[`initializeVersionable(activatedBy, data)`\]
* \[`upgradeVersionable(data)`\]
* \[`_upgrade(data)`\]
Registerable
* \[`__Registerable_init(authority, registry, parentNftId, objectType, isInterceptor, initialOwner, data)`\]
* \[`isActive()`\]
* \[`getRelease()`\]
* \[`getInitialInfo()`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
AccessManagedUpgradeable
* \[`__AccessManaged_init(initialAuthority)`\]
* \[`__AccessManaged_init_unchained(initialAuthority)`\]
* \[`authority()`\]
* \[`setAuthority(newAuthority)`\]
* \[`isConsumingScheduledOp()`\]
* \[`_setAuthority(newAuthority)`\]
* \[`_checkCanCall(caller, data)`\]
ContextUpgradeable
* \[`__Context_init()`\]
* \[`__Context_init_unchained()`\]
* \[`_msgSender()`\]
* \[`_msgData()`\]
* \[`_contextSuffixLength()`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
IStakingService
* \[`LogStakingServiceProtocolTargetRegistered(protocolNftId)`\]
* \[`LogStakingServiceInstanceTargetRegistered(instanceNftId, initialLockingPeriod, initialRewardRate)`\]
* \[`LogStakingServiceRewardReservesIncreased(targetNftId, rewardProvider, dipAmount, newBalance)`\]
* \[`LogStakingServiceRewardReservesDecreased(targetNftId, targetOwner, dipAmount, newBalance)`\]
* \[`LogStakingServiceStakeCreated(stakeNftId, targetNftId, stakeOwner)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
IAccessManaged
* \[`AuthorityUpdated(authority)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#StakingService-onlyStaking--)
`onlyStaking()` modifier
#### [](#StakingService-createInstanceTarget-NftId-Seconds-UFixed-)
`createInstanceTarget(NftId targetNftId, Seconds initialLockingPeriod, UFixed initialRewardRate)` external
Creates/registers an on-chain instance staking target. Permissioned: Only instance service
#### [](#StakingService-setInstanceLockingPeriod-NftId-Seconds-)
`setInstanceLockingPeriod(NftId instanceNftId, Seconds lockingPeriod)` external
Set the instance stake locking period to the specified duration. Permissioned: Only instance service
#### [](#StakingService-setInstanceRewardRate-NftId-UFixed-)
`setInstanceRewardRate(NftId instanceNftId, UFixed rewardRate)` external
Set the instance reward rate to the specified value. Permissioned: Only instance service
#### [](#StakingService-setInstanceMaxStakedAmount-NftId-Amount-)
`setInstanceMaxStakedAmount(NftId instanceNftId, Amount maxStakingAmount)` external
Set the instance max staked amount to the specified value. Permissioned: Only instance service
#### [](#StakingService-refillInstanceRewardReserves-NftId-address-Amount-)
`refillInstanceRewardReserves(NftId instanceNftId, address rewardProvider, Amount dipAmount) → Amount newBalance` external
(Re)fills the staking reward reserves for the specified target using the dips provided by the reward provider. Permissioned: Only instance service
#### [](#StakingService-withdrawInstanceRewardReserves-NftId-Amount-)
`withdrawInstanceRewardReserves(NftId instanceNftId, Amount dipAmount) → Amount newBalance` external
Defunds the staking reward reserves for the specified target Permissioned: Only instance service
#### [](#StakingService-createStakeObject-NftId-address-)
`createStakeObject(NftId targetNftId, address stakeOwner) → NftId stakeNftId` external
Creates a new stake object for the specified target via the registry service. Permissioned: only the staking component may call this function
#### [](#StakingService-pullDipToken-Amount-address-)
`pullDipToken(Amount dipAmount, address stakeOwner)` external
Collect DIP token from stake owner. Permissioned: only the staking component may call this function
#### [](#StakingService-pushDipToken-Amount-address-)
`pushDipToken(Amount dipAmount, address stakeOwner)` external
Transfer DIP token to stake owner. Permissioned: only the staking component may call this function
#### [](#StakingService-approveTokenHandler-contract-IERC20Metadata-Amount-)
`approveTokenHandler(contract IERC20Metadata token, Amount amount)` external
Approves the staking token handler. Permissioned: only the staking component may call this function
#### [](#StakingService-setTotalValueLocked-NftId-address-Amount-)
`setTotalValueLocked(NftId targetNftId, address token, Amount amount)` external
Sets total value locked data for a target contract on a different chain. this is done via CCIP (cross chain communication)
#### [](#StakingService-getDipToken--)
`getDipToken() → contract IERC20Metadata dip` external
#### [](#StakingService-getTokenHandler--)
`getTokenHandler() → contract TokenHandler tokenHandler` external
#### [](#StakingService-getStaking--)
`getStaking() → contract IStaking staking` external
#### [](#StakingService-_initialize-address-bytes-)
`_initialize(address owner, bytes data)` internal
#### [](#StakingService-_registerStaking-address-)
`_registerStaking(address stakingAddress) → contract IStaking staking` internal
#### [](#StakingService-_getDomain--)
`_getDomain() → ObjectType` internal
### [](#StakingLib)
`StakingLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingLib.sol)
import "@etherisc/gif-next/contracts/staking/StakingLib.sol";
Functions
* \[`checkCreateParameters(stakingReader, targetNftId, dipAmount)`\]
* \[`_checkCreateParameters(stakingReader, targetNftId, dipAmount)`\]
* \[`checkStakeParameters(stakingReader, stakeNftId)`\]
* \[`checkUnstakeParameters(stakingReader, stakeNftId)`\]
* \[`checkTarget(stakingReader, targetNftId)`\]
* \[`checkAndGetStakingService(registry, release)`\]
* \[`checkDipAmount(stakingReader, targetNftId, dipAmount)`\]
* \[`calculateRewardIncrease(stakingReader, stakeNftId, rewardRate)`\]
* \[`calculateRewardAmount(rewardRate, duration, stakeAmount)`\]
* \[`getYearFraction(duration)`\]
#### [](#StakingLib-checkCreateParameters-contract-StakingReader-NftId-Amount-)
`checkCreateParameters(contract StakingReader stakingReader, NftId targetNftId, Amount dipAmount) → Timestamp lockedUntil` external
#### [](#StakingLib-_checkCreateParameters-contract-StakingReader-NftId-Amount-)
`_checkCreateParameters(contract StakingReader stakingReader, NftId targetNftId, Amount dipAmount) → Timestamp lockedUntil` internal
#### [](#StakingLib-checkStakeParameters-contract-StakingReader-NftId-)
`checkStakeParameters(contract StakingReader stakingReader, NftId stakeNftId) → UFixed rewardRate, Seconds lockingPeriod` public
#### [](#StakingLib-checkUnstakeParameters-contract-StakingReader-NftId-)
`checkUnstakeParameters(contract StakingReader stakingReader, NftId stakeNftId) → Seconds lockingPeriod` public
#### [](#StakingLib-checkTarget-contract-StakingReader-NftId-)
`checkTarget(contract StakingReader stakingReader, NftId targetNftId) → Seconds lockingPeriod` public
#### [](#StakingLib-checkAndGetStakingService-contract-IRegistry-VersionPart-)
`checkAndGetStakingService(contract IRegistry registry, VersionPart release) → contract IStakingService stakingService` public
#### [](#StakingLib-checkDipAmount-contract-StakingReader-NftId-Amount-)
`checkDipAmount(contract StakingReader stakingReader, NftId targetNftId, Amount dipAmount)` public
#### [](#StakingLib-calculateRewardIncrease-contract-StakingReader-NftId-UFixed-)
`calculateRewardIncrease(contract StakingReader stakingReader, NftId stakeNftId, UFixed rewardRate) → Amount rewardIncreaseAmount` public
#### [](#StakingLib-calculateRewardAmount-UFixed-Seconds-Amount-)
`calculateRewardAmount(UFixed rewardRate, Seconds duration, Amount stakeAmount) → Amount rewardAmount` public
#### [](#StakingLib-getYearFraction-Seconds-)
`getYearFraction(Seconds duration) → UFixed yearFraction` public
### [](#TargetManagerLib)
`TargetManagerLib`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/TargetManagerLib.sol)
import "@etherisc/gif-next/contracts/staking/TargetManagerLib.sol";
Functions
* \[`updateLockingPeriod(staking, targetNftId, lockingPeriod)`\]
* \[`updateRewardRate(staking, targetNftId, rewardRate)`\]
* \[`checkTargetParameters(registry, stakingReader, targetNftId, expectedObjectType, lockingPeriod, rewardRate)`\]
* \[`checkLockingPeriod(reader, targetNftId, targetType, lockingPeriod)`\]
* \[`checkRewardRate(reader, targetNftId, targetType, rewardRate)`\]
* \[`calculateRequiredDipAmount(tokenAmount, stakingRate)`\]
* \[`calculateStakingRate(dipToken, token, requiredDipPerToken)`\]
* \[`getMaxLockingPeriod()`\]
* \[`getDefaultLockingPeriod()`\]
* \[`getMinimumLockingPeriod()`\]
* \[`getMaxRewardRate()`\]
* \[`getDefaultRewardRate()`\]
* \[`toTargetKey(targetNftId)`\]
#### [](#TargetManagerLib-updateLockingPeriod-contract-IStaking-NftId-Seconds-)
`updateLockingPeriod(contract IStaking staking, NftId targetNftId, Seconds lockingPeriod) → Seconds oldLockingPeriod, struct IStaking.TargetInfo targetInfo` external
#### [](#TargetManagerLib-updateRewardRate-contract-IStaking-NftId-UFixed-)
`updateRewardRate(contract IStaking staking, NftId targetNftId, UFixed rewardRate) → UFixed oldRewardRate, struct IStaking.TargetInfo targetInfo` external
#### [](#TargetManagerLib-checkTargetParameters-contract-IRegistry-contract-StakingReader-NftId-ObjectType-Seconds-UFixed-)
`checkTargetParameters(contract IRegistry registry, contract StakingReader stakingReader, NftId targetNftId, ObjectType expectedObjectType, Seconds lockingPeriod, UFixed rewardRate)` external
#### [](#TargetManagerLib-checkLockingPeriod-contract-StakingReader-NftId-ObjectType-Seconds-)
`checkLockingPeriod(contract StakingReader reader, NftId targetNftId, ObjectType targetType, Seconds lockingPeriod)` public
#### [](#TargetManagerLib-checkRewardRate-contract-StakingReader-NftId-ObjectType-UFixed-)
`checkRewardRate(contract StakingReader reader, NftId targetNftId, ObjectType targetType, UFixed rewardRate)` public
#### [](#TargetManagerLib-calculateRequiredDipAmount-Amount-UFixed-)
`calculateRequiredDipAmount(Amount tokenAmount, UFixed stakingRate) → Amount dipAmount` public
#### [](#TargetManagerLib-calculateStakingRate-contract-IERC20Metadata-contract-IERC20Metadata-UFixed-)
`calculateStakingRate(contract IERC20Metadata dipToken, contract IERC20Metadata token, UFixed requiredDipPerToken) → UFixed stakingRate` public
#### [](#TargetManagerLib-getMaxLockingPeriod--)
`getMaxLockingPeriod() → Seconds maxLockingPeriod` public
#### [](#TargetManagerLib-getDefaultLockingPeriod--)
`getDefaultLockingPeriod() → Seconds maxLockingPeriod` public
#### [](#TargetManagerLib-getMinimumLockingPeriod--)
`getMinimumLockingPeriod() → Seconds minLockingPeriod` public
the minimum locking period is 24 hours
#### [](#TargetManagerLib-getMaxRewardRate--)
`getMaxRewardRate() → UFixed maxRewardRate` public
#### [](#TargetManagerLib-getDefaultRewardRate--)
`getDefaultRewardRate() → UFixed defaultRewardRate` public
#### [](#TargetManagerLib-toTargetKey-NftId-)
`toTargetKey(NftId targetNftId) → Key32 targetKey` public
### [](#StakingManager)
`StakingManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingManager.sol)
import "@etherisc/gif-next/contracts/staking/StakingManager.sol";
Functions
* \[`constructor(registry, targetHandler, stakingStore, tokenRegistry, initialOwner, salt)`\]
* \[`getStaking()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#StakingManager-constructor-address-address-address-address-address-bytes32-)
`constructor(address registry, address targetHandler, address stakingStore, address tokenRegistry, address initialOwner, bytes32 salt)` public
initializes proxy manager with service implementation
#### [](#StakingManager-getStaking--)
`getStaking() → contract Staking` external
### [](#StakingServiceManager)
`StakingServiceManager`[](https://github.com/etherisc/gif-next/blob/develop/contracts/staking/StakingServiceManager.sol)
import "@etherisc/gif-next/contracts/staking/StakingServiceManager.sol";
Functions
* \[`constructor(authority, registry, salt)`\]
* \[`getStakingService()`\]
ProxyManager
* \[`initialize(registry, implementation, data, salt)`\]
* \[`deploy(registry, initialImplementation, initializationData)`\]
* \[`deployDetermenistic(registry, initialImplementation, initializationData, salt)`\]
* \[`upgrade(newImplementation)`\]
* \[`upgrade(newImplementation, upgradeData)`\]
* \[`linkToProxy()`\]
* \[`getDeployData(proxyOwner, deployData)`\]
* \[`getUpgradeData(upgradeData)`\]
* \[`getProxy()`\]
* \[`getVersion()`\]
* \[`getVersionCount()`\]
* \[`getVersion(idx)`\]
* \[`getVersionInfo(_version)`\]
NftOwnable
* \[`_checkNftType(nftId, expectedObjectType)`\]
* \[`__NftOwnable_init(registry, initialOwner)`\]
* \[`linkToRegisteredNftId()`\]
* \[`getNftId()`\]
* \[`getOwner()`\]
* \[`_linkToNftOwnable(nftOwnableAddress)`\]
RegistryLinked
* \[`__RegistryLinked_init(registry)`\]
* \[`getRegistry()`\]
InitializableERC165
* \[`__ERC165_init()`\]
* \[`_initializeERC165()`\]
* \[`_registerInterface(interfaceId)`\]
* \[`_registerInterfaceNotInitializing(interfaceId)`\]
* \[`supportsInterface(interfaceId)`\]
Initializable
* \[`_checkInitializing()`\]
* \[`_disableInitializers()`\]
* \[`_getInitializedVersion()`\]
* \[`_isInitializing()`\]
Events
ProxyManager
* \[`LogProxyManagerVersionableDeployed(proxy, initialImplementation)`\]
* \[`LogProxyManagerVersionableUpgraded(proxy, upgradedImplementation)`\]
INftOwnable
* \[`LogNftOwnableNftLinkedToAddress(nftId, owner)`\]
Initializable
* \[`Initialized(version)`\]
#### [](#StakingServiceManager-constructor-address-address-bytes32-)
`constructor(address authority, address registry, bytes32 salt)` public
initializes proxy manager with service implementation
#### [](#StakingServiceManager-getStakingService--)
`getStakingService() → contract StakingService` external
[← shared](/gif-next/3.x/api/shared)
[type →](/gif-next/3.x/api/type)
---
# Architecture - Etherisc Docs
Architecture
============
[](#introduction)
Introduction
------------------------------
### [](#decentralized_insurance_protocol_dip)
Decentralized Insurance Protocol (DIP)
The Decentralized Insurance Protocol (DIP) enables the creation and management of decentralized insurance products. The protocol is designed to be flexible and extensible, allowing for the creation of a wide range of insurance products.
The protocol supports a multi-chain ecosystem to let users choose the chain that best fits their needs. The protocol is designed to be chain agnostic, allowing for the deployment of the protocol on any EVM compatible chain.
### [](#generalized_insurance_framework_gif)
Generalized Insurance Framework (GIF)
The Generalized Insurance Framework (GIF) is a set of smart contracts that implement the Decentralized Insurance Protocol (DIP). The main Goal of the GIF is to support its users in creating and managing decentralized insurance products as efficitiently and safe as possible.
GIF users should be able to focus on their use case specific business logic. GIF takes care of the use case independent heavy lifting like managing policies, claims, payouts, managing collateral in pools, etc.
The GIF itself is a highly modularized and flexible infrastructure that can be deployed to any EVM compatible chain. Most contracts of the GIF will already be deployed and are ready to be used by the users.
[](#multi_chain_setup)
Multi-Chain Setup
----------------------------------------
### [](#overview)
Overview
For each supported chain a chain specific GIF setup is deployed. To link all chains together a global registry is deployed on mainnet. This global registry then holds the links to all chain specific registries as shown in the diagram below.

### [](#global_registry)
Global Registry
The global registry is deployed on mainnet can be understood as the directory and entry point for the entire protocol ecosystem.
The global registry contains entries for all protocol relevant objects on mainnet and a chain registry entry for each supported chain in the ecosystem. At the same time the global registy plays the role of the mainnet chain registry.
### [](#chain_registries)
Chain Registries
On each chain supported by the protocol, a chain registry is deployed. A chain registry contains entries for all protocol relevant objects on that specific chain. These entries hold basic metadata for each registered object. Each registry entry is backed by an NFT that defines the ownership of the object.
[](#single_chain_setup)
Single-Chain Setup
------------------------------------------
### [](#overview_2)
Overview
The GIF setup on any specific chain always consists of a registry and staking modules, services and instances as shown in the diagram below.

### [](#registry)
Registry
Registries have already been introduced in the text above. As mentioned above, a registry is the central entry point for all protocol objects on a specific chain. Registries also serve as the trusted source for protocol object information and relationships between different objects.
### [](#components)
Components
Once the instance is created it can be used to deploy a set of components contracts that are required to implement the use case. The framework provides template contracts for products, distributions, oracles, and pools that need to be extended to implement the actual business logic.
### [](#staking)
Staking
The staking module is used to manage the DIP that are staked by users to either the protocol itself or to an instance that is registered as a staking target.
### [](#services)
Services
Services implement the generic insurance business logic of the protocol. They also manage the communication between components, instances, the registry, and the staking module.
Each service is associated with a specific GIF release and has a defined domain scope, such as "Registry" or "Policy". Services are stateless and operate solely on the state of the module contracts they are involved with. Additionally, service contracts may interact with other service contracts. It is important to note that all service contracts are designed to be upgradeable, allowing for bug fixes and minor enhancements.
Breaking changes in any service, instance or component template contract would imply the deployment of a new GIF release.
[](#registry_2)
Registry
------------------------
### [](#overview_3)
Overview
The registry maintains a complete and reliable record of all relevant protocol objects. The registry module plays a critical role in the overall architecture of the protocol, facilitating the seamless integration and interoperability of the different instances, components, services and staking.
By centralizing object information and their relationships, registries ensure consistency and integrity across the protocol ecosystem. They provide a reliable foundation for the decentralized insurance protocol, enabling efficient and secure management of insurance products.
Registries are non-upgradeable. Once deployed, the registry contracts remain unchanged to maintain the integrity of the protocol’s object ecosystem. In addition, registry entries are immutable and cannot be altered or deleted once they have been written to the registry. This ensures that the protocol’s object ecosystem remains consistent and reliable.
### [](#registry_objects)
Registry Objects
Protocol objects are stored in the registry in the form of registry objects. A registry object is a simple data structure that holds the following properties.
* NFT ID: A protocol unique ID
* Parent NFT ID: A pointer to the parent object in the registry
* Object Type: The type of the object (registry, service, instance, product, policy, etc)
* Object Address: The contract address for contract objects
The table below lists the different object types that can be stored in the registry.
| Object | Comments |
| --- | --- |
| Protocol | The object representing the protocol itself |
| Registry | Registry contracts |
| Staking | The staking contract for the chain |
| Service | Service contracts linked to the chain registry. In addition to storing the service contract address, services also carry the information regarding the release and the domain of the service. |
| Instance | Instance contracts linked to the chain registry |
| Product | Product contracts linked to an instance |
| Policy | Policy object linked to a product contract |
| Distribution | Distribution contracts linked to an instance |
| Distributor | Distributor object linked to a distribution contract |
| Oracle | Oracle contracts linked to an instance |
| Pool | Pool contracts linked to an instance |
| Bundle | Bundle object linked to a pool contract |
| Stake | Stake object linked to its target object. Stakes are the only objects that can have a parent object with a non unique parent type. Currently, stakes are allowed to have a parent of type protocol or instance. |
Except for the protocol object each object in the registry is linked to a parent object. Every object has its defined parent object. The only exception are stake objects which may either have the protocol object or an instance object as its parent object.
The diagram below shows the registry object hierarchy.

The global registry is the parent object for all chain registries. On Mainnet the global registry may also serve as a parent object for service, staking and instance objects on mainnet.
### [](#contracts)
Contracts
The registry module diagram below provides an overview of the registry related contracts of a GIF deployment.

Contracts and their responsibilities are outlined below.
| Contract | Responsibility |
| --- | --- |
| GIF Admin (Actor) | The account with the GIF Admin role initiates and confirms new GIF releases. |
| GIF Manager (Actor) | An account with a GIF Manager role deploys and registers service contracts of new GIF releases. Manages token white listing. |
| ChainNft | Mints and manages all NFTs related to the objects stored in the registry. Only the registry contract may call state changing functions on this contract. |
| Registry | Stores entries for all protocol relevant objects on this chain. |
| ReleaseRegistry | Keeps track of all deployed major releases so far. Manages deployment of new releases. |
| TokenRegistry | Manages whitelisting of supported ERC20 tokens per major release. |
| RegistryAdmin | Central authorization for all core contracts (resistry module and staking module) and all service contracts from all major releases. |
| RegistryService | A registry service contract from a specific GIF release. Registry service contracts are authoriezd to register new objects with the registry. |
| Other Services | TODO remove this component also remove dashed line beween registry and registry service. |
| Dip | The DIP token deployed outside of the GIF deployment. The DIP token is always registered with the Token registry. |
[](#instances)
Instances
------------------------
### [](#overview_4)
Overview
Instances provide the central context to create and operate actual protection/insurance use cases. The recommendation is to create a new instance for each new use case.
The purpose of an instance is to manage all necessary aspects and components to implement a use case. An instance is responsible for the handling of the following aspects:
* Registration of the product, distribution, oracle and pool components needed to implement the use case.
* Managing the lifecycle and the data of all business objects involved in the use case
* Managing the data necessary for the bookkeeping of all fees, commissions, and funds related to the use case.
* Authorization management for all linked components and services
### [](#stakeholders)
Stakeholders
#### [](#instance_owner)
Instance Owner
The instance owner is represented by the account that holds the instance NFT. Instances can be created by any account using the instance service through the `createInstance()` function. The initial instance owner is the account that created the instance.
The instance owner is in charge of the following tasks:
* Upgrading of the instance reader when necessary
* Locking / unlocking linked components
* Managing component owner roles for the instance
* Managing authorization for all linked components
* Defining the instance staking parameters
#### [](#product_owner)
Product Owner
Product owners are defined as accounts/contracts that have been granted the product owner role by the instance owner. Only accounts/contracts with the product owner role may register a product component with the instance.
Additional tasks may be defined through the use case specific implementation of the component.
#### [](#distribution_owner)
Distribution Owner
Distribution owners are defined as accounts/contracts that have been granted the distribution owner role by the instance owner. Only accounts/contracts with the distribution owner role may register a distribution component with the instance.
Additional tasks for distribution owners may be defined through the use case specific implementation of the component.
#### [](#oracle_owner)
Oracle Owner
Oracle owners are defined as accounts/contracts that have been granted the oracle owner role by the instance owner. Only accounts/contracts with the oracle owner role may register a oracle component with the instance.
Additional tasks for oracle owners may be defined through the use case specific implementation of the component.
#### [](#pool_owner)
Pool Owner
Pool owners are defined as accounts/contracts that have been granted the pool owner role by the instance owner. Only accounts/contracts with the pool owner role may register a pool component with the instance.
Additional tasks for pool owners may be defined through the use case specific implementation of the component.
#### [](#use_case_specific_stakeholders)
Use Case Specific Stakeholders
The instance owner may introduce use case specific stakeholders through additional use case specific roles.
### [](#business_objects)
Business Objects
#### [](#components_2)
Components
Components are the building blocks of a use case implementation that is managed in the context of the instance. For every component registered with the instance the instance manages a component object.
The component objects holds component meta data such as its name, the product NFT Id it is related to, token, tokenHandler, and its wallet address. Once a component is registered with the instance only the wallet address may be updated.
Component objects are stored with the InstanceStore contract.
#### [](#products)
Products
Products are the principal components of a use case implementation. The use case specific implementation defines what products are available and how they are structured.
For products registered with the instance an additional product object is created. This product object holds the information of the linked distribution and pool component as well as all pricing relevant fees for all involved components.
Product objects are stored with the InstanceStore contract.
#### [](#pools)
Pools
Pools are the risk capital providers of a use case implementation.
For pools registered with the instance an additional pool object is created. This pool object holds pool meta data such as the maximal allowed balance amount for the pool, its collateralization level or the retention level of the pool.
Pool objects are stored with the InstanceStore contract.
#### [](#roles)
Roles
Roles are named IDs that are managed by the InstanceAdmin. Roles may be granted to any accounts/contracts.
The instance can list all registered roles and the current set of accounts/contracts that have been assigned a specific role.
Role objects are stored with the InstanceAdmin contract.
#### [](#targets_and_functions)
Targets and Functions
Targets are named contract addresses that are managed by the InstanceAdmin. The instance can list all registered targets.
For each registered target named functions may be defined and linked to the necessary role. The function of this target contract can then only be called/executed when the caller has been granted the necessary role.
The instance can list all registered targets together with the all related functions that are linked to a specific role.
Target and function objects are stored with the InstanceAdmin contract.
### [](#creating_a_new_instance)
Creating a new Instance
New instances can only be created through the instance service contract. To enforce this behaviour only the instance service is authorized to register instances with the registry through the registry service.
This process ensures that it is not possible to deploy and register malicious instances when using the framework. The process also ensures that the inital wiring and authorization of a newly created instance is done completely and correctly.
Instance creation is the responsibility of the `InstanceService`. New instances are created using the function createInstance(). This function creates a complete set of instance contracts via cloning the contracts of its "master instance". This "master instance" is part of the deployment of every GIF release.
The principal steps of the instance creation process are outlined below: g 1. A new `InstanceAdmin` contract with its `AccessManagerCloneable` contract is cloned from the master instance.
1. A new `Instance` contract is cloned from the master instance. This step includes the cloning of the supportint `InstanceReader`, `InstanceStore` and `RiskSet` and `BundleSet` contracts from the same master instance.
2. The newly cloned instance is registered with the registry via the `RegistryService`.
3. The instance is registered as a staking target with staking through the `StakingService`.
4. Instance creation is completed by setting up the inital instancde authorization through the `InstanceAdmin`.

### [](#authorization_management)
Authorization Management
The instance owner is responsible for granting and revoking of the predefined component owner roles. The instance owner may also define additional use case specific roles. The instance owner can also extend the authorization to use case specific supporting contracts.
The instance owner only interacts with the `Instance` contract although the actual authorization is managed by the `InstanceAdmin` contract. The available instance functions for authorization management are listed in the table below.
| | |
| --- | --- |
| Function | Description |
| `createRole()` | Creates a new use case specific role. |
| `grantRole()` | Grants a role to an account/contract. |
| `revokeRole()` | Revokes a role from an account/contract. |
| `createTarget()` | Creates a new use case specific contract target. |
| `setTargetFunctionRole()` | Links a function of a target contract to a role. |
| `setTargetLocked()` | Locks/unlockes a target contract. A locked target contract may no longer accept state changing transactions. |
### [](#staking_management)
Staking Management
When an instance is created it is automatically registered as a staking target with the staking module. It is then in the responsibility of the instance owner to define the staking parameters for the instance. For this purpose the instance provides the functions listed in the table below.
| | |
| --- | --- |
| Function | Description |
| `setStakingLockingPeriod()` | Sets the locking period for DIP stakes for the instance. Once an instance stake is created by a staker the staked DIP tokens cannot be unstaked before the locking period has passed. Only the instance owner may set the locking period. |
| `setStakingRewardRate()` | Sets the reward rate for DIP stakes for the instance in the form of an annual percentage rate. Only the instance owner may set the reward rate. |
| `refillStakingRewardReserves()` | Refills the reward reserves of the instance. The reward reserves are used to pay out rewards to stakers. This function is not limited to the instance owner but callable by any account/contract. |
| `withdrawStakingRewardReserves()` | Withdraws the reward reserves for this instance. Only the instance owner may withdraw the reward reserves. |
### [](#contracts_2)
Contracts
The instance module diagram below provides an overview of the instance related contracts.

Contracts and their responsibilities are outlined below.
| Contract/Account | Responsibility |
| --- | --- |
| Instance Owner (Actor) | Contract/Account that is the holder of the instance NFT that represents this particular instance. The instance NFT is linked to the instance contract and registered in the registry. |
| Instance | Central instance contract that manages instance authorization and references to other instance module contracts. |
| InstanceReader | Provides all read access functions to instance related data. This includes data access for all components linked to the instance. |
| InstanceStore | Stores all instance related data like managed components, polices, bundles, distributors etc. |
| BundleSet | Manages the set of active policies for each bundle. |
| RiskSet | Manages the set of active policies for each risk. |
| InstanceAdmin | Central authorization for all instance and linked component contracts as well as all service contracts that need write access to instance data. |
| Services … | The set of services that interact with the instance module. |
[](#components_3)
Components
----------------------------
The term component is used as a summary term for use case specific product, distribution, oracle, and pool contracts/modules. Components provide the shared functionality of the different types of components that does not depend on any specifc use case.
### [](#overview_5)
Overview
Components are are always linked to a specific instance. The term "component" covers four distinct types of components that together implement the actual use case specific business logic of a concrete use case.
The diagram below shows the architecture of an exemplary "My Product" use case. TODO remove or update module packages in diagram

Moudle contracts and their responsibilities are outlined below.
| Contract/Account | Responsibility |
| --- | --- |
| Product Owner (Actor) | Contract/Account that is the holder of the product NFT that represents this particular product. The NFT is linked to the product contract and registered in the registry. |
| Distribution Owner (Actor) | Contract/Account that is the holder of the distribution NFT that represents this particular distribution contract. The NFT is linked to the distribution contract and registered in the registry. |
| Oracle Owner (Actor) | Contract/Account that is the holder of the oracle NFT that represents this particular oracle contract. The NFT is linked to the oracle contract and registered in the registry. |
| Pool Owner (Actor) | Contract/Account that is the holder of the pool NFT that represents this particular pool contract. The NFT is linked to the pool contract and registered in the registry. |
| My Product | Does not contain actual contracts, It represents the use case specific collection of component moudules that are required to implement and operate the use case. |
| Product Module | The use case specific product contract that manages policies, claims and payouts. The product contract is based on product template contract provided by the framework. The module may includes additional supporting contracts. A Pool module always needs to be linked to a pool module. Links to a distribution module and oracle modules are optional |
| Distribution Module | The use case specific distribution contract that manages distributors, referral codes and policy sales. The distribution contract is based on distribution template contract provided by the framework. The module may includes additional supporting contracts. A distribution module is always linked to a single product module |
| Oracle Module | One or more use case specific oracle modules. Each oracle module contains an oracle contract that manages oracle requests and responses that connect the product to real world (off-chain) data. The oracle contracts are based on a oracle template contract provided by the framework. The modules may includes additional supporting contracts. Any oracle module is always linked to a single product module. |
| Pool Module | The use case specific pool contract that manages bundles which in turn provide the risk capital of the use case. The pool contract is based on pool template contract provided by the framework. The module may includes additional supporting contracts. A pool moudle is always linked to a single product module |
| Instance Module | The instance module that links all component modules and also holds the data related to the component modules. During operation the linked instance module manages the data related to all relevant business objects like policies, claims, payouts, bundles, distributors, etc. |
| Registry Module | When setting up a new use case, component modules are registerd with the instance module and the registry module. For each registered component module an associated registry entry is created and a component module specific NFT is minted. Additional registry entries and NFTs are created during the operation of the use case. In this phase NFTs are also minted for most business relevant objects such as policies or bundles. |
### [](#component_principles)
Component Principles
1. Components come in four different types: products, distributions, oracles, and pools.
2. Components need a use case specific implementation. The framework provides templates for each component type that need to be extended and customized accordingly.
3. Components may be upgradeable or non-upgradeable. Only the actual implementation of the component determines if the component is upgradeable or not.
4. Every component needs to be registered with exactly one instance.
5. To register a component the registrar account needs to be authorized via the instance admin contract.
6. Every component contract is also registered with the registry and comes with an associated NFT.
7. Component ownership is defined as the owner of the NFT associated with the componet contract.
8. Component owners may lock and unlock their components. A locked component may no longer accept state changing transactions. Note that this behaviour needs to be ensured by the use case specific implementation of the component contracts.
9. Component owners may withdraw collected component fees.
10. Every component contract has a defined ERC20 token that represents the principal token for the specific use case. All components that together implement a specific use case must share the same ERC20 token.
11. Every component contract comes with its own wallet address. The default wallet address is the contract address itself. Depending on the component type this wallet holds ERC20 token that represent fees, commissions, or funds.
12. Every component contract has its own token handling contract that manages token transfers to and from the component contract.
13. All business object data defined by the framework are stored with the instance contract and not the component contracts.
14. For all framework related business logic components may only interact through services with other components or the linked instance contract.
15. Authorization for interaction of components with framework services is managed by the instance admin contract.
16. Use case specific component implementations should follow these patterns and not store business or security relevant data in the component contracts and not directly interact with any other components.
17. Authorization for communication with use case specific supporting contracts should also be managed by the instance admin contract.
### [](#wallet_management)
Wallet Management
Every component contract has its own wallet address. As mentioned above the default wallet address is the component contract address.
To increase flexibility for use case specific implementations the component owner may also define an external wallet address. For example a gnosis safe or a multisig wallet. In such cases it is the responsibility of the external wallet owner to maintain adequate allowances from the external wallet to the components token handling contract.
### [](#token_management)
Token Management
Every component contract has its own token handling contract that manages token transfers to and from the component contract.
Moving tokens form an account to the component wallet requires a corresponding allowance from that account to the token handling contract. Moving tokens from the component wallet to a receiving account also requires an allowance from the component wallet to the token handling contract.
To illustrate this setup consider a premium payment. To buy a policy, a policy holder first needs to create an approval for the token handling contract of the policy component over the premium amount. The buying transaction then calculates the associated fees, commissions, and net premium amount. The token handler of the product component then executes the transfer of the product fee to the product wallet, the transfers of the distribution fee and commission to the distribution wallet, and the transfer of the pool fee, the bundle fee and the net premium to the pool wallet.
In the case of a payout the token handler of the pool component transfers the payout amount from the pool wallet to the policy holder.
Other uses component token handlers include fee withdrawals for component owners, commission withdrawals and risk capital collection from investors.
### [](#contracts_3)
Contracts
The component diagram below provides the overview of the component contract hierarchy.

The table below provides additional contract specific information.
| Contract | Responsibility |
| --- | --- |
| `Initializable` | provides the initialization mechanism for upgradeable components. It is up to the use case specific implementation to take advantage of this capability. |
| `(I)RegistryLinked`
(shared) | Base interface and implementation for contracts that are linked to the registry. Any contract that needs to query or interact with the registry is derived from this base contract. This base class is also derived from OpenZeppelin’s `Initializable` to support upgradeability and contract cloning. |
| `(I)NftOwnable`
(shared) | Base interface and implementation for contracts which define ownability via the owner of the NFT corresponding to a contract registered in the registry. The linking to the NFT is done via the `linkToRegisteredNftId` function that looks up the NFT ID in the registry using the contract address. |
| `(I)Registerable`
(shared) | Base interface and implementation for contracts that need to be registered with the registry. Registerable contracts provide all necessary information to be registered via its `getInitialInfo` function. |
| `AccessManagedUpgradeable` | As components might need to be upgradeable they also need to derive from OpenZeppelin’s upgradeable base contract. |
| `(I)Component`
(shared) | Base interface and implementation for all component contracts. |
| `TokenHandler`
(shared) | Component specific token transfer manager contract. |
| `IERC20Metadata` | Use case specific principal ERC20 token. |
[](#product_components)
Product Components
------------------------------------------
### [](#overview_6)
Overview
The product component forms the central part of a use case implementation. It is responsible for the management of risk, application, policy, claim, and payout business objects.
Via the services shown in the diagram below, the product component stores its business objects data with the instance module and interacts with the other components that jointly implement the use case.

The responsibilities of the services interacting with the product component are described in detail in the business processes section below.
### [](#stakeholders_2)
Stakeholders
Product owners and policy holders are the relevant stakeholder accounts for product components.
#### [](#product_owner_2)
Product Owner
The product owner is responsible for managing the variable product parameters including the pool and processing fees.
The product owner is represented by the account that holds the product NFT. The initial owner is specified via the `getInitialInfo()` function of the product component
#### [](#policy_holder)
Policy Holder
As all policies created by the framework have an associated NFT a policy holder is defined as the current holder of the NFT that represents the policy.
When no specific beneficiary is defined for a claim/payout the payout recipient is the policy holder.
### [](#business_objects_2)
Business Objects
#### [](#overview_7)
Overview
The business objects relevant to the product component and their relations are shown in the diagram below. To indicate the use case specific nature of products the product component is named "MyProduct"in the diagram.

* A product may defines one or more risks.
* For each application/policy a policy object is created.
* Policy objects are always linked to a single product component.
* Each policy object is also linked to a single risk object.
* A policy may has from zero to many claim objects.
* A claim object may has from one to many payout objects.
More information regarding these business objects is provided in the sections below.
#### [](#risks)
Risks
Risks are product specific and have unique IDs that represent an insurable event. Examples of insurable events are a delayed flight, a flood in a specific area and time window, or a failed harvest in a specific area and growing season.
All policies linked to the same risk will share the claim/payout characteristics.
Risk objects have a simple lifecycle that indicates if the risk is active, paused or archived. Once risks are no longer relevant from a business perspective, risks can be paused or archived. Paused risks may be reactivated at a later point in time. Once a risk is in archived state it can no longer be reactivated.
New policies can only be created for risks in active state.
#### [](#application_and_policies)
Application and Policies
Applications and Policies are two terms for the same business object in two different livecyle states. An application is also registered in the registry and represented by an NFT that is used to define the application/policy holder as the current owner of the NFT.
An application is the request for a policy and holds all information necessary to specify the covered risk, the policy holder, the premium, and the sum insured (maximum payout amount). Applications can be created by any account that is authorized to interact with the product component.
A policy is an application that has been approved by the product component and collateralized by locking capital in the pool component. The policy business object also holds summary information about the policy like the number of open claims and the total payout amount.
The framework does not enforce a specific policy management process. It is therefore up to the use case specific implementation to define the final process that defines who can create applications, how applications are approved or rejected etc.
The framework does however enforce a policy lifecycle that is illustrated below.

The table below provides additional information about the policy lifecycle.
| State | Description |
| --- | --- |
| Applied | The initial state of a new policy business object. In this state the object is called an application. |
| Declined | The application has not been accepted by the product component. The business object will never become a policy. This is a terminal state and no policy will be created. |
| Revoked | The application has been declared irrelevant by the application holder. The business object will never become a policy. This is a terminal state and no policy will be created. |
| Collateralized | The application has been accepted by the product component and the necessary collateral has been locked in the pool component linked to the product component. |
| Active
(virtual) | Active is a virtual state that indicates that the policy is in a state where claims can be created. Active can be considered as a sub state of state Collateralized. A policy may only be in state active if the current block timestamp has reached or passed the activatedAt property of the policy and has not yet been expired. |
| Expired
(virtual) | Expired is a virtual state that indicates that the policy has reached a state where claims can no longer be made. Payouts may still be created for confirmed claims even though the policy is expired. Expired is a sub state of state Collateralized. A policy becomes expired if the current block timestamp has reached or passed the expiredAt property of the policy. |
| Closed | A policy can be closed once has been expired and all its confirmed claims have been payed out in full. A policy may also be closed once the total of the processed payout amounts has reached the sum insured amount. TODO: decide if the policy should be explicityl expired first of if it should be sufficient to set the closedAt property. |
#### [](#claims)
Claims
A claim represents a request for a payout in the context of a specific policy. Claim creation is only possible for policies in state active.
The framework does not enforce a specific claim management process. It is therefore up to the use case specific implementation that defines who can create claims, how claims are approved or rejected etc.
As in the case of policies the framework does enforce a claim lifecycle. The table below provides information for the available claim lifecycle states.
| State | Description |
| --- | --- |
| Submitted | The initial state of a newly created claim business object. Claims can only be submitted for policies in active state. A submitted claim must also specify a claim amount. |
| Declined | The claim has been rejected. No associated payout object(s) will be created and no payout(s) will be made. This is a terminal state. |
| Revoked | The claim has been declared irrelevant and no claim evaluation needs to be made. As for declined claims no associated payout object(s) will be created and no payout(s) will be made. This is a terminal state and no policy will be created. |
| Confirmed | The claim has been accepted and includes a decision about the claim amount. The framework ensures that the sum total of confirmed claim amounts of a policy does not exceed the sum insured amount of the same policy. For confirmed claims one or more payout objects linked to the claim object may now be created and payouts can then be executed. |
| Closed | A confirmed claim can only be closed once the associated payout object(s) have been processed and the payout(s) have been made. |
#### [](#payouts)
Payouts
Confirmed claims may have one or more associated payout objects. This implies that each payout object is linked to a specific claim object and indirectly to a specific policy object.
The framework does not enforce a specific payout management process. It is therefore up to the use case specific implementation that defines who can create, cancel or execute payouts. As in the case of claims, the framework enforces a payout lifecycle. The framework futher ensures that the sum total of all processed payout amounts does never exceed the the confirmed claim amount and that the associated claim can only be closed the full claim amount has been paid out.
The table below describes the payout lifecycle states.
| State | Description |
| --- | --- |
| Expected | The initial state of a newly created payout business object. Payout objects can only be created for claim objects in confirmed state and as long as the sum total of the payout amounts does not exceed the claim amount. |
| Cancelled | The payout has been cancelled. A payout can only move to the cancelled state from the expected state. For cancelled payouts no payout will ever be made. This is a terminal state. |
| Executed | The payout has been executed and the specified token amount has been transferred to the payout recipient. This is a terminal state. |
### [](#business_processes)
Business Processes
#### [](#product_registration)
Product Registration
To register a product component with the linked instance module two conditions need to be met. The product component needs to be deployed by the future product owner. The product owner needs to be authorized by the instance admin contract via the product owner role.
Product registration is the responsibility of the `ComponentService`. The principal registration process steps can be summarized as follows:
1. Registration of the new component contract with the `Registry` and minting of the product NFT by the `ChainNft`
2. Setup component authorization at the `InstanceAdmin` via the `InstanceService`
3. Creation of a component specific `TokenHandler` and the component object in the `InstanceStore`
4. Creation of the product object in the `InstanceStore`. The product objects holds the information of the linked distribution and pool component as well as all pricing releevant fess for all involved components.
The actual registration can then be performed by executing the `register()` function of the products `Component` base contract. A sequence diagram of the product registration process is shown below.

The same process flow is used to register distribution, oracle and pool components. These processes only differ in the last step where component specific objects are created in the `InstanceStore`.
#### [](#pricing)
Pricing
Product pricing is the responsibility of the `PricingService`. The pricing process steps can be summarized as follows:
1. Obtain the use case specific net premium amount from the product object itself.
2. Obtain the product and bundle information using the `InstanceReader`. The product information provides all fees specifications for the product and the pool. The bundle information also provides the bundle fee specification.
3. Calculate fixed and variable fee amounts for the product and the pool component.
4. Calculate the fee and commission amounts for the distribution component. The commission amount depends on the availability and validity of the referral code used for the policy application.
5. For each component wallet calculate the inidividual amounts that would result from a policy sale. The sum of all these component specific amounts is equal to the premium amount.

#### [](#application_creation)
Application Creation
Application creation is the responsibility of the `ApplicationService`. The application creation process steps can be summarized as follows:
1. Create and register a new registry object with the registry. The resulting NFT is used to define ownership of the application.
2. Create the application object in the `InstanceStore`.

#### [](#policy_creation)
Policy Creation
Policies are created from applications. Policy creation is the responsibility of the `PolicyService`.
The policy creation process steps can be summarized as follows:
1. Given the NFT Id of a new application object the policy creation is started by the `PolicyService` function `createPolicy`.
2. The policy service calls the `PoolService` function `lockCollateral` which in turn tasks the `BundleService` to lock the necessary collateral amount. The bundle service also links the new policy to the `BundleSet` that is collateralized by the specified bundle NFT Id. This step ends with updating the total locked value for the linked instance with the `Staking` contract.
3. The policy service calls the function `calculatePremium` of the `PricingService`. This ensures that for premium collection the correct pricing process is involved. See above for the description of this pricing process.
4. In turn the policy service triggers the calculation of all resulting fees, commission and net premiums for the policy sale in the product, distribution and pool components. The resulting balance updates are stored in the `InstanceStore`.
5. The actual token transfers from the policy holder to the involved component wallets according to the above calculated fee, commission and net premium amounts.
6. In case the policy holder is a contract that implements the `IPolicyHolder` interface the callback function `policyActivated` is called.

#### [](#policy_expiry)
Policy Expiry
A policy expires when the current block timestamp has reached or passed the expiredAt property of the policy.
The initial `expiryAt` property is when activating a policy and is calculated as the current block timestamp plus the policy lifetime set in the application phase of the policy. In a typical policy lifecycle this expiry property will not be changed and the policy will expire at the end of the policy period.
There are two exceptions to this rule. The first exception is enforced by the framework and cannot be changed: When the total payout amount of a policy has reached the sum insured amount of the policy. In this case the expiryAt timestamp is set to the block timestamp that corresponds to the confirmation of the claim amount that leads to reaching the sum insured amount.
The second exception is use case specific and needs to be explicitly implemented by the product component. The product implementation may decide to expire the policy at any time that falls inbetween the current block timestamp and the previously set expiryAt timestamp. The expiry process is the responsibility of the `PolicyService`.

#### [](#policy_closure)
Policy Closure
Once a policy has expired and all claims have been payed out in full a policy can be closed. Closing a policy is the responsibility of the `PolicyService`.

#### [](#claims_handling)
Claims Handling
#### [](#payout_handling)
Payout Handling
### [](#contracts_4)
Contracts
[](#distribution_components)
Distribution Components
----------------------------------------------------
### [](#overview_8)
Overview
The distribution component manages the process of selling policies. This includes the management of distributors (brokers) and referral codes associated with distributors. A distribution component is always linked to a single product component and cannot be shared between multiple product components.
Via the services shown in the diagram below, the distribution component stores its business objects data with the instance module.

The responsibilities of the services interacting with the distribution component are described in detail in the business processes section below.
### [](#stakeholders_3)
Stakeholders
Distribution owners and distributors are the relevant stakeholder accounts for distribution components.
#### [](#distribution_owner_2)
Distribution Owner
The distribution owner is responsible for managing the distribution parameters including the distribution fee and the minimum distribution owner fee.
The distribution owner is represented by the account that holds the distribution NFT. The initial owner is specified via the `getInitialInfo()` function of the distribution component.
#### [](#distributors)
Distributors
Distributors are linnked accounts that support selling policies. Distributors can provide referral codes to incentivice prospects to buy policies at a discounted rate. For their role/work distributors receive a commission that is also linked to the referral code.
To act as a distributor is typically not implemented permissionless but requires possession of a distributor NFT. The use case specific implementation of the distribution component then defines the process to gain this role. Once an account qualifies to become a distributor the distribution component creates a new NFT that is transferred to the newly entitled account.
### [](#business_objects_3)
Business Objects
#### [](#distributor_types)
Distributor Types
Distributor types represent objects that define the degrees of freedom distributors have in referrals. A distributor type may define the minimum and maximum discount rates a distributor that can be used when creating a referral code.
#### [](#distributors_2)
Distributors
As mentioned in the stakeholder section, a distributor can be understood as a role with associated properties that is linked to an account. The linking is achieved through an NFT that represents a specific distributor. The distributor object then defines the properties of a distributor that also includes its distributor type.
#### [](#referral_codes)
Referral Codes
Referral codes are simple strings that must be unique in the context of a distribution component.
The referral object then links the referral code to a specific distributor and defines the discount rate that is associated with the referral code. The referral object also holds additional properties, such as the maximum number of uses of the referral code and an expiry date.
### [](#business_processes_2)
Business Processes
#### [](#distributor_type_creation)
Distributor Type Creation
#### [](#distributor_creation)
Distributor Creation
#### [](#referral_code_creation)
Referral Code Creation
### [](#fee_and_commissions_management)
Fee and Commissions Management
### [](#contracts_5)
Contracts
[](#oracle_components)
Oracle Components
----------------------------------------
### [](#overview_9)
Overview
The oracle component manages the interactions of the product cluster with the "real" worls. An oracle component is always linked to a single product component and cannot be shared between multiple product components.
Via the services shown in the diagram below, the oracle component stores its business objects data with the instance module.

The responsibilities of the services interacting with the oracle component are described in detail in the business processes section below.
### [](#stakeholders_4)
Stakeholders
Oracles only have oracle owners as stakeholders. In contrast to the other component types, the oracle owner does not need to manage any framework relevant variable parameters.
The oracle owner is represented by the account that holds the oracle NFT. The initial owner is specified via the `getInitialInfo()` function of the oracle component.
### [](#business_objects_4)
Business Objects
#### [](#requests)
Requests
Requests are objects that define which oracle component is requested to fetch which from the off-chain world. The request object also holds the parameters to store the response data and the information to which function of which component the response data has to be routed once it becomes available.
#### [](#responses)
Responses
Reponses are not technically independent business objects but only update data fields of response objects that are waiting for response data.ß
### [](#business_processes_3)
Business Processes
#### [](#request_creation)
Request Creation
#### [](#response_handling)
Response Handling
### [](#contracts_6)
Contracts
[](#pool_components)
Pool Components
------------------------------------
### [](#overview_10)
Overview
The pool component manages the funds required to collateralize policies. A pool component is always linked to a single product component and cannot be shared between multiple product components.
Via the services shown in the diagram below, the pool component stores its business objects data with the instance module.

The responsibilities of the services interacting with the pool component are described in detail in the business processes section below.
### [](#stakeholders_5)
Stakeholders
Pool owners and bundle owners are the relevant stakeholder accounts for pool components.
#### [](#pool_owner_2)
Pool Owner
The pool owner is responsible for managing the variable pool parameters including the pool fee, tha staking fee and the performance fee and the pool’s maximum balance amount.
The pool owner is represented by the account that holds the pool NFT. The initial owner is specified via the `getInitialInfo()` function of the pool component
#### [](#bundle_owner)
Bundle Owner
Bundle owners are accounts that have staked product specific tokens to the pool of a product cluster. These tokens are then used to collateralize policies.
A Bundle owner is responsible to manage the bundle fee and funding of its bundle. Bundle owners may also pause and resume their bundle. Paused bundles may no longer be used to collateralize policies.
### [](#business_objects_5)
Business Objects
#### [](#pools_2)
Pools
The pool object stores the properties of the pool that is implemented in the pool component. The individual properties are described in the table below.
| Property | Description |
| --- | --- |
| `maxBalanceAmount` | The maximum amount of project tokens the pool is allowed to manage at any time.
The default is not to restrict the maximum balance amount. |
| `bundleOwnerRole` | The required role for an account to create a new bundle. Setting this to a non public role ensures that only authorized accounts can create new bundles.
The default role is the public role. |
| `isInterceptingBundleTransfers` | Ensures the pool receives a callback when a bundle is transferred to a new bundle owner. To illustrate this property consider a this property in combination with the bundle owner role to ensure that only authorized accounts can receive a bundle.
The default is not to intercept bundle transfers. |
| `isExternallyManaged` | Externally managed pools only use bundles for book keeping and do not collect tokens from bundle owners when creating new bundles or staking to bundles. Instead, it is the responsibility of the pool owner to ensure proper funding of the pool with tokens.
The default for pools is not to be externally managed. |
| `isVerifyingApplications` | Verifying pools require the bundle service to execute a callback to function asdfasf of the pool component when the bundle is asked to collateralize a new application. This allows for the implementation of custom logic to verify and approve the application during collateralization.
The default behaviour is not to verify applications. |
| `collateralizationLevel` | Defines the multiplicator to be used when calculating the required collateral to match the sum insured of a policy.
The default collateralization level value is 1,0. |
| `retentionLevel` | Specifies the percentage of the calculated collateral amount that is to be held by the pool itself. Setting the retention level to less than 1,0 implies that the pool component implementation will need to provide the remaining collateral amount throug an external funding mechanism.
The default retention level value is 1,0 to avoid the requirement of an external funding mechanism. |
#### [](#bundles)
Bundles
A Bundle object is always linked to exactly one pool and represents the book keeping unit that ensures that risks and rewards of a bundle owner are correctly calculated and assigned to the bundle owner.
Bundle objects have additional properties that define the lifetime of the bundle and set the bundle fee that is used to collect a part of the premium to incentivice the bundle owner to stake tokens to the bundle.
### [](#business_processes_4)
Business Processes
#### [](#bundle_creation)
Bundle Creation
#### [](#bundle_locking_and_unlocking)
Bundle Locking and Unlocking
#### [](#bundle_staking_and_unstaking)
Bundle Staking and Unstaking
#### [](#bundle_expiry)
Bundle Expiry
### [](#fee_management)
Fee Management
### [](#contracts_7)
Contracts
[](#staking_2)
Staking
----------------------
### [](#overview_11)
Overview
The protocl currently provides two options for staking the DIP protocol token.
The first option is protocol staking where a DIP holder directly stakes DIP token to the protocol. The staker receives a reward in the form of DIP tokens to incentivize the participation in the protocol. In the future staking to the protocol will be required to actively participate in the governance of the protocol. The reward rate, locking period and reserves are managed by the DIF as the protocol owner.
The second option is instance staking where DIP tokens are staked to a specific instance. Instance staking is required to enable the operation of the instance in relation to the total value locked by that instance. The instance owner may decide to stake the required DIP tokens from its own funds or incentivice other DIP holders to stake to the instance. When an instance owner decides to invite the community to stake to the instance the instance owner is responsible for setting the reward rate, the locking period and providing the reward reserves. The instance owner also has the possibility to cap the total amount of DIP that can be staked to the instance in relation to the total locked value of the instance.
These two staking options are managed by the staking module and the staking service.
### [](#business_objects_6)
Business Objects
#### [](#targets)
Targets
Staking is always linked to a specific target that needs to be registered in both the registry and the staking module. In the current release two stake target types are supported. The protocol target is used for protocol staking and the instance target is used for instance staking.
The protocol target is registered with the staking module during the initial protocol deployment on each supported chain. Instance targets are automatically registered with the staking module when a new instance is created.
#### [](#stakes)
Stakes
A stake represents a specific amount of DIP tokens that is staked to a registered target and is initially locked for a specific period of time. Every stake is also registered with the registry an backed by an NFT that represents the stake and defines the ownership of the stake.
Only the owner of a stake may unstake or restake the stake to a different target. As the ownership is defined by the NFT the current owner of a stake may sell the stake NFT to another account. This transfer of ownership can be done at any time which allows selling a stake NFT even during the time when the stake is still locked.
### [](#business_processes_5)
Business Processes
#### [](#target_management)
Target Management
Creating the protocol target and the instance target is does not need an explicit interaction of any stakeholder.
Setting the reward rates and loking period for protocol staking is the responsibility of the staking owner. The staking owner is also responsible for refilling the reward reserves.
Setting the reward rates, locking period, reward reserves and total stake cap for instance staking is the responsibility of the instance owner. The instance owner may also refill the reward reserves.
#### [](#stake_management)
Stake Management
### [](#contracts_8)
Contracts
The staking module diagram below provides an overview of the registry related contracts of a GIF deployment.

Contracts and their responsibilities are outlined below.
| Contract | Responsibility |
| --- | --- |
| StakingReader | Provides all read access functions to staking related data. |
| StakingStore | Stores all staking related data like staked DIPs per staker and target, available staking targets, total locked value per target staked DIPs per target. |
| Staking | The central staking contract that implements to upgradeable business logic for staking. |
| StakingService | A release specific service contract that is authorized to create new stakes and manage existing stakes. |
| PoolService | Informs the staking contract about changes in the total locked value (TVL) amounts of the instances. |
| RegistryAdmin | Central authorization for all core contracts (resistry module and staking module) and all service contracts from all major releases. |
[](#logging)
Logging
--------------------
### [](#overview_12)
Overview
Logging is one of the key feature of the framework and ensures the transparency and traceability of all business processes. As described below complete and accurate logs are crucial for compliance assurance, data integrity and accuracy, audit trail for accountability, and legal and forensic evidence.
**Compliance Assurance** Depending on the use case this is a mandatory requirement to demonstrate how the operation of the product adheres to legal and regulatory standards by providing a clear, indisputable record of all transactions, modifications.
**Data Integrity and Accuracy** Complete logs also enable interested parties to ensure that all financial and operational data is accurate and unaltered. This is crucial to maintain the trust of external stakeholder trust.
**Audit Trail for Accountability** Complete and accurate logs serve as an audit trail that details who did what and when
**Legal and Forensic Evidence** In cases of disputes or litigation, logs can serve as evidence. Complete and accurate logging ensures that the evidence is credible and can be used in legal proceedings.
### [](#general_principles)
General Principles
1. Logging of complete token transfer history: This includes all actual token transfers related to the framework, such as the NFT linked to protocol objects, the product token, and the DIP token.
2. Logging of complete balance history: This tracks all token balances related to the framework, allowing stakeholders to keep track of which account holds how many tokens at any given time.
3. Logging of complete trace through the lifecycle of every business object: This provides a record of the context and reason behind every change to a business object, as well as related token balances and transfers.
4. Business objects have either NFT IDs that are registerd in a registry and are unique over the the complete protocol ecosystem (e.g. Policy NFT ID) or are only unique in the context of such a NFT ID (e.g. Claim ID which is only unique per policy).
5. Business objects have a property `lastUpdatedIn` that refers to the blocknumber this business object has been last updated in. Events that refer to changes in these business objects include this property to allow to assemble a logging trace through the complete lifecycle of the objecet.
6. Log events are emitted at the end of state changing functions. Should the function interact with contracts outside of the framework, the log event is emitted before the external call. This applies to token transfers, calls to components and interceptor calls of the `ChainNft` contract.
7. Logging event names star with the prefix "Log" and are derived from the contract name that emits the log event. Example: `LogRegistryAdminGifAdminRoleSetUp`. The contract name used for the event might also be derived from the base contract that emits the event. Example: `LogAccessAdminRoleGranted`.
### [](#sources_and_events)
Sources and Events
#### [](#core_contract_sources)
Core Contract Sources
**ChainNft** Minting and transfers of NFTs for protocol objects. Interceptor Calls where applicable
**Registry** Registration of new protocol objects. Including object type, parent NFT ID, and initial owner.
**RegistryAdmin** Every action that has an impact on authorization. Creating Roles, Targets, and setting function level authorizations.
**ReleaseRegistry** Creating and activation of new releases and pausing/unpausing releases by GIF Admin. Preparation of new release and service registration by GIF Manager.
**TokenRegistry** Registration of new tokens. Activation/deactivation of tokens. Activation/deactivation of tokens per release.
**StakingStore** StakingRate changes. Staking target creation and target management regarding reward rates and locking periods. Stake creation, stake restaking, stake unstaking. Any staking and reward balance changes. Any token transfers related to staking.
#### [](#release_contract_sources)
Release Contract Sources
**ReleaseAdmin** Every action that has an impact on authorization. As in the case of the RegistryAdmin.
**Service** All state changing functions emit logs for every business object involved the reason for the change. All state chaning functions emit logs to report the completion of the function. TODO decide if state chaning functions should also emit logs to indicate the start of the function.
#### [](#instance_contract_sources)
Instance Contract Sources
* Instance
* InstanceStore
* InstanceAdmin
* BundleSet/RiskSet
* Components
#### [](#what_to_log)
What to Log
Any changes to a balances, a token transfer, and a business object change under the control of the framework.
* Fees, Commissions, Rewards, etc
Changes to Business Objects
* Business process: contract/function?
* Actor: Address that triggered the change through and instance, components, services, registry and staking
* Object Id: Business object involved in the transaction, parent object id if object id not unique on its own
* Business object state change, if any
* Addtional properties that provide insight into the reason behind the change
* Pointer to the previous change of this specific business object (blocknumber)
[](#authorization)
Authorization
--------------------------------
### [](#overview_13)
Overview
Autorization is a key concept in the GIF. Authorization is organized per supported chain and implemented in access admin contracts using role based access control. Role based access control involves roles, targets and functions level authorization.
Roles can be considered as lables or IDs that can be assigned (granted) to accounts or removed (revoked) from accounts. **Accounts** can either be externally owned accounts or contract accounts. The set of accounts that have a specific role is called the role members.
The term **Targets** is used for contracts for which function level authorization is managed by an access admin contract. That particular access admin contract is then called the authority of the target contract.
**Function Level Authorization** defines which fuctions of a target may be executed through which role. For each authorized function of a target the required role to access it is defined. Only a single role can be specified per function and only members of that role (both contracts and externally owned accounts) may then execute the function.
### [](#access_admin)
Access Admin
Access admin contracts manage explicit lists of named targets, roles and functions that are granted to these roles. It also provides view functions that allow to enumerate all available roles, current role members and all granted functions for every managed target.
The implementation of the access admin contract is based on OpenZeppelin’s `AccessManagerUpgradeable` and `AccessManagedUpgradeable` contracts.
The access admin contract extends the OpenZeppelin functionality by providing named roles, targets and functions and by providing the capability to enumerate all current role members and all granted functions for every managed target.
The access admin contract is the base contract for two specialized admin contracts. Per supported chain there is a registry admin contract and for each instance there is an instance admin contract.
### [](#registry_admin)
Registry Admin
The registry admin contract is the central contract that controls access to the registry, to staking as well as interactions between service contracts.
In the case of services the registry admin maintains access to service functions per major release in the sense that a service of a specific major release may only interact with services of the same major release.
### [](#instance_admin)
Instance Admin
For each instance an individual instance admin contract exits. This instance admin is used to manage authorizations for the interactions between the instance and all its linked components with all linked services.
### [](#upgrading_contracts)
Upgrading Contracts
Authorization for upgrading upgradeable contracts is a special case. Every upgradeable contract in GIF comes with its own proxy manager contract. Only this proxy manager contract may be used to upgrade an upgradeable contract. And only the owner of an upgradeable contract may execute an upgrade via this proxy manager contract.
The ownership of an GIF relevant upgradeable contract is defined via its NFT as recorded in the chain registry.
Upgradeability relies on OpenZeppelin’s `TransparentUpgradeableProxy` and `ProxyAdmin` contracts.
[](#release_management)
Release Management
------------------------------------------
### [](#overview_14)
Overview
GIF releases follow semantic versioning, which includes major, minor, and patch releases. The major version number is incremented whenever there are breaking changes that could potentially disrupt existing functionality or compatibility.
For every major releases, a consistent set of upgradeable service contracts are deployed and registered with the registry. For non-breaking changes the existing service contracts are upgraded in place. The staking module is independently upgradeable and may be upgraded at any time. The registry module is non-upgradeable and is capable of serving multiple major releases simultaneously. Instance modules are non-upgradeable and directly linked to the service contracts of the same major release.
Adding a new major release is guarded by role based authorization including two roles, a GIF Admin role and the GIF Manager role.
### [](#core_deployment)
Core Deployment
The core deployment sets up the registry and the staking modules and includes all the wiring between the contracts needed for actual relese deployment. For each supported chain a core deployment is the required first step.
For the registry module deployments the contracts Registry, ChainNft, TokenRegistry, and RegistryAdmin are deployed and initialized. Where neceesary these contracts are linked to the registry admin contract that manages all authorization for both the registry and the staking module.
On mainnet the **Regsitry** contract is deployed and initialized with two entries, one for the protocol object and one for global registry. On any other chain the initial setup includes an additional entry for the chain registry.
The registry istelf deployes the **ChainNFT** contract that will hold NFT representations of all protocol relevant objects on this chain.
The **TokenRegistry** is deployed and initialized with the DIP token as staking token.
The **RegistryAdmin** contract is deployed intialized with the GIF Admin role and the GIF Manager role.
* The necessary authorizations are put in place to allow the GIF Admin and GIF Manager roles to deploy the first major release.
* For the whitelisting of tokens the GIF Manager role is granted the necessary authorizations.
* For release deployment the release registry contract is authorized to register new service contracts with the registry.
* Regstry services (for all releases) are granted access to register objects with the registry contract.
* Staking services (for all releases) are granted access to the staking contract.
* Pool services (for all releases) are granted access to the staking contract to update the total value locked in instances.s
For the staking module deployment the contracts StakingReader, StakingStore, StakingManager and Staking are deployed and initialized. The staking contract is also registerd with the registry.
### [](#release_deployment)
Release Deployment
The release deployment is the second and final GIF deployment step to a specific chain. For each supported chain a release deployment is required. A release deployment to a new chain will only include the deployment of the latest major release. Initially this will be the GIF v3 release. In the future new major releases should be deployed on all chains that are actively supported by the protocol.
A release deployment consist of the deployment and authorization of a release specific and consistent set of service contracts. As the service authorization is restricted to other services of the same release, services are assigned release specific roles. Service authorization is managed by the registry admin contract and defines which service fuction may be called by which other service.
The process of a release deployment invlovles the GIF Admin and the GIF Manager roles. The GIF Admin role represents the principal owner of the protocol and GIF Manager role is the role that is authorized to deploy and register the service contracts with the release registry.
| Step | Role | Action | Comment |
| --- | --- | --- | --- |
| 1 | GIF Admin | `createNextRelease` | Initiates the deployment of the next major relase, sets the release registry contract into the state where release deployment is enabled. |
| 2 | GIF Manager | `prepareNextRelease` | Lets the release manager provide the authorization specification for the new release. This includes the ordered list of service domains relevant to the release. |
| 3 | GIF Manager | `registerService`
n times, once for each service contract. | The deployed release service contracts are registered with the release registry in the same order as defined in the authorization specification. |
| 4 | GIF Admin | `activateNextRelease` | After verifying the release deployment the GIF Admin can activate the new release. |
[← Overview](/gif-next/3.x/)
[Documentation Howto →](/gif-next/3.x/howto-documentation)
---