Giter Site home page Giter Site logo

cardano-foundation / cf-java-rewards-calculation Goto Github PK

View Code? Open in Web Editor NEW
19.0 14.0 1.0 3.25 MB

This java project is used to calculate the rewards of the Cardano blockchain. It aims to be both an edge case documentation and formula implementation.

License: MIT License

Java 94.19% JavaScript 3.81% HTML 2.00%
calculation cardano java pool reserve rewards treasury

cf-java-rewards-calculation's Introduction

Cardano Rewards Calculation ๐Ÿงฎ

Tests Coverage Release Publish Report conventionalcommits License Discord

This project is aims to target multiple goals. First of all, it tries to re-implement the cardano ledger rules for calculating the ADA pots (Treasury, Reserves, Rewards, Deposits, Utxo, Fees), as well as the rewards for stake pool operators and delegators. The second goal is to use this implementation to validate the rewards calculation of the Cardano blockchain by providing a different implementation of the ledger specification. The third goal is to provide a library that can be used in other project (such as yaci-store) to serve the rewards data independently of DB Sync. Last but not least, this project could also be used to understand the influence of protocol parameters and the flow of ADA through an interactive report.

๐Ÿงช Test Reports

To ensure the stability and reliability of this project, unit tests have been implemented. By clicking on the link below, you can access the detailed test report. We also generate for each version of this project calculation reports. These reports are generated by the unit tests and contain the calculation results compared to the actual values.

๐Ÿ“ˆ Treasury Calculation Report ๐Ÿ“Š Coverage Report

flowchart
    A[Total Transaction Fees <br />at Epoch n] --> B[Total Reward Pot <br />at Epoch n]
    B --> | treasuryGrowthRate | C[Treasury]
    B --> | 1 - treasuryGrowthRate | D[Stake Pool Rewards Pot <br />at Epoch n]
        subgraph ADA_POTS[" "]
        D --> | Unclaimed Rewards | E["ADA Reserves<br /> (monetary expansion) <br /> Started at ~14B ADA"]
        E --> | monetaryExpandRate * Performance of all Stake Pools | B
        C --> F[Payouts e.g. for <br />Project Catalyst]
        D --> | Rewards Equation<br /> for Pool 1 | G[Stake Pool 1]
        D --> | ewards Equation<br /> for Pool 2 | H[Stake Pool 2]
        D --> I[...]
        D --> | Rewards Equation<br /> for Pool n | J[Stake Pool n]
        J --> | margin & minPoolCost | K[Operators]
        J --> | rewards | L[Delegators]
        D --> | Rewards going to<br /> de-registered<br /> stake addresses | C
        L <--> | Stake Key Registrations + <br /> Deregistrations | M[Deposits]
        K <--> | Stake Pool Registrations + <br /> Deregistrations | M
        M --> | Unclaimed Refunds for Retired Pools | C
        end

    style A fill:#5C8DFF,stroke:#5C8DFF
    style B fill:#5C8DFF,stroke:#5C8DFF
    style C fill:#1EC198,stroke:#1EC198
    style D fill:#5C8DFF,stroke:#5C8DFF
    style E fill:#1EC198,stroke:#1EC198

    style F fill:#F6C667,stroke:#F6C667
    style G fill:#F6C667,stroke:#F6C667
    style H fill:#F6C667,stroke:#F6C667
    style I fill:#F6C667,stroke:#F6C667
    style J fill:#F6C667,stroke:#F6C667

    style ADA_POTS fill:#f6f9ff,stroke:#f6f9ff
Loading

๐Ÿค“ Interesting Facts

While the flowchart above shows the calculation of the Ada pots in general, there are some more aspects that need to be considered:

  • The point in time ๐Ÿ•‘. The reward calculation starts at slot (4 * 2160) / 0.05) = 172800 (48h) each epoch. Before the Babbage era, accounts that were de-registered before this point in time were not considered for the rewards calculation.
    This means that the rewards for the de-registered stake addresses are not considered in the rewards calculation. Those rewards were not distributed and went therefore back to the reserves. Accounts that deregistered after this point in time, but before the end of the epoch, were considered for the rewards calculation. But as it is not possible to send rewards to a de-registered stake address, the rewards went back to the treasury.
  • At the Allegra hard fork, the (pre-Shelley) bootstrap addresses were removed from the UTxO and the Ada contained in them was returned to the reserves.
  • There was a different behavior (pre-Allegra): If a pool reward address had been used for multiple pools, the stake account only received the reward for one of those pools and did also not get any member rewards. This behavior has changed in mainnet epoch 236 with the Allegra hard fork. Now, the stake account receives the rewards for all pools (including member rewards).
  • Transaction fees and a part of the reserve is used to build the total reward pot. It is often mentioned that the monetary expansion rate (protocol parameter) is used to calculate the part coming from the reserves. While this is true, the actual calculation is a multiplication of the monetary expansion rate and the performance of all stake pools eta. Eta is the ratio of the blocks produced by pools in an epoch and the expected blocks (432000 slots per epoch / 20 sec per block = 21600). With beginning of Shelly the blocks were produced by OBFT nodes and not by pools. Therefore, the performance of all stake pools would be 0. The decentralization parameter d has been introduced to slightly increase the amount of expected blocks produced by pools. In the time when d was above 0.8 eta was set to 1.0. d decreased over time from 1.0 to 0.0 and disappeared completely with the Vasil hard fork.
  • The pool deposit is currently 500 Ada. This deposit will be returned (on the next epoch boundary) to the pool reward address when the pool is retired. However, if the deposit could not be returned (e.g. because the pool reward address is de-registered), the deposit will be added to the treasury instead.
  • Pool updates override pool deregistrations. This means that if a pool is updated before the end of the epoch, the pool will not be retired and the deposit will not be returned.

๐Ÿš€ Getting Started

You can use this project as a library in your own project. The library is available through maven central, or you can clone the repository and run the tests or build the library yourself.

Maven

<dependency>
    <groupId>org.cardanofoundation</groupId>
    <artifactId>cf-rewards-calculation</artifactId>
    <version>0.13.0</version>
</dependency>

Make sure to have Java 17 installed and run the following commands:

git clone https://github.com/cardano-foundation/cf-java-rewards-calculation.git
cd cf-java-rewards-calculation
./mvnw clean test

๐Ÿ“ฆ Usage

In the near future you can use the calculation part of this repository as a library in your own project as it will be accessible through maven central.

For now the structure of the repository is divided in two parts:

While the calculation package is used as a pure re-implementation of the ledger specification, the validation package is used to get the needed data (e.g. registration/deregistration certificates, epoch stakes, etc.) from the data provider and execute the calculation. Furthermore, the validation package is used to compare the calculated values with the actual values using DB Sync as ground truth.

Data Provider

The pool rewards calculation and also the treasury calculation requires a data provider to perform the calculation. This repository offers different data providers and also an interface if you want to add your own provider. The following data providers are available:

Data Fetcher

The data fetcher is used to fetch the data from the data provider and put it into local json files. These files can be used to perform the calculation using the JSON Data Provider. The following data fetchers are available:

To make the application fetching the data, create an .env file with the following content in the validation resources folder:

SPRING_PROFILES_ACTIVE=db-sync

RUN_MODE=fetch
OVERWRITE_EXISTING_DATA=false
DATA_FETCHER_START_EPOCH=<start-epoch>
DATA_FETCHER_END_EPOCH=<end-epoch>
DATA_FETCHER_SKIP_VALIDATION_DATA=<true|false>

POSTGRES_USER=<username>
POSTGRES_PASSWORD=<password>
POSTGRES_DB=cexplorer

JSON_DATA_SOURCE_FOLDER=/path/to/your/rewards-calculation-test-data

Note

๏ธ The actual rewards data will also be fetched when setting DATA_FETCHER_SKIP_VALIDATION_DATA=false, but it is only used from the validator and not within the calculation itself.`

Data Plotter

The data plotter is used to generate the report. The following data plotters are available:

To use the application to make the report, create an .env file with the following content in the validation resources folder:

SPRING_PROFILES_ACTIVE=json
RUN_MODE=plot
JSON_DATA_SOURCE_FOLDER=/path/to/your/rewards-calculation-test-data

๐Ÿซก Roadmap

  • Enhance reporting and add values for the other pots as well. Display the flow of Ada within an epoch
  • Add a /docs folder containing parsable Markdown files to explain MIR certificates and edge cases
  • Provide a library through maven central to use the calculation in other projects
  • Find out the root cause of the difference between the actual rewards and the calculated rewards beginning with epoch 350
  • Include MIR certificates
  • Calculate member and operator rewards
  • Add deposits and utxo pot
  • Calculate unclaimed rewards that need to go back to the reserves
  • Put rewards to unregistered stake addresses into the treasury

๐Ÿ“– Sources

cf-java-rewards-calculation's People

Contributors

cleanerm5 avatar fabianbormann avatar github-actions[bot] avatar nemo83 avatar satran004 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

satran004

cf-java-rewards-calculation's Issues

[๐Ÿš€ Feature]: Multi Network Support

๐Ÿš€ The feature and your motivation

Currently, there is no option or configuration to select a network other than mainnet. To test upcoming protocol changes, it would make sense to test against a local Cardano testnet (e.g., yaci-devkit) or other public testnets (sanchonet/preview/preprod). Therefore, a refactoring of some constants (such as the first Shelley epoch) would be necessary.

Alternatives

No response

Additional context

No response

[๐Ÿš€ Feature]: Add reserves pot calculation

๐Ÿš€ The feature and your motivation

The reserves pot calculation is currently still missing and needs to be implemented for all epochs, to implement eventually all ada pots calculations.

Alternatives

No response

Additional context

No response

[๐Ÿž Bug]: UTXO pot calculation is sometimes 4 Lovelace off

Is there an existing issue for this?

  • I have searched the existing issues

Current (incorrect ๐Ÿ™ˆ) Behavior

For some epochs the UTXO pot calculation is 4 or -4 Lovelace off.
image

For the other epochs the formula utxoPot = utxoFromPreviousEpochPot - deposits - fees + withdrawals; seems to work pretty well.

With the other pot calculations we already prove that deposits and fee are aligned with their adapots table. So the issue must most probably come from the withdrawals table or some rule from the protocol that hasn't been implemented yet.

Expected Behavior (what you should have seen ๐ŸŽ‰)

No response

Steps To Reproduce

  1. Run the UTXO test in the tests folder

Environment

- OS:all
- Java JDK: all

Anything else?

No response

[๐Ÿ‘ท Task]: Move the test data to an S3 bucket and remove it from the actual repository

Is there an existing issue for this?

  • I have searched the existing issues

Task description ๐Ÿ”จ๐Ÿ”ง

Even if the data used by the JSON data provider is aggregated and less than the data in DB Sync, it is growing and growing over time. It makes sense to remove this test data from the repository.

  • Move the test data to an S3 bucket
  • Provide a how to fetch the data
  • Include the data folder in the .gitignore
  • Remove those folders from the git history as well to reduce the disk size of this project
  • Change the report generation and test pipeline to fetch the data on-the-fly from the bucket

Anything else?

No response

[๐Ÿš€ Feature]: Provide information about the actual percentage of the total rewards pot going into the treasury per epoch

๐Ÿš€ The feature and your motivation

With the current report, we provide the information about the calculated and the actual treasury value. Another interesting measure would be including the actual treasury cut 0.2 * totalRewardsPot and the amount of Lovelace being added on top of this value due to ledger rules such as PoolReap etc.

Alternatives

No response

Additional context

No response

[๐Ÿ‘ท Task]: Add a report for the utxo, fees and deposits pot as well

Is there an existing issue for this?

  • I have searched the existing issues

Task description ๐Ÿ”จ๐Ÿ”ง

Currently we only provide a report for the treasury calculation, but with finishing the utxo, deposits and fees pot calculation, we should also provide a report for them as well.

Anything else?

No response

[๐Ÿš€ Feature]: Make the calculation accessible via maven central

๐Ÿš€ The feature and your motivation

Currently it is not possible to use this repository within other java-based projects like yaci-store or ledger-sync.

To overcome this situation, the rewards calculation part should be put on maven central allowing other java-based projects to reuse the calculation methods. We need to make sure not to include all the codebase, as this could bring unnecessary overhead to those projects.

Alternatives

Providing an API would also allow other projects to make use of the rewards calculation, but they would need to run the project somewhere aside to their application, which is maybe not wanted. We should anyways wrap this service in an api.

Additional context

No response

[๐Ÿž Bug]: The treasury calculation output is different from the actual treasury value starting at epoch 350 (close before Babbage era)

Is there an existing issue for this?

  • I have searched the existing issues

Current (incorrect ๐Ÿ™ˆ) Behavior

With the beginning of epoch 215, it seems that more ADA has been added to the treasury than calculated by the current treasury calculation. It probably comes from the fact, that (from the spec) remainders from the rewards pot should go into the treasury as well as member rewards going to unregistered stake accounts.

Expected Behavior (what you should have seen ๐ŸŽ‰)

0 Lovelace difference between calculation and the actual treasury value provided by the ada_pots table from dbsync.

Steps To Reproduce

  1. Run the TreasuryCalculationTest in the test folder with a range from 208-460 (epochs)

Environment

- OS: any
- Java JDK: any

Anything else?

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.